diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeqDatabase.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeqDatabase.py new file mode 100644 index 0000000000000000000000000000000000000000..32cbd85aae7d67f82e647b09c2a1c40e37b2310f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/BioSeqDatabase.py @@ -0,0 +1,841 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2016 copyright by Peter Cock. All rights reserved. +# Revisions 2009 copyright by Cymon J. Cox. All rights reserved. +# Revisions 2013-2014 copyright by Tiago Antao. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org +"""Connect with a BioSQL database and load Biopython like objects from it. + +This provides interfaces for loading biological objects from a relational +database, and is compatible with the BioSQL standards. +""" + +import os + +from . import BioSeq +from . import DBUtils +from . import Loader + +_POSTGRES_RULES_PRESENT = False # Hack for BioSQL Bug 2839 + + +def open_database(driver="MySQLdb", **kwargs): + """Load an existing BioSQL-style database. + + This function is the easiest way to retrieve a connection to a + database, doing something like:: + + from BioSQL import BioSeqDatabase + server = BioSeqDatabase.open_database(user="root", db="minidb") + + Arguments: + - driver - The name of the database driver to use for connecting. The + driver should implement the python DB API. By default, the MySQLdb + driver is used. + - user -the username to connect to the database with. + - password, passwd - the password to connect with + - host - the hostname of the database + - database or db - the name of the database + + """ + if driver == "psycopg": + raise ValueError( + "Using BioSQL with psycopg (version one) is no " + "longer supported. Use psycopg2 instead." + ) + + if os.name == "java": + from com.ziclix.python.sql import zxJDBC + + module = zxJDBC + if driver in ["MySQLdb"]: + jdbc_driver = "com.mysql.jdbc.Driver" + url_pref = "jdbc:mysql://" + kwargs["host"] + "/" + elif driver in ["psycopg2"]: + jdbc_driver = "org.postgresql.Driver" + url_pref = "jdbc:postgresql://" + kwargs["host"] + "/" + + else: + module = __import__(driver, fromlist=["connect"]) + connect = module.connect + + # Different drivers use different keywords... + kw = kwargs.copy() + if driver in ["MySQLdb", "mysql.connector"] and os.name != "java": + if "database" in kw: + kw["db"] = kw["database"] + del kw["database"] + if "password" in kw: + kw["passwd"] = kw["password"] + del kw["password"] + # kw["charset"] = "utf8" + # kw["use_unicode"] = True + else: + # DB-API recommendations + if "db" in kw: + kw["database"] = kw["db"] + del kw["db"] + if "passwd" in kw: + kw["password"] = kw["passwd"] + del kw["passwd"] + if driver in ["psycopg2", "pgdb"] and not kw.get("database"): + kw["database"] = "template1" + # SQLite connect takes the database name as input + if os.name == "java": + if driver in ["MySQLdb"]: + conn = connect( + url_pref + kw.get("database", "mysql"), + kw["user"], + kw["password"], + jdbc_driver, + ) + elif driver in ["psycopg2"]: + conn = connect( + url_pref + kw.get("database", "postgresql") + "?stringtype=unspecified", + kw["user"], + kw["password"], + jdbc_driver, + ) + elif driver in ["sqlite3"]: + conn = connect(kw["database"]) + else: + conn = connect(**kw) + + if os.name == "java": + server = DBServer(conn, module, driver) + else: + server = DBServer(conn, module) + + # Sets MySQL to allow double quotes, rather than only backticks + if driver in ["MySQLdb", "mysql.connector"]: + server.adaptor.execute("SET sql_mode='ANSI_QUOTES';") + + # TODO - Remove the following once BioSQL Bug 2839 is fixed. + # Test for RULES in PostgreSQL schema, see also Bug 2833. + if driver in ["psycopg2", "pgdb"]: + sql = ( + "SELECT ev_class FROM pg_rewrite WHERE " + "rulename='rule_bioentry_i1' OR " + "rulename='rule_bioentry_i2';" + ) + if server.adaptor.execute_and_fetchall(sql): + import warnings + + from Bio import BiopythonWarning + + warnings.warn( + "Your BioSQL PostgreSQL schema includes some rules " + "currently required for bioperl-db but which may" + "cause problems loading data using Biopython (see " + "BioSQL's RedMine Bug 2839 aka GitHub Issue 4 " + "https://github.com/biosql/biosql/issues/4). " + "If you do not use BioPerl, please remove these " + "rules. Biopython should cope with the rules " + "present, but with a performance penalty when " + "loading new records.", + BiopythonWarning, + ) + global _POSTGRES_RULES_PRESENT + _POSTGRES_RULES_PRESENT = True + + elif driver == "sqlite3": + # Tell SQLite that we want to use foreign keys + # https://www.sqlite.org/foreignkeys.html#fk_enable + server.adaptor.execute("PRAGMA foreign_keys = ON") + + return server + + +class DBServer: + """Represents a BioSQL database containing namespaces (sub-databases). + + This acts like a Python dictionary, giving access to each namespace + (defined by a row in the biodatabase table) as a BioSeqDatabase object. + """ + + def __init__(self, conn, module, module_name=None): + """Create a DBServer object. + + Arguments: + - conn - A database connection object + - module - The module used to create the database connection + - module_name - Optionally, the name of the module. Default: module.__name__ + + Normally you would not want to create a DBServer object yourself. + Instead use the open_database function, which returns an instance of DBServer. + """ + self.module = module + if module_name is None: + module_name = module.__name__ + if module_name == "mysql.connector": + wrap_cursor = True + else: + wrap_cursor = False + # Get module specific Adaptor or the base (general) Adaptor + Adapt = _interface_specific_adaptors.get(module_name, Adaptor) + self.adaptor = Adapt( + conn, DBUtils.get_dbutils(module_name), wrap_cursor=wrap_cursor + ) + self.module_name = module_name + + def __repr__(self): + """Return a short description of the class name and database connection.""" + return f"{self.__class__.__name__}({self.adaptor.conn!r})" + + def __getitem__(self, name): + """Return a BioSeqDatabase object. + + Arguments: + - name - The name of the BioSeqDatabase + + """ + return BioSeqDatabase(self.adaptor, name) + + def __len__(self): + """Return number of namespaces (sub-databases) in this database.""" + sql = "SELECT COUNT(name) FROM biodatabase;" + return int(self.adaptor.execute_and_fetch_col0(sql)[0]) + + def __contains__(self, value): + """Check if a namespace (sub-database) in this database.""" + sql = "SELECT COUNT(name) FROM biodatabase WHERE name=%s;" + return bool(self.adaptor.execute_and_fetch_col0(sql, (value,))[0]) + + def __iter__(self): + """Iterate over namespaces (sub-databases) in the database.""" + # TODO - Iterate over the cursor, much more efficient + return iter(self.adaptor.list_biodatabase_names()) + + def keys(self): + """Iterate over namespaces (sub-databases) in the database.""" + return iter(self) + + def values(self): + """Iterate over BioSeqDatabase objects in the database.""" + for key in self: + yield self[key] + + def items(self): + """Iterate over (namespace, BioSeqDatabase) in the database.""" + for key in self: + yield key, self[key] + + def __delitem__(self, name): + """Remove a namespace and all its entries.""" + if name not in self: + raise KeyError(name) + db_id = self.adaptor.fetch_dbid_by_dbname(name) + remover = Loader.DatabaseRemover(self.adaptor, db_id) + remover.remove() + + def new_database(self, db_name, authority=None, description=None): + """Add a new database to the server and return it.""" + # make the database + sql = ( + "INSERT INTO biodatabase (name, authority, description) VALUES (%s, %s, %s)" + ) + self.adaptor.execute(sql, (db_name, authority, description)) + return BioSeqDatabase(self.adaptor, db_name) + + def load_database_sql(self, sql_file): + """Load a database schema into the given database. + + This is used to create tables, etc when a database is first created. + sql_file should specify the complete path to a file containing + SQL entries for building the tables. + """ + # Not sophisticated enough for PG schema. Is it needed by MySQL? + # Looks like we need this more complicated way for both. Leaving it + # the default and removing the simple-minded approach. + + # read the file with all comment lines removed + sql = "" + with open(sql_file) as sql_handle: + for line in sql_handle: + if line.startswith("--"): # don't include comment lines + pass + elif line.startswith("#"): # ditto for MySQL comments + pass + elif line.strip(): # only include non-blank lines + sql += line.strip() + " " + + # two ways to load the SQL + # 1. PostgreSQL can load it all at once and actually needs to + # due to FUNCTION defines at the end of the SQL which mess up + # the splitting by semicolons + if self.module_name in ["psycopg2", "pgdb"]: + self.adaptor.cursor.execute(sql) + # 2. MySQL needs the database loading split up into single lines of + # SQL executed one at a time + elif self.module_name in ["mysql.connector", "MySQLdb", "sqlite3"]: + sql_parts = sql.split(";") # one line per sql command + # don't use the last item, it's blank + for sql_line in sql_parts[:-1]: + self.adaptor.cursor.execute(sql_line) + else: + raise ValueError(f"Module {self.module_name} not supported by the loader.") + + def commit(self): + """Commit the current transaction to the database.""" + return self.adaptor.commit() + + def rollback(self): + """Roll-back the current transaction.""" + return self.adaptor.rollback() + + def close(self): + """Close the connection. No further activity possible.""" + return self.adaptor.close() + + +class _CursorWrapper: + """A wrapper for mysql.connector resolving bytestring representations.""" + + def __init__(self, real_cursor): + self.real_cursor = real_cursor + + def execute(self, operation, params=None, multi=False): + """Execute a sql statement.""" + self.real_cursor.execute(operation, params, multi) + + def executemany(self, operation, params): + """Execute many sql statements.""" + self.real_cursor.executemany(operation, params) + + def _convert_tuple(self, tuple_): + """Decode any bytestrings present in the row (PRIVATE).""" + tuple_list = list(tuple_) + for i, elem in enumerate(tuple_list): + if isinstance(elem, bytes): + tuple_list[i] = elem.decode("utf-8") + return tuple(tuple_list) + + def _convert_list(self, lst): + ret_lst = [] + for tuple_ in lst: + new_tuple = self._convert_tuple(tuple_) + ret_lst.append(new_tuple) + return ret_lst + + def fetchall(self): + rv = self.real_cursor.fetchall() + return self._convert_list(rv) + + def fetchone(self): + tuple_ = self.real_cursor.fetchone() + return self._convert_tuple(tuple_) + + +class Adaptor: + """High level wrapper for a database connection and cursor. + + Most database calls in BioSQL are done indirectly though this adaptor + class. This provides helper methods for fetching data and executing + sql. + """ + + def __init__(self, conn, dbutils, wrap_cursor=False): + """Create an Adaptor object. + + Arguments: + - conn - A database connection + - dbutils - A BioSQL.DBUtils object + - wrap_cursor - Optional, whether to wrap the cursor object + + """ + self.conn = conn + if wrap_cursor: + self.cursor = _CursorWrapper(conn.cursor()) + else: + self.cursor = conn.cursor() + self.dbutils = dbutils + + def last_id(self, table): + """Return the last row id for the selected table.""" + return self.dbutils.last_id(self.cursor, table) + + def autocommit(self, y=True): + """Set the autocommit mode. True values enable; False value disable.""" + return self.dbutils.autocommit(self.conn, y) + + def commit(self): + """Commit the current transaction.""" + return self.conn.commit() + + def rollback(self): + """Roll-back the current transaction.""" + return self.conn.rollback() + + def close(self): + """Close the connection. No further activity possible.""" + return self.conn.close() + + def fetch_dbid_by_dbname(self, dbname): + """Return the internal id for the sub-database using its name.""" + self.execute( + "select biodatabase_id from biodatabase where name = %s", (dbname,) + ) + rv = self.cursor.fetchall() + if not rv: + raise KeyError(f"Cannot find biodatabase with name {dbname!r}") + return rv[0][0] + + def fetch_seqid_by_display_id(self, dbid, name): + """Return the internal id for a sequence using its display id. + + Arguments: + - dbid - the internal id for the sub-database + - name - the name of the sequence. Corresponds to the + name column of the bioentry table of the SQL schema + + """ + sql = "select bioentry_id from bioentry where name = %s" + fields = [name] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find display id {name!r}") + if len(rv) > 1: + raise IndexError(f"More than one entry with display id {name!r}") + return rv[0][0] + + def fetch_seqid_by_accession(self, dbid, name): + """Return the internal id for a sequence using its accession. + + Arguments: + - dbid - the internal id for the sub-database + - name - the accession of the sequence. Corresponds to the + accession column of the bioentry table of the SQL schema + + """ + sql = "select bioentry_id from bioentry where accession = %s" + fields = [name] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find accession {name!r}") + if len(rv) > 1: + raise IndexError(f"More than one entry with accession {name!r}") + return rv[0][0] + + def fetch_seqids_by_accession(self, dbid, name): + """Return a list internal ids using an accession. + + Arguments: + - dbid - the internal id for the sub-database + - name - the accession of the sequence. Corresponds to the + accession column of the bioentry table of the SQL schema + + """ + sql = "select bioentry_id from bioentry where accession = %s" + fields = [name] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + return self.execute_and_fetch_col0(sql, fields) + + def fetch_seqid_by_version(self, dbid, name): + """Return the internal id for a sequence using its accession and version. + + Arguments: + - dbid - the internal id for the sub-database + - name - the accession of the sequence containing a version number. + Must correspond to . + + """ + acc_version = name.split(".") + if len(acc_version) > 2: + raise IndexError(f"Bad version {name!r}") + acc = acc_version[0] + if len(acc_version) == 2: + version = acc_version[1] + else: + version = "0" + sql = "SELECT bioentry_id FROM bioentry WHERE accession = %s AND version = %s" + fields = [acc, version] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find version {name!r}") + if len(rv) > 1: + raise IndexError(f"More than one entry with version {name!r}") + return rv[0][0] + + def fetch_seqid_by_identifier(self, dbid, identifier): + """Return the internal id for a sequence using its identifier. + + Arguments: + - dbid - the internal id for the sub-database + - identifier - the identifier of the sequence. Corresponds to + the identifier column of the bioentry table in the SQL schema. + + """ + # YB: was fetch_seqid_by_seqid + sql = "SELECT bioentry_id FROM bioentry WHERE identifier = %s" + fields = [identifier] + if dbid: + sql += " and biodatabase_id = %s" + fields.append(dbid) + self.execute(sql, fields) + rv = self.cursor.fetchall() + if not rv: + raise IndexError(f"Cannot find display id {identifier!r}") + return rv[0][0] + + def list_biodatabase_names(self): + """Return a list of all of the sub-databases.""" + return self.execute_and_fetch_col0("SELECT name FROM biodatabase") + + def list_bioentry_ids(self, dbid): + """Return a list of internal ids for all of the sequences in a sub-databae. + + Arguments: + - dbid - The internal id for a sub-database + + """ + return self.execute_and_fetch_col0( + "SELECT bioentry_id FROM bioentry WHERE biodatabase_id = %s", (dbid,) + ) + + def list_bioentry_display_ids(self, dbid): + """Return a list of all sequence names in a sub-databae. + + Arguments: + - dbid - The internal id for a sub-database + + """ + return self.execute_and_fetch_col0( + "SELECT name FROM bioentry WHERE biodatabase_id = %s", (dbid,) + ) + + def list_any_ids(self, sql, args): + """Return ids given a SQL statement to select for them. + + This assumes that the given SQL does a SELECT statement that + returns a list of items. This parses them out of the 2D list + they come as and just returns them in a list. + """ + return self.execute_and_fetch_col0(sql, args) + + def execute_one(self, sql, args=None): + """Execute sql that returns 1 record, and return the record.""" + self.execute(sql, args or ()) + rv = self.cursor.fetchall() + if len(rv) != 1: + raise ValueError(f"Expected 1 response, got {len(rv)}.") + return rv[0] + + def execute(self, sql, args=None): + """Just execute an sql command.""" + if os.name == "java": + sql = sql.replace("%s", "?") + self.dbutils.execute(self.cursor, sql, args) + + def executemany(self, sql, args): + """Execute many sql commands.""" + if os.name == "java": + sql = sql.replace("%s", "?") + self.dbutils.executemany(self.cursor, sql, args) + + def get_subseq_as_string(self, seqid, start, end): + """Return a substring of a sequence. + + Arguments: + - seqid - The internal id for the sequence + - start - The start position of the sequence; 0-indexed + - end - The end position of the sequence + + """ + length = end - start + # XXX Check this on MySQL and PostgreSQL. substr should be general, + # does it need dbutils? + # return self.execute_one( + # """select SUBSTRING(seq FROM %s FOR %s) + # from biosequence where bioentry_id = %s""", + # (start+1, length, seqid))[0] + return self.execute_one( + "SELECT SUBSTR(seq, %s, %s) FROM biosequence WHERE bioentry_id = %s", + (start + 1, length, seqid), + )[0] + + def execute_and_fetch_col0(self, sql, args=None): + """Return a list of values from the first column in the row.""" + self.execute(sql, args or ()) + return [field[0] for field in self.cursor.fetchall()] + + def execute_and_fetchall(self, sql, args=None): + """Return a list of tuples of all rows.""" + self.execute(sql, args or ()) + return self.cursor.fetchall() + + +class MysqlConnectorAdaptor(Adaptor): + """A BioSQL Adaptor class with fixes for the MySQL interface. + + BioSQL was failing due to returns of bytearray objects from + the mysql-connector-python database connector. This adaptor + class scrubs returns of bytearrays and of byte strings converting + them to string objects instead. This adaptor class was made in + response to backwards incompatible changes added to + mysql-connector-python in release 2.0.0 of the package. + """ + + @staticmethod + def _bytearray_to_str(s): + """If s is bytes or bytearray, convert to a string (PRIVATE).""" + if isinstance(s, (bytes, bytearray)): + return s.decode() + return s + + def execute_one(self, sql, args=None): + """Execute sql that returns 1 record, and return the record.""" + out = super().execute_one(sql, args) + return tuple(self._bytearray_to_str(v) for v in out) + + def execute_and_fetch_col0(self, sql, args=None): + """Return a list of values from the first column in the row.""" + out = super().execute_and_fetch_col0(sql, args) + return [self._bytearray_to_str(column) for column in out] + + def execute_and_fetchall(self, sql, args=None): + """Return a list of tuples of all rows.""" + out = super().execute_and_fetchall(sql, args) + return [tuple(self._bytearray_to_str(v) for v in o) for o in out] + + +_interface_specific_adaptors = { + # If SQL interfaces require a specific adaptor, use this to map the adaptor + "mysql.connector": MysqlConnectorAdaptor, + "MySQLdb": MysqlConnectorAdaptor, +} + +_allowed_lookups = { + # Lookup name / function name to get id, function to list all ids + "primary_id": "fetch_seqid_by_identifier", + "gi": "fetch_seqid_by_identifier", + "display_id": "fetch_seqid_by_display_id", + "name": "fetch_seqid_by_display_id", + "accession": "fetch_seqid_by_accession", + "version": "fetch_seqid_by_version", +} + + +class BioSeqDatabase: + """Represents a namespace (sub-database) within the BioSQL database. + + i.e. One row in the biodatabase table, and all all rows in the bioentry + table associated with it. + """ + + def __init__(self, adaptor, name): + """Create a BioDatabase object. + + Arguments: + - adaptor - A BioSQL.Adaptor object + - name - The name of the sub-database (namespace) + + """ + self.adaptor = adaptor + self.name = name + self.dbid = self.adaptor.fetch_dbid_by_dbname(name) + + def __repr__(self): + """Return a short summary of the BioSeqDatabase.""" + return f"BioSeqDatabase({self.adaptor!r}, {self.name!r})" + + def get_Seq_by_id(self, name): + """Get a DBSeqRecord object by its name. + + Example: seq_rec = db.get_Seq_by_id('ROA1_HUMAN') + + The name of this method is misleading since it returns a DBSeqRecord + rather than a Seq object, and presumably was to mirror BioPerl. + """ + seqid = self.adaptor.fetch_seqid_by_display_id(self.dbid, name) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def get_Seq_by_acc(self, name): + """Get a DBSeqRecord object by accession number. + + Example: seq_rec = db.get_Seq_by_acc('X77802') + + The name of this method is misleading since it returns a DBSeqRecord + rather than a Seq object, and presumably was to mirror BioPerl. + """ + seqid = self.adaptor.fetch_seqid_by_accession(self.dbid, name) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def get_Seq_by_ver(self, name): + """Get a DBSeqRecord object by version number. + + Example: seq_rec = db.get_Seq_by_ver('X77802.1') + + The name of this method is misleading since it returns a DBSeqRecord + rather than a Seq object, and presumably was to mirror BioPerl. + """ + seqid = self.adaptor.fetch_seqid_by_version(self.dbid, name) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def get_Seqs_by_acc(self, name): + """Get a list of DBSeqRecord objects by accession number. + + Example: seq_recs = db.get_Seq_by_acc('X77802') + + The name of this method is misleading since it returns a list of + DBSeqRecord objects rather than a list of Seq objects, and presumably + was to mirror BioPerl. + """ + seqids = self.adaptor.fetch_seqids_by_accession(self.dbid, name) + return [BioSeq.DBSeqRecord(self.adaptor, seqid) for seqid in seqids] + + def __getitem__(self, key): + """Return a DBSeqRecord for one of the sequences in the sub-database. + + Arguments: + - key - The internal id for the sequence + + """ + record = BioSeq.DBSeqRecord(self.adaptor, key) + if record._biodatabase_id != self.dbid: + raise KeyError(f"Entry {key!r} does exist, but not in current name space") + return record + + def __delitem__(self, key): + """Remove an entry and all its annotation.""" + if key not in self: + raise KeyError( + f"Entry {key!r} cannot be deleted. It was not found or is invalid" + ) + # Assuming this will automatically cascade to the other tables... + sql = "DELETE FROM bioentry WHERE biodatabase_id=%s AND bioentry_id=%s;" + self.adaptor.execute(sql, (self.dbid, key)) + + def __len__(self): + """Return number of records in this namespace (sub database).""" + sql = "SELECT COUNT(bioentry_id) FROM bioentry WHERE biodatabase_id=%s;" + return int(self.adaptor.execute_and_fetch_col0(sql, (self.dbid,))[0]) + + def __contains__(self, value): + """Check if a primary (internal) id is this namespace (sub database).""" + sql = ( + "SELECT COUNT(bioentry_id) FROM bioentry " + "WHERE biodatabase_id=%s AND bioentry_id=%s;" + ) + # The bioentry_id field is an integer in the schema. + # PostgreSQL will throw an error if we use a non integer in the query. + try: + bioentry_id = int(value) + except ValueError: + return False + return bool( + self.adaptor.execute_and_fetch_col0(sql, (self.dbid, bioentry_id))[0] + ) + + def __iter__(self): + """Iterate over ids (which may not be meaningful outside this database).""" + # TODO - Iterate over the cursor, much more efficient + return iter(self.adaptor.list_bioentry_ids(self.dbid)) + + def keys(self): + """Iterate over ids (which may not be meaningful outside this database).""" + return iter(self) + + def values(self): + """Iterate over DBSeqRecord objects in the namespace (sub database).""" + for key in self: + yield self[key] + + def items(self): + """Iterate over (id, DBSeqRecord) for the namespace (sub database).""" + for key in self: + yield key, self[key] + + def lookup(self, **kwargs): + """Return a DBSeqRecord using an acceptable identifier. + + Arguments: + - kwargs - A single key-value pair where the key is one + of primary_id, gi, display_id, name, accession, version + + """ + if len(kwargs) != 1: + raise TypeError("single key/value parameter expected") + k, v = list(kwargs.items())[0] + if k not in _allowed_lookups: + raise TypeError( + f"lookup() expects one of {list(_allowed_lookups.keys())!r}, not {k!r}" + ) + lookup_name = _allowed_lookups[k] + lookup_func = getattr(self.adaptor, lookup_name) + seqid = lookup_func(self.dbid, v) + return BioSeq.DBSeqRecord(self.adaptor, seqid) + + def load(self, record_iterator, fetch_NCBI_taxonomy=False): + """Load a set of SeqRecords into the BioSQL database. + + record_iterator is either a list of SeqRecord objects, or an + Iterator object that returns SeqRecord objects (such as the + output from the Bio.SeqIO.parse() function), which will be + used to populate the database. + + fetch_NCBI_taxonomy is boolean flag allowing or preventing + connection to the taxonomic database on the NCBI server + (via Bio.Entrez) to fetch a detailed taxonomy for each + SeqRecord. + + Example:: + + from Bio import SeqIO + count = db.load(SeqIO.parse(open(filename), format)) + + Returns the number of records loaded. + """ + db_loader = Loader.DatabaseLoader(self.adaptor, self.dbid, fetch_NCBI_taxonomy) + num_records = 0 + for cur_record in record_iterator: + num_records += 1 + # Hack to work around BioSQL Bug 2839 - If using PostgreSQL and + # the RULES are present check for a duplicate record before loading + if _POSTGRES_RULES_PRESENT: + # Recreate what the Loader's _load_bioentry_table will do: + if cur_record.id.count(".") == 1: + accession, version = cur_record.id.split(".") + try: + version = int(version) + except ValueError: + accession = cur_record.id + version = 0 + else: + accession = cur_record.id + version = 0 + gi = cur_record.annotations.get("gi") + sql = ( + "SELECT bioentry_id FROM bioentry " + "WHERE (identifier = '%s' AND biodatabase_id = '%s') " + "OR (accession = '%s' AND version = '%s' AND biodatabase_id = '%s')" + ) + self.adaptor.execute( + sql % (gi, self.dbid, accession, version, self.dbid) + ) + if self.adaptor.cursor.fetchone(): + raise self.adaptor.conn.IntegrityError( + "Duplicate record detected: record has not been inserted" + ) + # End of hack + db_loader.load_seqrecord(cur_record) + return num_records diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/DBUtils.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/DBUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..7552b983fb1faf765304cf14210c9c0324511a25 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/DBUtils.py @@ -0,0 +1,153 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2010 copyright by Peter Cock. All rights reserved. +# Revisions 2009 copyright by Brad Chapman. All rights reserved. +# Revisions 2013 copyright by Tiago Antao. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org +"""Helper code for Biopython's BioSQL code (for internal use).""" + +import os + +_dbutils: dict[str, type["Generic_dbutils"]] = {} + + +class Generic_dbutils: + """Default database utilities.""" + + def __init__(self): + """Create a Generic_dbutils object.""" + + def tname(self, table): + """Return the name of the table.""" + if table != "biosequence": + return table + else: + return "bioentry" + + def last_id(self, cursor, table): + """Return the last used id for a table.""" + # XXX: Unsafe without transactions isolation + table = self.tname(table) + sql = f"select max({table}_id) from {table}" + cursor.execute(sql) + rv = cursor.fetchone() + return rv[0] + + def execute(self, cursor, sql, args=None): + """Just execute an sql command.""" + cursor.execute(sql, args or ()) + + def executemany(self, cursor, sql, seq): + """Execute many sql commands.""" + cursor.executemany(sql, seq) + + def autocommit(self, conn, y=1): + """Set autocommit on the database connection.""" + # Let's hope it was not really needed + + +class Sqlite_dbutils(Generic_dbutils): + """Custom database utilities for SQLite.""" + + def _sub_placeholder(self, sql): + """Format the argument placeholders for sqlite (PRIVATE).""" + return sql.replace("%s", "?") + + def execute(self, cursor, sql, args=None): + """Execute SQL command. + + Replaces %s with ? for variable substitution in sqlite3. + """ + sql = self._sub_placeholder(sql) + cursor.execute(sql, args or ()) + + def executemany(self, cursor, sql, seq): + """Execute many sql statements.""" + sql = self._sub_placeholder(sql) + cursor.executemany(sql, seq) + + +_dbutils["sqlite3"] = Sqlite_dbutils + + +class Mysql_dbutils(Generic_dbutils): + """Custom database utilities for MySQL.""" + + def last_id(self, cursor, table): + """Return the last used id for a table.""" + if os.name == "java": + return Generic_dbutils.last_id(self, cursor, table) + try: + # This worked on older versions of MySQL + return cursor.insert_id() + except AttributeError: + # See bug 2390 + # Google suggests this is the new way, + # same fix also suggested by Eric Gibert: + return cursor.lastrowid + + +_dbutils["MySQLdb"] = Mysql_dbutils + + +class _PostgreSQL_dbutils(Generic_dbutils): + """Base class for any PostgreSQL adaptor.""" + + def next_id(self, cursor, table): + table = self.tname(table) + sql = f"SELECT nextval('{table}_pk_seq')" + cursor.execute(sql) + rv = cursor.fetchone() + return rv[0] + + def last_id(self, cursor, table): + table = self.tname(table) + sql = f"SELECT currval('{table}_pk_seq')" + cursor.execute(sql) + rv = cursor.fetchone() + return rv[0] + + +class Psycopg2_dbutils(_PostgreSQL_dbutils): + """Custom database utilities for Psycopg2 (PostgreSQL).""" + + def autocommit(self, conn, y=True): + """Set autocommit on the database connection.""" + if y: + if os.name == "java": + conn.autocommit = 1 + else: + conn.set_isolation_level(0) + else: + if os.name == "java": + conn.autocommit = 0 + else: + conn.set_isolation_level(1) + + +_dbutils["psycopg2"] = Psycopg2_dbutils + + +class Pgdb_dbutils(_PostgreSQL_dbutils): + """Custom database utilities for Pgdb (aka PyGreSQL, for PostgreSQL).""" + + def autocommit(self, conn, y=True): + """Set autocommit on the database connection. Currently not implemented.""" + raise NotImplementedError("pgdb does not support this!") + + +_dbutils["pgdb"] = Pgdb_dbutils + + +def get_dbutils(module_name): + """Return the correct dbutils object for the database driver.""" + try: + return _dbutils[module_name]() + except KeyError: + return Generic_dbutils() diff --git a/.venv_haddock/lib/python3.12/site-packages/BioSQL/__init__.py b/.venv_haddock/lib/python3.12/site-packages/BioSQL/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8f079d70ededef41ad81cdfefa7ebf05ce2e7b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/BioSQL/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2002 by Andrew Dalke. All rights reserved. +# Revisions 2007-2008 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Note that BioSQL (including the database schema and scripts) is +# available and licensed separately. Please consult www.biosql.org +"""Storing and retrieve biological sequences in a BioSQL relational database. + +See: + +- http://biopython.org/wiki/BioSQL +- http://www.biosql.org/ + +""" diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__init__.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/basevalidators.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/basevalidators.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7849cc931c24f9741bf1256a28f05fe14d1693 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/basevalidators.py @@ -0,0 +1,2754 @@ +import base64 +import numbers +import textwrap +import uuid +from importlib import import_module +import copy +import io +import re +import sys +import narwhals.stable.v1 as nw + +from _plotly_utils.optional_imports import get_module + + +# back-port of fullmatch from Py3.4+ +def fullmatch(regex, string, flags=0): + """Emulate python-3.4 re.fullmatch().""" + if "pattern" in dir(regex): + regex_string = regex.pattern + else: + regex_string = regex + return re.match("(?:" + regex_string + r")\Z", string, flags=flags) + + +def to_non_numpy_type(np, v): + """ + Convert a numpy scalar value to a native Python type. + Calling .item() on a datetime64[ns] value returns an integer, since + Python datetimes only support microsecond precision. So we cast + datetime64[ns] to datetime64[us] to ensure it remains a datetime. + + Should only be used in contexts where we already know `np` is defined. + """ + if hasattr(v, "dtype") and v.dtype == np.dtype("datetime64[ns]"): + return v.astype("datetime64[us]").item() + return v.item() + + +# Utility functions +# ----------------- +def to_scalar_or_list(v): + # Handle the case where 'v' is a non-native scalar-like type, + # such as numpy.float32. Without this case, the object might be + # considered numpy-convertable and therefore promoted to a + # 0-dimensional array, but we instead want it converted to a + # Python native scalar type ('float' in the example above). + # We explicitly check if is has the 'item' method, which conventionally + # converts these types to native scalars. + np = get_module("numpy", should_load=False) + pd = get_module("pandas", should_load=False) + if np and np.isscalar(v) and hasattr(v, "item"): + return to_non_numpy_type(np, v) + if isinstance(v, (list, tuple)): + return [to_scalar_or_list(e) for e in v] + elif np and isinstance(v, np.ndarray): + if v.ndim == 0: + return to_non_numpy_type(np, v) + return [to_scalar_or_list(e) for e in v] + elif pd and isinstance(v, (pd.Series, pd.Index)): + return [to_scalar_or_list(e) for e in v] + elif is_numpy_convertable(v): + return to_scalar_or_list(np.array(v)) + else: + return v + + +def copy_to_readonly_numpy_array(v, kind=None, force_numeric=False): + """ + Convert an array-like value into a read-only numpy array + + Parameters + ---------- + v : array like + Array like value (list, tuple, numpy array, pandas series, etc.) + kind : str or tuple of str + If specified, the numpy dtype kind (or kinds) that the array should + have, or be converted to if possible. + If not specified then let numpy infer the datatype + force_numeric : bool + If true, raise an exception if the resulting numpy array does not + have a numeric dtype (i.e. dtype.kind not in ['u', 'i', 'f']) + Returns + ------- + np.ndarray + Numpy array with the 'WRITEABLE' flag set to False + """ + np = get_module("numpy") + + assert np is not None + + # ### Process kind ### + if not kind: + kind = () + elif isinstance(kind, str): + kind = (kind,) + + first_kind = kind[0] if kind else None + + # u: unsigned int, i: signed int, f: float + numeric_kinds = {"u", "i", "f"} + kind_default_dtypes = { + "u": "uint32", + "i": "int32", + "f": "float64", + "O": "object", + } + + # With `pass_through=True`, the original object will be returned if unable to convert + # to a Narwhals DataFrame or Series. + v = nw.from_native(v, allow_series=True, pass_through=True) + + if isinstance(v, nw.Series): + if v.dtype == nw.Datetime and v.dtype.time_zone is not None: + # Remove time zone so that local time is displayed + v = v.dt.replace_time_zone(None).to_numpy() + else: + v = v.to_numpy() + elif isinstance(v, nw.DataFrame): + schema = v.schema + overrides = {} + for key, val in schema.items(): + if val == nw.Datetime and val.time_zone is not None: + # Remove time zone so that local time is displayed + overrides[key] = nw.col(key).dt.replace_time_zone(None) + if overrides: + v = v.with_columns(**overrides) + v = v.to_numpy() + + if not isinstance(v, np.ndarray): + # v has its own logic on how to convert itself into a numpy array + if is_numpy_convertable(v): + return copy_to_readonly_numpy_array( + np.array(v), kind=kind, force_numeric=force_numeric + ) + else: + # v is not homogenous array + v_list = [to_scalar_or_list(e) for e in v] + + # Lookup dtype for requested kind, if any + dtype = kind_default_dtypes.get(first_kind, None) + + # construct new array from list + new_v = np.array(v_list, order="C", dtype=dtype) + elif v.dtype.kind in numeric_kinds: + # v is a homogenous numeric array + if kind and v.dtype.kind not in kind: + # Kind(s) were specified and this array doesn't match + # Convert to the default dtype for the first kind + dtype = kind_default_dtypes.get(first_kind, None) + new_v = np.ascontiguousarray(v.astype(dtype)) + else: + # Either no kind was requested or requested kind is satisfied + new_v = np.ascontiguousarray(v.copy()) + else: + # v is a non-numeric homogenous array + new_v = v.copy() + + # Handle force numeric param + # -------------------------- + if force_numeric and new_v.dtype.kind not in numeric_kinds: + raise ValueError( + "Input value is not numeric and force_numeric parameter set to True" + ) + + if "U" not in kind: + # Force non-numeric arrays to have object type + # -------------------------------------------- + # Here we make sure that non-numeric arrays have the object + # datatype. This works around cases like np.array([1, 2, '3']) where + # numpy converts the integers to strings and returns array of dtype + # ' 'x' for anchor-style + # enumeration properties + self.regex_replacements = [] + + # Loop over enumeration values + # ---------------------------- + # Look for regular expressions + for v in self.values: + if v and isinstance(v, str) and v[0] == "/" and v[-1] == "/" and len(v) > 1: + # String is a regex with leading and trailing '/' character + regex_str = v[1:-1] + self.val_regexs.append(re.compile(regex_str)) + self.regex_replacements.append( + EnumeratedValidator.build_regex_replacement(regex_str) + ) + else: + self.val_regexs.append(None) + self.regex_replacements.append(None) + + def __deepcopy__(self, memodict={}): + """ + A custom deepcopy method is needed here because compiled regex + objects don't support deepcopy + """ + cls = self.__class__ + return cls(self.plotly_name, self.parent_name, values=self.values) + + @staticmethod + def build_regex_replacement(regex_str): + # Example: regex_str == r"^y([2-9]|[1-9][0-9]+)?$" + # + # When we see a regular expression like the one above, we want to + # build regular expression replacement params that will remove a + # suffix of 1 from the input string ('y1' -> 'y' in this example) + # + # Why?: Regular expressions like this one are used in enumeration + # properties that refer to subplotids (e.g. layout.annotation.xref) + # The regular expressions forbid suffixes of 1, like 'x1'. But we + # want to accept 'x1' and coerce it into 'x' + # + # To be cautious, we only perform this conversion for enumerated + # values that match the anchor-style regex + match = re.match( + r"\^(\w)\(\[2\-9\]\|\[1\-9\]\[0\-9\]\+\)\?\( domain\)\?\$", regex_str + ) + + if match: + anchor_char = match.group(1) + return "^" + anchor_char + "1$", anchor_char + else: + return None + + def perform_replacemenet(self, v): + """ + Return v with any applicable regex replacements applied + """ + if isinstance(v, str): + for repl_args in self.regex_replacements: + if repl_args: + v = re.sub(repl_args[0], repl_args[1], v) + + return v + + def description(self): + # Separate regular values from regular expressions + enum_vals = [] + enum_regexs = [] + for v, regex in zip(self.values, self.val_regexs): + if regex is not None: + enum_regexs.append(regex.pattern) + else: + enum_vals.append(v) + desc = """\ + The '{name}' property is an enumeration that may be specified as:""".format( + name=self.plotly_name + ) + + if enum_vals: + enum_vals_str = "\n".join( + textwrap.wrap( + repr(enum_vals), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + ) + ) + + desc = ( + desc + + """ + - One of the following enumeration values: +{enum_vals_str}""".format(enum_vals_str=enum_vals_str) + ) + + if enum_regexs: + enum_regexs_str = "\n".join( + textwrap.wrap( + repr(enum_regexs), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + ) + ) + + desc = ( + desc + + """ + - A string that matches one of the following regular expressions: +{enum_regexs_str}""".format(enum_regexs_str=enum_regexs_str) + ) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def in_values(self, e): + """ + Return whether a value matches one of the enumeration options + """ + is_str = isinstance(e, str) + for v, regex in zip(self.values, self.val_regexs): + if is_str and regex: + in_values = fullmatch(regex, e) is not None + # in_values = regex.fullmatch(e) is not None + else: + in_values = e == v + + if in_values: + return True + + return False + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_array(v): + v_replaced = [self.perform_replacemenet(v_el) for v_el in v] + + invalid_els = [e for e in v_replaced if (not self.in_values(e))] + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + if is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(v) + else: + v = to_scalar_or_list(v) + else: + v = self.perform_replacemenet(v) + if not self.in_values(v): + self.raise_invalid_val(v) + return v + + +class BooleanValidator(BaseValidator): + """ + "boolean": { + "description": "A boolean (true/false) value.", + "requiredOpts": [], + "otherOpts": [ + "arrayOk", + "dflt" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, array_ok=False, **kwargs): + super(BooleanValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a boolean and must be specified as: + - A boolean value: True or False""".format(plotly_name=self.plotly_name) + if self.array_ok: + desc += """ + - A tuple or list of the above""" + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_simple_array(v): + invalid_els = [e for e in v if not isinstance(e, bool)] + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + v = to_scalar_or_list(v) + elif not isinstance(v, bool): + self.raise_invalid_val(v) + + return v + + +class SrcValidator(BaseValidator): + def __init__(self, plotly_name, parent_name, **kwargs): + super(SrcValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.chart_studio = get_module("chart_studio") + + def description(self): + return """\ + The '{plotly_name}' property must be specified as a string or + as a plotly.grid_objs.Column object""".format(plotly_name=self.plotly_name) + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif isinstance(v, str): + pass + elif self.chart_studio and isinstance(v, self.chart_studio.grid_objs.Column): + # Convert to id string + v = v.id + else: + self.raise_invalid_val(v) + + return v + + +class NumberValidator(BaseValidator): + """ + "number": { + "description": "A number or a numeric value (e.g. a number + inside a string). When applicable, values + greater (less) than `max` (`min`) are coerced to + the `dflt`.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "min", + "max", + "arrayOk" + ] + }, + """ + + def __init__( + self, plotly_name, parent_name, min=None, max=None, array_ok=False, **kwargs + ): + super(NumberValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Handle min + if min is None and max is not None: + # Max was specified, so make min -inf + self.min_val = float("-inf") + else: + self.min_val = min + + # Handle max + if max is None and min is not None: + # Min was specified, so make min inf + self.max_val = float("inf") + else: + self.max_val = max + + if min is not None or max is not None: + self.has_min_max = True + else: + self.has_min_max = False + + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a number and may be specified as:""".format( + plotly_name=self.plotly_name + ) + + if not self.has_min_max: + desc = ( + desc + + """ + - An int or float""" + ) + + else: + desc = ( + desc + + """ + - An int or float in the interval [{min_val}, {max_val}]""".format( + min_val=self.min_val, max_val=self.max_val + ) + ) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + np = get_module("numpy") + try: + v_array = copy_to_readonly_numpy_array(v, force_numeric=True) + except (ValueError, TypeError, OverflowError): + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + v_valid = np.logical_and( + self.min_val <= v_array, v_array <= self.max_val + ) + + if not np.all(v_valid): + # Grab up to the first 10 invalid values + v_invalid = np.logical_not(v_valid) + some_invalid_els = np.array(v, dtype="object")[v_invalid][ + :10 + ].tolist() + + self.raise_invalid_elements(some_invalid_els) + + v = v_array # Always numeric numpy array + elif self.array_ok and is_simple_array(v): + # Check numeric + invalid_els = [e for e in v if not isinstance(e, numbers.Number)] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + # Check min/max + if self.has_min_max: + invalid_els = [e for e in v if not (self.min_val <= e <= self.max_val)] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + v = to_scalar_or_list(v) + else: + # Check numeric + if not isinstance(v, numbers.Number): + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + if not (self.min_val <= v <= self.max_val): + self.raise_invalid_val(v) + return v + + +class IntegerValidator(BaseValidator): + """ + "integer": { + "description": "An integer or an integer inside a string. When + applicable, values greater (less) than `max` + (`min`) are coerced to the `dflt`.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "min", + "max", + "extras", + "arrayOk" + ] + }, + """ + + def __init__( + self, + plotly_name, + parent_name, + min=None, + max=None, + extras=None, + array_ok=False, + **kwargs, + ): + super(IntegerValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Handle min + if min is None and max is not None: + # Max was specified, so make min -inf + self.min_val = -sys.maxsize - 1 + else: + self.min_val = min + + # Handle max + if max is None and min is not None: + # Min was specified, so make min inf + self.max_val = sys.maxsize + else: + self.max_val = max + + if min is not None or max is not None: + self.has_min_max = True + else: + self.has_min_max = False + + self.extras = extras if extras is not None else [] + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a integer and may be specified as:""".format( + plotly_name=self.plotly_name + ) + + if not self.has_min_max: + desc = ( + desc + + """ + - An int (or float that will be cast to an int)""" + ) + else: + desc = desc + ( + """ + - An int (or float that will be cast to an int) + in the interval [{min_val}, {max_val}]""".format( + min_val=self.min_val, max_val=self.max_val + ) + ) + + # Extras + if self.extras: + desc = desc + ( + """ + OR exactly one of {extras} (e.g. '{eg_extra}')""" + ).format(extras=self.extras, eg_extra=self.extras[-1]) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif v in self.extras: + return v + elif self.array_ok and is_homogeneous_array(v): + np = get_module("numpy") + v_array = copy_to_readonly_numpy_array( + v, kind=("i", "u"), force_numeric=True + ) + + if v_array.dtype.kind not in ["i", "u"]: + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + v_valid = np.logical_and( + self.min_val <= v_array, v_array <= self.max_val + ) + + if not np.all(v_valid): + # Grab up to the first 10 invalid values + v_invalid = np.logical_not(v_valid) + some_invalid_els = np.array(v, dtype="object")[v_invalid][ + :10 + ].tolist() + self.raise_invalid_elements(some_invalid_els) + + v = v_array + elif self.array_ok and is_simple_array(v): + # Check integer type + invalid_els = [ + e for e in v if not isinstance(e, int) and e not in self.extras + ] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + # Check min/max + if self.has_min_max: + invalid_els = [ + e + for e in v + if not (isinstance(e, int) and self.min_val <= e <= self.max_val) + and e not in self.extras + ] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + v = to_scalar_or_list(v) + else: + # Check int + if not isinstance(v, int): + # don't let int() cast strings to ints + self.raise_invalid_val(v) + + # Check min/max + if self.has_min_max: + if not (self.min_val <= v <= self.max_val): + self.raise_invalid_val(v) + + return v + + +class StringValidator(BaseValidator): + """ + "string": { + "description": "A string value. Numbers are converted to strings + except for attributes with `strict` set to true.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "noBlank", + "strict", + "arrayOk", + "values" + ] + }, + """ + + def __init__( + self, + plotly_name, + parent_name, + no_blank=False, + strict=False, + array_ok=False, + values=None, + **kwargs, + ): + super(StringValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.no_blank = no_blank + self.strict = strict + self.array_ok = array_ok + self.values = values + + @staticmethod + def to_str_or_unicode_or_none(v): + """ + Convert a value to a string if it's not None, a string, + or a unicode (on Python 2). + """ + if v is None or isinstance(v, str): + return v + else: + return str(v) + + def description(self): + desc = """\ + The '{plotly_name}' property is a string and must be specified as:""".format( + plotly_name=self.plotly_name + ) + + if self.no_blank: + desc = ( + desc + + """ + - A non-empty string""" + ) + elif self.values: + valid_str = "\n".join( + textwrap.wrap( + repr(self.values), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + ) + ) + + desc = ( + desc + + """ + - One of the following strings: +{valid_str}""".format(valid_str=valid_str) + ) + else: + desc = ( + desc + + """ + - A string""" + ) + + if not self.strict: + desc = ( + desc + + """ + - A number that will be converted to a string""" + ) + + if self.array_ok: + desc = ( + desc + + """ + - A tuple, list, or one-dimensional numpy array of the above""" + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_array(v): + # If strict, make sure all elements are strings. + if self.strict: + invalid_els = [e for e in v if not isinstance(e, str)] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + if is_homogeneous_array(v): + np = get_module("numpy") + + # If not strict, let numpy cast elements to strings + v = copy_to_readonly_numpy_array(v, kind="U") + + # Check no_blank + if self.no_blank: + invalid_els = v[v == ""][:10].tolist() + if invalid_els: + self.raise_invalid_elements(invalid_els) + + # Check values + if self.values: + invalid_inds = np.logical_not(np.isin(v, self.values)) + invalid_els = v[invalid_inds][:10].tolist() + if invalid_els: + self.raise_invalid_elements(invalid_els) + elif is_simple_array(v): + if not self.strict: + v = [StringValidator.to_str_or_unicode_or_none(e) for e in v] + + # Check no_blank + if self.no_blank: + invalid_els = [e for e in v if e == ""] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + # Check values + if self.values: + invalid_els = [e for e in v if v not in self.values] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(v) + + else: + if self.strict: + if not isinstance(v, str): + self.raise_invalid_val(v) + else: + if isinstance(v, str): + pass + elif isinstance(v, (int, float)): + # Convert value to a string + v = str(v) + else: + self.raise_invalid_val(v) + + if self.no_blank and len(v) == 0: + self.raise_invalid_val(v) + + if self.values and v not in self.values: + self.raise_invalid_val(v) + + return v + + +class ColorValidator(BaseValidator): + """ + "color": { + "description": "A string describing color. Supported formats: + - hex (e.g. '#d3d3d3') + - rgb (e.g. 'rgb(255, 0, 0)') + - rgba (e.g. 'rgb(255, 0, 0, 0.5)') + - hsl (e.g. 'hsl(0, 100%, 50%)') + - hsv (e.g. 'hsv(0, 100%, 100%)') + - named colors(full list: + http://www.w3.org/TR/css3-color/#svg-color)", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "arrayOk" + ] + }, + """ + + re_hex = re.compile(r"#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})") + re_rgb_etc = re.compile(r"(rgb|hsl|hsv)a?\([\d.]+%?(,[\d.]+%?){2,3}\)") + re_ddk = re.compile(r"var\(\-\-.*\)") + + named_colors = [ + "aliceblue", + "antiquewhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "black", + "blanchedalmond", + "blue", + "blueviolet", + "brown", + "burlywood", + "cadetblue", + "chartreuse", + "chocolate", + "coral", + "cornflowerblue", + "cornsilk", + "crimson", + "cyan", + "darkblue", + "darkcyan", + "darkgoldenrod", + "darkgray", + "darkgrey", + "darkgreen", + "darkkhaki", + "darkmagenta", + "darkolivegreen", + "darkorange", + "darkorchid", + "darkred", + "darksalmon", + "darkseagreen", + "darkslateblue", + "darkslategray", + "darkslategrey", + "darkturquoise", + "darkviolet", + "deeppink", + "deepskyblue", + "dimgray", + "dimgrey", + "dodgerblue", + "firebrick", + "floralwhite", + "forestgreen", + "fuchsia", + "gainsboro", + "ghostwhite", + "gold", + "goldenrod", + "gray", + "grey", + "green", + "greenyellow", + "honeydew", + "hotpink", + "indianred", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderblush", + "lawngreen", + "lemonchiffon", + "lightblue", + "lightcoral", + "lightcyan", + "lightgoldenrodyellow", + "lightgray", + "lightgrey", + "lightgreen", + "lightpink", + "lightsalmon", + "lightseagreen", + "lightskyblue", + "lightslategray", + "lightslategrey", + "lightsteelblue", + "lightyellow", + "lime", + "limegreen", + "linen", + "magenta", + "maroon", + "mediumaquamarine", + "mediumblue", + "mediumorchid", + "mediumpurple", + "mediumseagreen", + "mediumslateblue", + "mediumspringgreen", + "mediumturquoise", + "mediumvioletred", + "midnightblue", + "mintcream", + "mistyrose", + "moccasin", + "navajowhite", + "navy", + "oldlace", + "olive", + "olivedrab", + "orange", + "orangered", + "orchid", + "palegoldenrod", + "palegreen", + "paleturquoise", + "palevioletred", + "papayawhip", + "peachpuff", + "peru", + "pink", + "plum", + "powderblue", + "purple", + "red", + "rosybrown", + "royalblue", + "rebeccapurple", + "saddlebrown", + "salmon", + "sandybrown", + "seagreen", + "seashell", + "sienna", + "silver", + "skyblue", + "slateblue", + "slategray", + "slategrey", + "snow", + "springgreen", + "steelblue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whitesmoke", + "yellow", + "yellowgreen", + ] + + def __init__( + self, plotly_name, parent_name, array_ok=False, colorscale_path=None, **kwargs + ): + super(ColorValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.array_ok = array_ok + + # colorscale_path is the path to the colorscale associated with this + # color property, or None if no such colorscale exists. Only colors + # with an associated colorscale may take on numeric values + self.colorscale_path = colorscale_path + + def numbers_allowed(self): + return self.colorscale_path is not None + + def description(self): + valid_color_description = """\ + The '{plotly_name}' property is a color and may be specified as: + - A hex string (e.g. '#ff0000') + - An rgb/rgba string (e.g. 'rgb(255,0,0)') + - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') + - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') + - A named CSS color: see https://plotly.com/python/css-colors/ for a list""".format( + plotly_name=self.plotly_name + ) + + if self.colorscale_path: + valid_color_description = ( + valid_color_description + + """ + - A number that will be interpreted as a color + according to {colorscale_path}""".format(colorscale_path=self.colorscale_path) + ) + + if self.array_ok: + valid_color_description = ( + valid_color_description + + """ + - A list or array of any of the above""" + ) + + return valid_color_description + + def validate_coerce(self, v, should_raise=True): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(v) + if self.numbers_allowed() and v.dtype.kind in ["u", "i", "f"]: + # Numbers are allowed and we have an array of numbers. + # All good + pass + else: + validated_v = [self.validate_coerce(e, should_raise=False) for e in v] + + invalid_els = self.find_invalid_els(v, validated_v) + + if invalid_els and should_raise: + self.raise_invalid_elements(invalid_els) + + # ### Check that elements have valid colors types ### + elif self.numbers_allowed() or invalid_els: + v = copy_to_readonly_numpy_array(validated_v, kind="O") + else: + v = copy_to_readonly_numpy_array(validated_v, kind="U") + elif self.array_ok and is_simple_array(v): + validated_v = [self.validate_coerce(e, should_raise=False) for e in v] + + invalid_els = self.find_invalid_els(v, validated_v) + + if invalid_els and should_raise: + self.raise_invalid_elements(invalid_els) + else: + v = validated_v + else: + # Validate scalar color + validated_v = self.vc_scalar(v) + if validated_v is None and should_raise: + self.raise_invalid_val(v) + + v = validated_v + + return v + + def find_invalid_els(self, orig, validated, invalid_els=None): + """ + Helper method to find invalid elements in orig array. + Elements are invalid if their corresponding element in + the validated array is None. + + This method handles deeply nested list structures + """ + if invalid_els is None: + invalid_els = [] + + for orig_el, validated_el in zip(orig, validated): + if is_array(orig_el): + self.find_invalid_els(orig_el, validated_el, invalid_els) + else: + if validated_el is None: + invalid_els.append(orig_el) + + return invalid_els + + def vc_scalar(self, v): + """Helper to validate/coerce a scalar color""" + return ColorValidator.perform_validate_coerce( + v, allow_number=self.numbers_allowed() + ) + + @staticmethod + def perform_validate_coerce(v, allow_number=None): + """ + Validate, coerce, and return a single color value. If input cannot be + coerced to a valid color then return None. + + Parameters + ---------- + v : number or str + Candidate color value + + allow_number : bool + True if numbers are allowed as colors + + Returns + ------- + number or str or None + """ + + if isinstance(v, numbers.Number) and allow_number: + # If allow_numbers then any number is ok + return v + elif not isinstance(v, str): + # If not allow_numbers then value must be a string + return None + else: + # Remove spaces so regexes don't need to bother with them. + v_normalized = v.replace(" ", "").lower() + + # if ColorValidator.re_hex.fullmatch(v_normalized): + if fullmatch(ColorValidator.re_hex, v_normalized): + # valid hex color (e.g. #f34ab3) + return v + elif fullmatch(ColorValidator.re_rgb_etc, v_normalized): + # elif ColorValidator.re_rgb_etc.fullmatch(v_normalized): + # Valid rgb(a), hsl(a), hsv(a) color + # (e.g. rgba(10, 234, 200, 50%) + return v + elif fullmatch(ColorValidator.re_ddk, v_normalized): + # Valid var(--*) DDK theme variable, inspired by CSS syntax + # (e.g. var(--accent) ) + # DDK will crawl & eval var(-- colors for Graph theming + return v + elif v_normalized in ColorValidator.named_colors: + # Valid named color (e.g. 'coral') + return v + else: + # Not a valid color + return None + + +class ColorlistValidator(BaseValidator): + """ + "colorlist": { + "description": "A list of colors. Must be an {array} containing + valid colors.", + "requiredOpts": [], + "otherOpts": [ + "dflt" + ] + } + """ + + def __init__(self, plotly_name, parent_name, **kwargs): + super(ColorlistValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + def description(self): + return """\ + The '{plotly_name}' property is a colorlist that may be specified + as a tuple, list, one-dimensional numpy array, or pandas Series of valid + color strings""".format(plotly_name=self.plotly_name) + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif is_array(v): + validated_v = [ + ColorValidator.perform_validate_coerce(e, allow_number=False) for e in v + ] + + invalid_els = [ + el for el, validated_el in zip(v, validated_v) if validated_el is None + ] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(v) + else: + self.raise_invalid_val(v) + return v + + +class ColorscaleValidator(BaseValidator): + """ + "colorscale": { + "description": "A Plotly colorscale either picked by a name: + (any of Greys, YlGnBu, Greens, YlOrRd, Bluered, + RdBu, Reds, Blues, Picnic, Rainbow, Portland, + Jet, Hot, Blackbody, Earth, Electric, Viridis) + customized as an {array} of 2-element {arrays} + where the first element is the normalized color + level value (starting at *0* and ending at *1*), + and the second item is a valid color string.", + "requiredOpts": [], + "otherOpts": [ + "dflt" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, **kwargs): + super(ColorscaleValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # named colorscales initialized on first use + self._named_colorscales = None + + @property + def named_colorscales(self): + if self._named_colorscales is None: + import inspect + import itertools + from plotly import colors + + colorscale_members = itertools.chain( + inspect.getmembers(colors.sequential), + inspect.getmembers(colors.diverging), + inspect.getmembers(colors.cyclical), + ) + + self._named_colorscales = { + c[0].lower(): c[1] + for c in colorscale_members + if isinstance(c, tuple) + and len(c) == 2 + and isinstance(c[0], str) + and isinstance(c[1], list) + and not c[0].endswith("_r") + and not c[0].startswith("_") + } + + return self._named_colorscales + + def description(self): + colorscales_str = "\n".join( + textwrap.wrap( + repr(sorted(list(self.named_colorscales))), + initial_indent=" " * 12, + subsequent_indent=" " * 13, + break_on_hyphens=False, + width=80, + ) + ) + + desc = """\ + The '{plotly_name}' property is a colorscale and may be + specified as: + - A list of colors that will be spaced evenly to create the colorscale. + Many predefined colorscale lists are included in the sequential, diverging, + and cyclical modules in the plotly.colors package. + - A list of 2-element lists where the first element is the + normalized color level value (starting at 0 and ending at 1), + and the second item is a valid color string. + (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) + - One of the following named colorscales: +{colorscales_str}. + Appending '_r' to a named colorscale reverses it. +""".format(plotly_name=self.plotly_name, colorscales_str=colorscales_str) + + return desc + + def validate_coerce(self, v): + v_valid = False + + if v is None: + v_valid = True + elif isinstance(v, str): + v_lower = v.lower() + if v_lower in self.named_colorscales: + # Convert to color list + v = self.named_colorscales[v_lower] + v_valid = True + elif v_lower.endswith("_r") and v_lower[:-2] in self.named_colorscales: + v = self.named_colorscales[v_lower[:-2]][::-1] + v_valid = True + # + if v_valid: + # Convert to list of lists colorscale + d = len(v) - 1 + v = [[(1.0 * i) / (1.0 * d), x] for i, x in enumerate(v)] + + elif is_array(v) and len(v) > 0: + # If firset element is a string, treat as colorsequence + if isinstance(v[0], str): + invalid_els = [ + e for e in v if ColorValidator.perform_validate_coerce(e) is None + ] + + if len(invalid_els) == 0: + v_valid = True + + # Convert to list of lists colorscale + d = len(v) - 1 + v = [[(1.0 * i) / (1.0 * d), x] for i, x in enumerate(v)] + else: + invalid_els = [ + e + for e in v + if ( + not is_array(e) + or len(e) != 2 + or not isinstance(e[0], numbers.Number) + or not (0 <= e[0] <= 1) + or not isinstance(e[1], str) + or ColorValidator.perform_validate_coerce(e[1]) is None + ) + ] + + if len(invalid_els) == 0: + v_valid = True + + # Convert to list of lists + v = [ + [e[0], ColorValidator.perform_validate_coerce(e[1])] for e in v + ] + + if not v_valid: + self.raise_invalid_val(v) + + return v + + def present(self, v): + # Return-type must be immutable + if v is None: + return None + elif isinstance(v, str): + return v + else: + return tuple([tuple(e) for e in v]) + + +class AngleValidator(BaseValidator): + """ + "angle": { + "description": "A number (in degree) between -180 and 180.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "arrayOk" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, array_ok=False, **kwargs): + super(AngleValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is a angle (in degrees) that may be + specified as a number between -180 and 180{array_ok}. + Numeric values outside this range are converted to the equivalent value + (e.g. 270 is converted to -90). + """.format( + plotly_name=self.plotly_name, + array_ok=( + ", or a list, numpy array or other iterable thereof" + if self.array_ok + else "" + ), + ) + + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + try: + v_array = copy_to_readonly_numpy_array(v, force_numeric=True) + except (ValueError, TypeError, OverflowError): + self.raise_invalid_val(v) + v = v_array # Always numeric numpy array + # Normalize v onto the interval [-180, 180) + v = (v + 180) % 360 - 180 + elif self.array_ok and is_simple_array(v): + # Check numeric + invalid_els = [e for e in v if not isinstance(e, numbers.Number)] + + if invalid_els: + self.raise_invalid_elements(invalid_els[:10]) + + v = [(x + 180) % 360 - 180 for x in to_scalar_or_list(v)] + elif not isinstance(v, numbers.Number): + self.raise_invalid_val(v) + else: + # Normalize v onto the interval [-180, 180) + v = (v + 180) % 360 - 180 + + return v + + +class SubplotidValidator(BaseValidator): + """ + "subplotid": { + "description": "An id string of a subplot type (given by dflt), + optionally followed by an integer >1. e.g. if + dflt='geo', we can have 'geo', 'geo2', 'geo3', + ...", + "requiredOpts": [ + "dflt" + ], + "otherOpts": [ + "arrayOk", + "regex" + ] + } + """ + + def __init__( + self, plotly_name, parent_name, dflt=None, regex=None, array_ok=False, **kwargs + ): + if dflt is None and regex is None: + raise ValueError("One or both of regex and deflt must be specified") + + super(SubplotidValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + if dflt is not None: + self.base = dflt + else: + # e.g. regex == '/^y([2-9]|[1-9][0-9]+)?$/' + self.base = re.match(r"/\^(\w+)", regex).group(1) + + self.regex = self.base + r"(\d*)" + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property is an identifier of a particular + subplot, of type '{base}', that may be specified as: + - the string '{base}' optionally followed by an integer >= 1 + (e.g. '{base}', '{base}1', '{base}2', '{base}3', etc.)""".format( + plotly_name=self.plotly_name, base=self.base + ) + if self.array_ok: + desc += """ + - A tuple or list of the above""" + return desc + + def validate_coerce(self, v): + def coerce(value): + if not isinstance(value, str): + return value, False + match = fullmatch(self.regex, value) + if not match: + return value, False + else: + digit_str = match.group(1) + if len(digit_str) > 0 and int(digit_str) == 0: + return value, False + elif len(digit_str) > 0 and int(digit_str) == 1: + return self.base, True + else: + return value, True + + if v is None: + pass + elif self.array_ok and is_simple_array(v): + values = [] + invalid_els = [] + for e in v: + coerced_e, success = coerce(e) + values.append(coerced_e) + if not success: + invalid_els.append(coerced_e) + if len(invalid_els) > 0: + self.raise_invalid_elements(invalid_els[:10]) + return values + else: + v, success = coerce(v) + if not success: + self.raise_invalid_val(self.base) + return v + + +class FlaglistValidator(BaseValidator): + """ + "flaglist": { + "description": "A string representing a combination of flags + (order does not matter here). Combine any of the + available `flags` with *+*. + (e.g. ('lines+markers')). Values in `extras` + cannot be combined.", + "requiredOpts": [ + "flags" + ], + "otherOpts": [ + "dflt", + "extras", + "arrayOk" + ] + }, + """ + + def __init__( + self, plotly_name, parent_name, flags, extras=None, array_ok=False, **kwargs + ): + super(FlaglistValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.flags = flags + self.extras = extras if extras is not None else [] + self.array_ok = array_ok + + def description(self): + desc = ( + """\ + The '{plotly_name}' property is a flaglist and may be specified + as a string containing:""" + ).format(plotly_name=self.plotly_name) + + # Flags + desc = desc + ( + """ + - Any combination of {flags} joined with '+' characters + (e.g. '{eg_flag}')""" + ).format(flags=self.flags, eg_flag="+".join(self.flags[:2])) + + # Extras + if self.extras: + desc = desc + ( + """ + OR exactly one of {extras} (e.g. '{eg_extra}')""" + ).format(extras=self.extras, eg_extra=self.extras[-1]) + + if self.array_ok: + desc = ( + desc + + """ + - A list or array of the above""" + ) + + return desc + + def vc_scalar(self, v): + if isinstance(v, str): + v = v.strip() + + if v in self.extras: + return v + + if not isinstance(v, str): + return None + + # To be generous we accept flags separated on plus ('+'), + # or comma (',') and we accept whitespace around the flags + split_vals = [e.strip() for e in re.split("[,+]", v)] + + # Are all flags valid names? + if all(f in self.flags for f in split_vals): + return "+".join(split_vals) + else: + return None + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_array(v): + # Coerce individual strings + validated_v = [self.vc_scalar(e) for e in v] + + invalid_els = [ + el for el, validated_el in zip(v, validated_v) if validated_el is None + ] + if invalid_els: + self.raise_invalid_elements(invalid_els) + + if is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(validated_v, kind="U") + else: + v = to_scalar_or_list(v) + else: + validated_v = self.vc_scalar(v) + if validated_v is None: + self.raise_invalid_val(v) + + v = validated_v + + return v + + +class AnyValidator(BaseValidator): + """ + "any": { + "description": "Any type.", + "requiredOpts": [], + "otherOpts": [ + "dflt", + "values", + "arrayOk" + ] + }, + """ + + def __init__(self, plotly_name, parent_name, values=None, array_ok=False, **kwargs): + super(AnyValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.values = values + self.array_ok = array_ok + + def description(self): + desc = """\ + The '{plotly_name}' property accepts values of any type + """.format(plotly_name=self.plotly_name) + return desc + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + pass + elif self.array_ok and is_homogeneous_array(v): + v = copy_to_readonly_numpy_array(v, kind="O") + elif self.array_ok and is_simple_array(v): + v = to_scalar_or_list(v) + return v + + +class InfoArrayValidator(BaseValidator): + """ + "info_array": { + "description": "An {array} of plot information.", + "requiredOpts": [ + "items" + ], + "otherOpts": [ + "dflt", + "freeLength", + "dimensions" + ] + } + """ + + def __init__( + self, + plotly_name, + parent_name, + items, + free_length=None, + dimensions=None, + **kwargs, + ): + super(InfoArrayValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.items = items + self.dimensions = dimensions if dimensions else 1 + self.free_length = free_length + + # Instantiate validators for each info array element + self.item_validators = [] + info_array_items = self.items if isinstance(self.items, list) else [self.items] + + for i, item in enumerate(info_array_items): + element_name = "{name}[{i}]".format(name=plotly_name, i=i) + item_validator = InfoArrayValidator.build_validator( + item, element_name, parent_name + ) + self.item_validators.append(item_validator) + + def description(self): + # Cases + # 1) self.items is array, self.dimensions is 1 + # a) free_length=True + # b) free_length=False + # 2) self.items is array, self.dimensions is 2 + # (requires free_length=True) + # 3) self.items is scalar (requires free_length=True) + # a) dimensions=1 + # b) dimensions=2 + # + # dimensions can be set to '1-2' to indicate the both are accepted + # + desc = """\ + The '{plotly_name}' property is an info array that may be specified as:\ +""".format(plotly_name=self.plotly_name) + + if isinstance(self.items, list): + # ### Case 1 ### + if self.dimensions in (1, "1-2"): + upto = " up to" if self.free_length and self.dimensions == 1 else "" + desc += """ + + * a list or tuple of{upto} {N} elements where:\ +""".format(upto=upto, N=len(self.item_validators)) + + for i, item_validator in enumerate(self.item_validators): + el_desc = item_validator.description().strip() + desc = ( + desc + + """ +({i}) {el_desc}""".format(i=i, el_desc=el_desc) + ) + + # ### Case 2 ### + if self.dimensions in ("1-2", 2): + assert self.free_length + + desc += """ + + * a 2D list where:""" + for i, item_validator in enumerate(self.item_validators): + # Update name for 2d + orig_name = item_validator.plotly_name + item_validator.plotly_name = "{name}[i][{i}]".format( + name=self.plotly_name, i=i + ) + + el_desc = item_validator.description().strip() + desc = ( + desc + + """ +({i}) {el_desc}""".format(i=i, el_desc=el_desc) + ) + item_validator.plotly_name = orig_name + else: + # ### Case 3 ### + assert self.free_length + item_validator = self.item_validators[0] + orig_name = item_validator.plotly_name + + if self.dimensions in (1, "1-2"): + item_validator.plotly_name = "{name}[i]".format(name=self.plotly_name) + + el_desc = item_validator.description().strip() + + desc += """ + * a list of elements where: + {el_desc} +""".format(el_desc=el_desc) + + if self.dimensions in ("1-2", 2): + item_validator.plotly_name = "{name}[i][j]".format( + name=self.plotly_name + ) + + el_desc = item_validator.description().strip() + desc += """ + * a 2D list where: + {el_desc} +""".format(el_desc=el_desc) + + item_validator.plotly_name = orig_name + + return desc + + @staticmethod + def build_validator(validator_info, plotly_name, parent_name): + datatype = validator_info["valType"] # type: str + validator_classname = datatype.title().replace("_", "") + "Validator" + validator_class = eval(validator_classname) + + kwargs = { + k: validator_info[k] + for k in validator_info + if k not in ["valType", "description", "role"] + } + + return validator_class( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + def validate_element_with_indexed_name(self, val, validator, inds): + """ + Helper to add indexes to a validator's name, call validate_coerce on + a value, then restore the original validator name. + + This makes sure that if a validation error message is raised, the + property name the user sees includes the index(es) of the offending + element. + + Parameters + ---------- + val: + A value to be validated + validator + A validator + inds + List of one or more non-negative integers that represent the + nested index of the value being validated + Returns + ------- + val + validated value + + Raises + ------ + ValueError + if val fails validation + """ + orig_name = validator.plotly_name + new_name = self.plotly_name + for i in inds: + new_name += "[" + str(i) + "]" + validator.plotly_name = new_name + try: + val = validator.validate_coerce(val) + finally: + validator.plotly_name = orig_name + + return val + + def validate_coerce(self, v): + if is_none_or_typed_array_spec(v): + return None + elif not is_array(v): + self.raise_invalid_val(v) + + # Save off original v value to use in error reporting + orig_v = v + + # Convert everything into nested lists + # This way we don't need to worry about nested numpy arrays + v = to_scalar_or_list(v) + + is_v_2d = v and is_array(v[0]) + + if is_v_2d and self.dimensions in ("1-2", 2): + if is_array(self.items): + # e.g. 2D list as parcoords.dimensions.constraintrange + # check that all items are there for each nested element + for i, row in enumerate(v): + # Check row length + if not is_array(row) or len(row) != len(self.items): + self.raise_invalid_val(orig_v[i], [i]) + + for j, validator in enumerate(self.item_validators): + row[j] = self.validate_element_with_indexed_name( + v[i][j], validator, [i, j] + ) + else: + # e.g. 2D list as layout.grid.subplots + # check that all elements match individual validator + validator = self.item_validators[0] + for i, row in enumerate(v): + if not is_array(row): + self.raise_invalid_val(orig_v[i], [i]) + + for j, el in enumerate(row): + row[j] = self.validate_element_with_indexed_name( + el, validator, [i, j] + ) + elif v and self.dimensions == 2: + # e.g. 1D list passed as layout.grid.subplots + self.raise_invalid_val(orig_v[0], [0]) + elif not is_array(self.items): + # e.g. 1D list passed as layout.grid.xaxes + validator = self.item_validators[0] + for i, el in enumerate(v): + v[i] = self.validate_element_with_indexed_name(el, validator, [i]) + + elif not self.free_length and len(v) != len(self.item_validators): + # e.g. 3 element list as layout.xaxis.range + self.raise_invalid_val(orig_v) + elif self.free_length and len(v) > len(self.item_validators): + # e.g. 4 element list as layout.updatemenu.button.args + self.raise_invalid_val(orig_v) + else: + # We have a 1D array of the correct length + for i, (el, validator) in enumerate(zip(v, self.item_validators)): + # Validate coerce elements + v[i] = validator.validate_coerce(el) + + return v + + def present(self, v): + if v is None: + return None + else: + if ( + self.dimensions == 2 + or self.dimensions == "1-2" + and v + and is_array(v[0]) + ): + # 2D case + v = copy.deepcopy(v) + for row in v: + for i, (el, validator) in enumerate(zip(row, self.item_validators)): + row[i] = validator.present(el) + + return tuple(tuple(row) for row in v) + else: + # 1D case + v = copy.copy(v) + # Call present on each of the item validators + for i, (el, validator) in enumerate(zip(v, self.item_validators)): + # Validate coerce elements + v[i] = validator.present(el) + + # Return tuple form of + return tuple(v) + + +class LiteralValidator(BaseValidator): + """ + Validator for readonly literal values + """ + + def __init__(self, plotly_name, parent_name, val, **kwargs): + super(LiteralValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + self.val = val + + def validate_coerce(self, v): + if v != self.val: + raise ValueError( + """\ + The '{plotly_name}' property of {parent_name} is read-only""".format( + plotly_name=self.plotly_name, parent_name=self.parent_name + ) + ) + else: + return v + + +class DashValidator(EnumeratedValidator): + """ + Special case validator for handling dash properties that may be specified + as lists of dash lengths. These are not currently specified in the + schema. + + "dash": { + "valType": "string", + "values": [ + "solid", + "dot", + "dash", + "longdash", + "dashdot", + "longdashdot" + ], + "dflt": "solid", + "role": "style", + "editType": "style", + "description": "Sets the dash style of lines. Set to a dash type + string (*solid*, *dot*, *dash*, *longdash*, *dashdot*, or + *longdashdot*) or a dash length list in px (eg *5px,10px,2px,2px*)." + }, + """ + + def __init__(self, plotly_name, parent_name, values, **kwargs): + # Add regex to handle dash length lists + dash_list_regex = r"/^\d+(\.\d+)?(px|%)?((,|\s)\s*\d+(\.\d+)?(px|%)?)*$/" + + values = values + [dash_list_regex] + + # Call EnumeratedValidator superclass + super(DashValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, values=values, **kwargs + ) + + def description(self): + # Separate regular values from regular expressions + enum_vals = [] + enum_regexs = [] + for v, regex in zip(self.values, self.val_regexs): + if regex is not None: + enum_regexs.append(regex.pattern) + else: + enum_vals.append(v) + desc = """\ + The '{name}' property is an enumeration that may be specified as:""".format( + name=self.plotly_name + ) + + if enum_vals: + enum_vals_str = "\n".join( + textwrap.wrap( + repr(enum_vals), + initial_indent=" " * 12, + subsequent_indent=" " * 12, + break_on_hyphens=False, + width=80, + ) + ) + + desc = ( + desc + + """ + - One of the following dash styles: +{enum_vals_str}""".format(enum_vals_str=enum_vals_str) + ) + + desc = ( + desc + + """ + - A string containing a dash length list in pixels or percentages + (e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.) +""" + ) + return desc + + +class ImageUriValidator(BaseValidator): + _PIL = None + + try: + _PIL = import_module("PIL") + except ImportError: + pass + + def __init__(self, plotly_name, parent_name, **kwargs): + super(ImageUriValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + def description(self): + desc = """\ + The '{plotly_name}' property is an image URI that may be specified as: + - A remote image URI string + (e.g. 'http://www.somewhere.com/image.png') + - A data URI image string + (e.g. 'data:image/png;base64,iVBORw0KGgoAAAANSU') + - A PIL.Image.Image object which will be immediately converted + to a data URI image string + See http://pillow.readthedocs.io/en/latest/reference/Image.html + """.format(plotly_name=self.plotly_name) + return desc + + def validate_coerce(self, v): + if v is None: + pass + elif isinstance(v, str): + # Future possibilities: + # - Detect filesystem system paths and convert to URI + # - Validate either url or data uri + pass + elif self._PIL and isinstance(v, self._PIL.Image.Image): + # Convert PIL image to png data uri string + v = self.pil_image_to_uri(v) + else: + self.raise_invalid_val(v) + + return v + + @staticmethod + def pil_image_to_uri(v): + in_mem_file = io.BytesIO() + v.save(in_mem_file, format="PNG") + in_mem_file.seek(0) + img_bytes = in_mem_file.read() + base64_encoded_result_bytes = base64.b64encode(img_bytes) + base64_encoded_result_str = base64_encoded_result_bytes.decode("ascii") + v = "data:image/png;base64,{base64_encoded_result_str}".format( + base64_encoded_result_str=base64_encoded_result_str + ) + return v + + +class CompoundValidator(BaseValidator): + def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs): + super(CompoundValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Save element class string + self.data_class_str = data_class_str + self._data_class = None + self.data_docs = data_docs + self.module_str = CompoundValidator.compute_graph_obj_module_str( + self.data_class_str, parent_name + ) + + @staticmethod + def compute_graph_obj_module_str(data_class_str, parent_name): + if parent_name == "frame" and data_class_str in ["Data", "Layout"]: + # Special case. There are no graph_objs.frame.Data or + # graph_objs.frame.Layout classes. These are remapped to + # graph_objs.Data and graph_objs.Layout + + parent_parts = parent_name.split(".") + module_str = ".".join(["plotly.graph_objs"] + parent_parts[1:]) + elif parent_name == "layout.template" and data_class_str == "Layout": + # Remap template's layout to regular layout + module_str = "plotly.graph_objs" + elif "layout.template.data" in parent_name: + # Remap template's traces to regular traces + parent_name = parent_name.replace("layout.template.data.", "") + if parent_name: + module_str = "plotly.graph_objs." + parent_name + else: + module_str = "plotly.graph_objs" + elif parent_name: + module_str = "plotly.graph_objs." + parent_name + else: + module_str = "plotly.graph_objs" + + return module_str + + @property + def data_class(self): + if self._data_class is None: + module = import_module(self.module_str) + self._data_class = getattr(module, self.data_class_str) + + return self._data_class + + def description(self): + desc = ( + """\ + The '{plotly_name}' property is an instance of {class_str} + that may be specified as: + - An instance of :class:`{module_str}.{class_str}` + - A dict of string/value properties that will be passed + to the {class_str} constructor""" + ).format( + plotly_name=self.plotly_name, + class_str=self.data_class_str, + module_str=self.module_str, + ) + + return desc + + def validate_coerce(self, v, skip_invalid=False, _validate=True): + if v is None: + v = self.data_class() + + elif isinstance(v, dict): + v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate) + + elif isinstance(v, self.data_class): + # Copy object + v = self.data_class(v) + else: + if skip_invalid: + v = self.data_class() + else: + self.raise_invalid_val(v) + + v._plotly_name = self.plotly_name + return v + + def present(self, v): + # Return compound object as-is + return v + + +class TitleValidator(CompoundValidator): + """ + This is a special validator to allow compound title properties + (e.g. layout.title, layout.xaxis.title, etc.) to be set as strings + or numbers. These strings are mapped to the 'text' property of the + compound validator. + """ + + def __init__(self, *args, **kwargs): + super(TitleValidator, self).__init__(*args, **kwargs) + + def validate_coerce(self, v, skip_invalid=False): + if isinstance(v, (str, int, float)): + v = {"text": v} + return super(TitleValidator, self).validate_coerce(v, skip_invalid=skip_invalid) + + +class CompoundArrayValidator(BaseValidator): + def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs): + super(CompoundArrayValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + # Save element class string + self.data_class_str = data_class_str + self._data_class = None + + self.data_docs = data_docs + self.module_str = CompoundValidator.compute_graph_obj_module_str( + self.data_class_str, parent_name + ) + + def description(self): + desc = ( + """\ + The '{plotly_name}' property is a tuple of instances of + {class_str} that may be specified as: + - A list or tuple of instances of {module_str}.{class_str} + - A list or tuple of dicts of string/value properties that + will be passed to the {class_str} constructor""" + ).format( + plotly_name=self.plotly_name, + class_str=self.data_class_str, + module_str=self.module_str, + ) + + return desc + + @property + def data_class(self): + if self._data_class is None: + module = import_module(self.module_str) + self._data_class = getattr(module, self.data_class_str) + + return self._data_class + + def validate_coerce(self, v, skip_invalid=False): + if v is None: + v = [] + + elif isinstance(v, (list, tuple)): + res = [] + invalid_els = [] + for v_el in v: + if isinstance(v_el, self.data_class): + res.append(self.data_class(v_el)) + elif isinstance(v_el, dict): + res.append(self.data_class(v_el, skip_invalid=skip_invalid)) + else: + if skip_invalid: + res.append(self.data_class()) + else: + res.append(None) + invalid_els.append(v_el) + + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(res) + else: + if skip_invalid: + v = [] + else: + self.raise_invalid_val(v) + + return v + + def present(self, v): + # Return compound object as tuple + return tuple(v) + + +class BaseDataValidator(BaseValidator): + def __init__( + self, class_strs_map, plotly_name, parent_name, set_uid=False, **kwargs + ): + super(BaseDataValidator, self).__init__( + plotly_name=plotly_name, parent_name=parent_name, **kwargs + ) + + self.class_strs_map = class_strs_map + self._class_map = {} + self.set_uid = set_uid + + def description(self): + trace_types = str(list(self.class_strs_map.keys())) + + trace_types_wrapped = "\n".join( + textwrap.wrap( + trace_types, + initial_indent=" One of: ", + subsequent_indent=" " * 21, + width=79 - 12, + ) + ) + + desc = ( + """\ + The '{plotly_name}' property is a tuple of trace instances + that may be specified as: + - A list or tuple of trace instances + (e.g. [Scatter(...), Bar(...)]) + - A single trace instance + (e.g. Scatter(...), Bar(...), etc.) + - A list or tuple of dicts of string/value properties where: + - The 'type' property specifies the trace type +{trace_types} + + - All remaining properties are passed to the constructor of + the specified trace type + + (e.g. [{{'type': 'scatter', ...}}, {{'type': 'bar, ...}}])""" + ).format(plotly_name=self.plotly_name, trace_types=trace_types_wrapped) + + return desc + + def get_trace_class(self, trace_name): + # Import trace classes + if trace_name not in self._class_map: + trace_module = import_module("plotly.graph_objs") + trace_class_name = self.class_strs_map[trace_name] + self._class_map[trace_name] = getattr(trace_module, trace_class_name) + + return self._class_map[trace_name] + + def validate_coerce(self, v, skip_invalid=False, _validate=True): + from plotly.basedatatypes import BaseTraceType + + # Import Histogram2dcontour, this is the deprecated name of the + # Histogram2dContour trace. + from plotly.graph_objs import Histogram2dcontour + + if v is None: + v = [] + else: + if not isinstance(v, (list, tuple)): + v = [v] + + res = [] + invalid_els = [] + for v_el in v: + if isinstance(v_el, BaseTraceType): + if isinstance(v_el, Histogram2dcontour): + v_el = dict(type="histogram2dcontour", **v_el._props) + else: + v_el = v_el._props + + if isinstance(v_el, dict): + type_in_v_el = "type" in v_el + trace_type = v_el.pop("type", "scatter") + + if trace_type not in self.class_strs_map: + if skip_invalid: + # Treat as scatter trace + trace = self.get_trace_class("scatter")( + skip_invalid=skip_invalid, _validate=_validate, **v_el + ) + res.append(trace) + else: + res.append(None) + invalid_els.append(v_el) + else: + trace = self.get_trace_class(trace_type)( + skip_invalid=skip_invalid, _validate=_validate, **v_el + ) + res.append(trace) + + if type_in_v_el: + # Restore type in v_el + v_el["type"] = trace_type + else: + if skip_invalid: + # Add empty scatter trace + trace = self.get_trace_class("scatter")() + res.append(trace) + else: + res.append(None) + invalid_els.append(v_el) + + if invalid_els: + self.raise_invalid_elements(invalid_els) + + v = to_scalar_or_list(res) + + # Set new UIDs + if self.set_uid: + for trace in v: + trace.uid = str(uuid.uuid4()) + + return v + + +class BaseTemplateValidator(CompoundValidator): + def __init__(self, plotly_name, parent_name, data_class_str, data_docs, **kwargs): + super(BaseTemplateValidator, self).__init__( + plotly_name=plotly_name, + parent_name=parent_name, + data_class_str=data_class_str, + data_docs=data_docs, + **kwargs, + ) + + def description(self): + compound_description = super(BaseTemplateValidator, self).description() + compound_description += """ + - The name of a registered template where current registered templates + are stored in the plotly.io.templates configuration object. The names + of all registered templates can be retrieved with: + >>> import plotly.io as pio + >>> list(pio.templates) # doctest: +ELLIPSIS + ['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', ...] + + - A string containing multiple registered template names, joined on '+' + characters (e.g. 'template1+template2'). In this case the resulting + template is computed by merging together the collection of registered + templates""" + + return compound_description + + def validate_coerce(self, v, skip_invalid=False): + import plotly.io as pio + + try: + # Check if v is a template identifier + # (could be any hashable object) + if v in pio.templates: + return copy.deepcopy(pio.templates[v]) + # Otherwise, if v is a string, check to see if it consists of + # multiple template names joined on '+' characters + elif isinstance(v, str): + template_names = v.split("+") + if all([name in pio.templates for name in template_names]): + return pio.templates.merge_templates(*template_names) + + except TypeError: + # v is un-hashable + pass + + # Check for empty template + if v == {} or isinstance(v, self.data_class) and v.to_plotly_json() == {}: + # Replace empty template with {'data': {'scatter': [{}]}} so that we can + # tell the difference between an un-initialized template and a template + # explicitly set to empty. + return self.data_class(data_scatter=[{}]) + + return super(BaseTemplateValidator, self).validate_coerce( + v, skip_invalid=skip_invalid + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/data_utils.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb05b03114c4475fe2040d7808a1f3b63676558 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/data_utils.py @@ -0,0 +1,75 @@ +from io import BytesIO +import base64 +from .png import Writer, from_array + +try: + from PIL import Image + + pil_imported = True +except ImportError: + pil_imported = False + + +def image_array_to_data_uri(img, backend="pil", compression=4, ext="png"): + """Converts a numpy array of uint8 into a base64 png or jpg string. + + Parameters + ---------- + img: ndarray of uint8 + array image + backend: str + 'auto', 'pil' or 'pypng'. If 'auto', Pillow is used if installed, + otherwise pypng. + compression: int, between 0 and 9 + compression level to be passed to the backend + ext: str, 'png' or 'jpg' + compression format used to generate b64 string + """ + # PIL and pypng error messages are quite obscure so we catch invalid compression values + if compression < 0 or compression > 9: + raise ValueError("compression level must be between 0 and 9.") + alpha = False + if img.ndim == 2: + mode = "L" + elif img.ndim == 3 and img.shape[-1] == 3: + mode = "RGB" + elif img.ndim == 3 and img.shape[-1] == 4: + mode = "RGBA" + alpha = True + else: + raise ValueError("Invalid image shape") + if backend == "auto": + backend = "pil" if pil_imported else "pypng" + if ext != "png" and backend != "pil": + raise ValueError("jpg binary strings are only available with PIL backend") + + if backend == "pypng": + ndim = img.ndim + sh = img.shape + if ndim == 3: + img = img.reshape((sh[0], sh[1] * sh[2])) + w = Writer( + sh[1], sh[0], greyscale=(ndim == 2), alpha=alpha, compression=compression + ) + img_png = from_array(img, mode=mode) + prefix = "data:image/png;base64," + with BytesIO() as stream: + w.write(stream, img_png.rows) + base64_string = prefix + base64.b64encode(stream.getvalue()).decode("utf-8") + else: # pil + if not pil_imported: + raise ImportError( + "pillow needs to be installed to use `backend='pil'. Please" + "install pillow or use `backend='pypng'." + ) + pil_img = Image.fromarray(img) + if ext == "jpg" or ext == "jpeg": + prefix = "data:image/jpeg;base64," + ext = "jpeg" + else: + prefix = "data:image/png;base64," + ext = "png" + with BytesIO() as stream: + pil_img.save(stream, format=ext, compress_level=compression) + base64_string = prefix + base64.b64encode(stream.getvalue()).decode("utf-8") + return base64_string diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/exceptions.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..836ef59e21532334561044a7bf2f9db92d72bb6d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/exceptions.py @@ -0,0 +1,97 @@ +class PlotlyError(Exception): + pass + + +class PlotlyEmptyDataError(PlotlyError): + pass + + +class PlotlyGraphObjectError(PlotlyError): + def __init__(self, message="", path=(), notes=()): + """ + General graph object error for validation failures. + + :param (str|unicode) message: The error message. + :param (iterable) path: A path pointing to the error. + :param notes: Add additional notes, but keep default exception message. + + """ + self.message = message + self.plain_message = message # for backwards compat + self.path = list(path) + self.notes = notes + super(PlotlyGraphObjectError, self).__init__(message) + + def __str__(self): + """This is called by Python to present the error message.""" + format_dict = { + "message": self.message, + "path": "[" + "][".join(repr(k) for k in self.path) + "]", + "notes": "\n".join(self.notes), + } + return "{message}\n\nPath To Error: {path}\n\n{notes}".format(**format_dict) + + +class PlotlyDictKeyError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"attribute": path[-1], "object_name": obj._name} + message = "'{attribute}' is not allowed in '{object_name}'".format( + **format_dict + ) + notes = [obj.help(return_help=True)] + list(notes) + super(PlotlyDictKeyError, self).__init__( + message=message, path=path, notes=notes + ) + + +class PlotlyDictValueError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"attribute": path[-1], "object_name": obj._name} + message = "'{attribute}' has invalid value inside '{object_name}'".format( + **format_dict + ) + notes = [obj.help(path[-1], return_help=True)] + list(notes) + super(PlotlyDictValueError, self).__init__( + message=message, notes=notes, path=path + ) + + +class PlotlyListEntryError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"index": path[-1], "object_name": obj._name} + message = "Invalid entry found in '{object_name}' at index, '{index}'".format( + **format_dict + ) + notes = [obj.help(return_help=True)] + list(notes) + super(PlotlyListEntryError, self).__init__( + message=message, path=path, notes=notes + ) + + +class PlotlyDataTypeError(PlotlyGraphObjectError): + def __init__(self, obj, path, notes=()): + """See PlotlyGraphObjectError.__init__ for param docs.""" + format_dict = {"index": path[-1], "object_name": obj._name} + message = "Invalid entry found in '{object_name}' at index, '{index}'".format( + **format_dict + ) + note = "It's invalid because it doesn't contain a valid 'type' value." + notes = [note] + list(notes) + super(PlotlyDataTypeError, self).__init__( + message=message, path=path, notes=notes + ) + + +class PlotlyKeyError(KeyError): + """ + KeyErrors are not printed as beautifully as other errors (this is so that + {}[''] prints "KeyError: ''" and not "KeyError:"). So here we use + LookupError's __str__ to make a PlotlyKeyError object which will print nicer + error messages for KeyErrors. + """ + + def __str__(self): + return LookupError.__str__(self) diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/files.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/files.py new file mode 100644 index 0000000000000000000000000000000000000000..68d11bd4a69bdd172b92c7cad32a670dfaa872e1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/files.py @@ -0,0 +1,37 @@ +import os + +PLOTLY_DIR = os.environ.get( + "PLOTLY_DIR", os.path.join(os.path.expanduser("~"), ".plotly") +) +TEST_FILE = os.path.join(PLOTLY_DIR, ".permission_test") + + +def _permissions(): + try: + if not os.path.exists(PLOTLY_DIR): + try: + os.mkdir(PLOTLY_DIR) + except Exception: + # in case of race + if not os.path.isdir(PLOTLY_DIR): + raise + with open(TEST_FILE, "w") as f: + f.write("testing\n") + try: + os.remove(TEST_FILE) + except Exception: + pass + return True + except Exception: # Do not trap KeyboardInterrupt. + return False + + +_file_permissions = None + + +def ensure_writable_plotly_dir(): + # Cache permissions status + global _file_permissions + if _file_permissions is None: + _file_permissions = _permissions() + return _file_permissions diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/importers.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/importers.py new file mode 100644 index 0000000000000000000000000000000000000000..20c77c1c8433649c0e1526e0616294036f9ec64a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/importers.py @@ -0,0 +1,50 @@ +import importlib + + +def relative_import(parent_name, rel_modules=(), rel_classes=()): + """ + Helper function to import submodules lazily in Python 3.7+ + + Parameters + ---------- + rel_modules: list of str + list of submodules to import, of the form .submodule + rel_classes: list of str + list of submodule classes/variables to import, of the form ._submodule.Foo + + Returns + ------- + tuple + Tuple that should be assigned to __all__, __getattr__ in the caller + """ + module_names = {rel_module.split(".")[-1]: rel_module for rel_module in rel_modules} + class_names = {rel_path.split(".")[-1]: rel_path for rel_path in rel_classes} + + def __getattr__(import_name): + # In Python 3.7+, lazy import submodules + + # Check for submodule + if import_name in module_names: + rel_import = module_names[import_name] + return importlib.import_module(rel_import, parent_name) + + # Check for submodule class + if import_name in class_names: + rel_path_parts = class_names[import_name].split(".") + rel_module = ".".join(rel_path_parts[:-1]) + class_name = import_name + class_module = importlib.import_module(rel_module, parent_name) + return getattr(class_module, class_name) + + raise AttributeError( + "module {__name__!r} has no attribute {name!r}".format( + name=import_name, __name__=parent_name + ) + ) + + __all__ = list(module_names) + list(class_names) + + def __dir__(): + return __all__ + + return __all__, __getattr__, __dir__ diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/optional_imports.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/optional_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..a31e087a34fe445683a2c55a20ff8e99d123a24c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/optional_imports.py @@ -0,0 +1,36 @@ +""" +Stand-alone module to provide information about whether optional deps exist. + +""" + +from importlib import import_module +import logging +import sys + +logger = logging.getLogger(__name__) +_not_importable = set() + + +def get_module(name, should_load=True): + """ + Return module or None. Absolute import is required. + + :param (str) name: Dot-separated module path. E.g., 'scipy.stats'. + :raise: (ImportError) Only when exc_msg is defined. + :return: (module|None) If import succeeds, the module will be returned. + + """ + if not should_load: + return sys.modules.get(name, None) + + if name not in _not_importable: + try: + return import_module(name) + except ImportError: + _not_importable.add(name) + except Exception: + _not_importable.add(name) + msg = f"Error importing optional module {name}" + logger.exception(msg) + + return None diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/png.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/png.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9e58560f2867a0fe1d113f83101756c5fcc373 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/png.py @@ -0,0 +1,2350 @@ +#!/usr/bin/env python + +# Vendored code from pypng https://github.com/drj11/pypng +# png.py - PNG encoder/decoder in pure Python +# +# Copyright (C) 2006 Johann C. Rocholl +# Portions Copyright (C) 2009 David Jones +# And probably portions Copyright (C) 2006 Nicko van Someren +# +# Original concept by Johann C. Rocholl. +# +# LICENCE (MIT) +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation files +# (the "Software"), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, +# publish, distribute, sublicense, and/or sell copies of the Software, +# and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +""" +The ``png`` module can read and write PNG files. + +Installation and Overview +------------------------- + +``pip install pypng`` + +For help, type ``import png; help(png)`` in your python interpreter. + +A good place to start is the :class:`Reader` and :class:`Writer` classes. + +Coverage of PNG formats is fairly complete; +all allowable bit depths (1/2/4/8/16/24/32/48/64 bits per pixel) and +colour combinations are supported: + +- greyscale (1/2/4/8/16 bit); +- RGB, RGBA, LA (greyscale with alpha) with 8/16 bits per channel; +- colour mapped images (1/2/4/8 bit). + +Interlaced images, +which support a progressive display when downloading, +are supported for both reading and writing. + +A number of optional chunks can be specified (when writing) +and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``. + +The ``sBIT`` chunk can be used to specify precision for +non-native bit depths. + +Requires Python 3.5 or higher. +Installation is trivial, +but see the ``README.txt`` file (with the source distribution) for details. + +Full use of all features will need some reading of the PNG specification +http://www.w3.org/TR/2003/REC-PNG-20031110/. + +The package also comes with command line utilities. + +- ``pripamtopng`` converts + `Netpbm `_ PAM/PNM files to PNG; +- ``pripngtopam`` converts PNG to file PAM/PNM. + +There are a few more for simple PNG manipulations. + +Spelling and Terminology +------------------------ + +Generally British English spelling is used in the documentation. +So that's "greyscale" and "colour". +This not only matches the author's native language, +it's also used by the PNG specification. + +Colour Models +------------- + +The major colour models supported by PNG (and hence by PyPNG) are: + +- greyscale; +- greyscale--alpha; +- RGB; +- RGB--alpha. + +Also referred to using the abbreviations: L, LA, RGB, RGBA. +Each letter codes a single channel: +*L* is for Luminance or Luma or Lightness (greyscale images); +*A* stands for Alpha, the opacity channel +(used for transparency effects, but higher values are more opaque, +so it makes sense to call it opacity); +*R*, *G*, *B* stand for Red, Green, Blue (colour image). + +Lists, arrays, sequences, and so on +----------------------------------- + +When getting pixel data out of this module (reading) and +presenting data to this module (writing) there are +a number of ways the data could be represented as a Python value. + +The preferred format is a sequence of *rows*, +which each row being a sequence of *values*. +In this format, the values are in pixel order, +with all the values from all the pixels in a row +being concatenated into a single sequence for that row. + +Consider an image that is 3 pixels wide by 2 pixels high, and each pixel +has RGB components: + +Sequence of rows:: + + list([R,G,B, R,G,B, R,G,B], + [R,G,B, R,G,B, R,G,B]) + +Each row appears as its own list, +but the pixels are flattened so that three values for one pixel +simply follow the three values for the previous pixel. + +This is the preferred because +it provides a good compromise between space and convenience. +PyPNG regards itself as at liberty to replace any sequence type with +any sufficiently compatible other sequence type; +in practice each row is an array (``bytearray`` or ``array.array``). + +To allow streaming the outer list is sometimes +an iterator rather than an explicit list. + +An alternative format is a single array holding all the values. + +Array of values:: + + [R,G,B, R,G,B, R,G,B, + R,G,B, R,G,B, R,G,B] + +The entire image is one single giant sequence of colour values. +Generally an array will be used (to save space), not a list. + +The top row comes first, +and within each row the pixels are ordered from left-to-right. +Within a pixel the values appear in the order R-G-B-A +(or L-A for greyscale--alpha). + +There is another format, which should only be used with caution. +It is mentioned because it is used internally, +is close to what lies inside a PNG file itself, +and has some support from the public API. +This format is called *packed*. +When packed, each row is a sequence of bytes (integers from 0 to 255), +just as it is before PNG scanline filtering is applied. +When the bit depth is 8 this is the same as a sequence of rows; +when the bit depth is less than 8 (1, 2 and 4), +several pixels are packed into each byte; +when the bit depth is 16 each pixel value is decomposed into 2 bytes +(and `packed` is a misnomer). +This format is used by the :meth:`Writer.write_packed` method. +It isn't usually a convenient format, +but may be just right if the source data for +the PNG image comes from something that uses a similar format +(for example, 1-bit BMPs, or another PNG file). +""" + +__version__ = "0.0.20" + +import collections +import io # For io.BytesIO +import itertools +import math + +# http://www.python.org/doc/2.4.4/lib/module-operator.html +import operator +import re +import struct +import sys + +# http://www.python.org/doc/2.4.4/lib/module-warnings.html +import warnings +import zlib + +from array import array + + +__all__ = ["Image", "Reader", "Writer", "write_chunks", "from_array"] + + +# The PNG signature. +# http://www.w3.org/TR/PNG/#5PNG-file-signature +signature = struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10) + +# The xstart, ystart, xstep, ystep for the Adam7 interlace passes. +adam7 = ( + (0, 0, 8, 8), + (4, 0, 8, 8), + (0, 4, 4, 8), + (2, 0, 4, 4), + (0, 2, 2, 4), + (1, 0, 2, 2), + (0, 1, 1, 2), +) + + +def adam7_generate(width, height): + """ + Generate the coordinates for the reduced scanlines + of an Adam7 interlaced image + of size `width` by `height` pixels. + + Yields a generator for each pass, + and each pass generator yields a series of (x, y, xstep) triples, + each one identifying a reduced scanline consisting of + pixels starting at (x, y) and taking every xstep pixel to the right. + """ + + for xstart, ystart, xstep, ystep in adam7: + if xstart >= width: + continue + yield ((xstart, y, xstep) for y in range(ystart, height, ystep)) + + +# Models the 'pHYs' chunk (used by the Reader) +Resolution = collections.namedtuple("_Resolution", "x y unit_is_meter") + + +def group(s, n): + return list(zip(*[iter(s)] * n)) + + +def isarray(x): + return isinstance(x, array) + + +def check_palette(palette): + """ + Check a palette argument (to the :class:`Writer` class) for validity. + Returns the palette as a list if okay; + raises an exception otherwise. + """ + + # None is the default and is allowed. + if palette is None: + return None + + p = list(palette) + if not (0 < len(p) <= 256): + raise ProtocolError( + "a palette must have between 1 and 256 entries," + " see https://www.w3.org/TR/PNG/#11PLTE" + ) + seen_triple = False + for i, t in enumerate(p): + if len(t) not in (3, 4): + raise ProtocolError("palette entry %d: entries must be 3- or 4-tuples." % i) + if len(t) == 3: + seen_triple = True + if seen_triple and len(t) == 4: + raise ProtocolError( + "palette entry %d: all 4-tuples must precede all 3-tuples" % i + ) + for x in t: + if int(x) != x or not (0 <= x <= 255): + raise ProtocolError( + "palette entry %d: values must be integer: 0 <= x <= 255" % i + ) + return p + + +def check_sizes(size, width, height): + """ + Check that these arguments, if supplied, are consistent. + Return a (width, height) pair. + """ + + if not size: + return width, height + + if len(size) != 2: + raise ProtocolError("size argument should be a pair (width, height)") + if width is not None and width != size[0]: + raise ProtocolError( + "size[0] (%r) and width (%r) should match when both are used." + % (size[0], width) + ) + if height is not None and height != size[1]: + raise ProtocolError( + "size[1] (%r) and height (%r) should match when both are used." + % (size[1], height) + ) + return size + + +def check_color(c, greyscale, which): + """ + Checks that a colour argument for transparent or background options + is the right form. + Returns the colour + (which, if it's a bare integer, is "corrected" to a 1-tuple). + """ + + if c is None: + return c + if greyscale: + try: + len(c) + except TypeError: + c = (c,) + if len(c) != 1: + raise ProtocolError("%s for greyscale must be 1-tuple" % which) + if not is_natural(c[0]): + raise ProtocolError("%s colour for greyscale must be integer" % which) + else: + if not ( + len(c) == 3 and is_natural(c[0]) and is_natural(c[1]) and is_natural(c[2]) + ): + raise ProtocolError("%s colour must be a triple of integers" % which) + return c + + +class Error(Exception): + def __str__(self): + return self.__class__.__name__ + ": " + " ".join(self.args) + + +class FormatError(Error): + """ + Problem with input file format. + In other words, PNG file does not conform to + the specification in some way and is invalid. + """ + + +class ProtocolError(Error): + """ + Problem with the way the programming interface has been used, + or the data presented to it. + """ + + +class ChunkError(FormatError): + pass + + +class Default: + """The default for the greyscale paramter.""" + + +class Writer: + """ + PNG encoder in pure Python. + """ + + def __init__( + self, + width=None, + height=None, + size=None, + greyscale=Default, + alpha=False, + bitdepth=8, + palette=None, + transparent=None, + background=None, + gamma=None, + compression=None, + interlace=False, + planes=None, + colormap=None, + maxval=None, + chunk_limit=2**20, + x_pixels_per_unit=None, + y_pixels_per_unit=None, + unit_is_meter=False, + ): + """ + Create a PNG encoder object. + + Arguments: + + width, height + Image size in pixels, as two separate arguments. + size + Image size (w,h) in pixels, as single argument. + greyscale + Pixels are greyscale, not RGB. + alpha + Input data has alpha channel (RGBA or LA). + bitdepth + Bit depth: from 1 to 16 (for each channel). + palette + Create a palette for a colour mapped image (colour type 3). + transparent + Specify a transparent colour (create a ``tRNS`` chunk). + background + Specify a default background colour (create a ``bKGD`` chunk). + gamma + Specify a gamma value (create a ``gAMA`` chunk). + compression + zlib compression level: 0 (none) to 9 (more compressed); + default: -1 or None. + interlace + Create an interlaced image. + chunk_limit + Write multiple ``IDAT`` chunks to save memory. + x_pixels_per_unit + Number of pixels a unit along the x axis (write a + `pHYs` chunk). + y_pixels_per_unit + Number of pixels a unit along the y axis (write a + `pHYs` chunk). Along with `x_pixel_unit`, this gives + the pixel size ratio. + unit_is_meter + `True` to indicate that the unit (for the `pHYs` + chunk) is metre. + + The image size (in pixels) can be specified either by using the + `width` and `height` arguments, or with the single `size` + argument. + If `size` is used it should be a pair (*width*, *height*). + + The `greyscale` argument indicates whether input pixels + are greyscale (when true), or colour (when false). + The default is true unless `palette=` is used. + + The `alpha` argument (a boolean) specifies + whether input pixels have an alpha channel (or not). + + `bitdepth` specifies the bit depth of the source pixel values. + Each channel may have a different bit depth. + Each source pixel must have values that are + an integer between 0 and ``2**bitdepth-1``, where + `bitdepth` is the bit depth for the corresponding channel. + For example, 8-bit images have values between 0 and 255. + PNG only stores images with bit depths of + 1,2,4,8, or 16 (the same for all channels). + When `bitdepth` is not one of these values or where + channels have different bit depths, + the next highest valid bit depth is selected, + and an ``sBIT`` (significant bits) chunk is generated + that specifies the original precision of the source image. + In this case the supplied pixel values will be rescaled to + fit the range of the selected bit depth. + + The PNG file format supports many bit depth / colour model + combinations, but not all. + The details are somewhat arcane + (refer to the PNG specification for full details). + Briefly: + Bit depths < 8 (1,2,4) are only allowed with greyscale and + colour mapped images; + colour mapped images cannot have bit depth 16. + + For colour mapped images + (in other words, when the `palette` argument is specified) + the `bitdepth` argument must match one of + the valid PNG bit depths: 1, 2, 4, or 8. + (It is valid to have a PNG image with a palette and + an ``sBIT`` chunk, but the meaning is slightly different; + it would be awkward to use the `bitdepth` argument for this.) + + The `palette` option, when specified, + causes a colour mapped image to be created: + the PNG colour type is set to 3; + `greyscale` must not be true; `alpha` must not be true; + `transparent` must not be set. + The bit depth must be 1,2,4, or 8. + When a colour mapped image is created, + the pixel values are palette indexes and + the `bitdepth` argument specifies the size of these indexes + (not the size of the colour values in the palette). + + The palette argument value should be a sequence of 3- or + 4-tuples. + 3-tuples specify RGB palette entries; + 4-tuples specify RGBA palette entries. + All the 4-tuples (if present) must come before all the 3-tuples. + A ``PLTE`` chunk is created; + if there are 4-tuples then a ``tRNS`` chunk is created as well. + The ``PLTE`` chunk will contain all the RGB triples in the same + sequence; + the ``tRNS`` chunk will contain the alpha channel for + all the 4-tuples, in the same sequence. + Palette entries are always 8-bit. + + If specified, the `transparent` and `background` parameters must be + a tuple with one element for each channel in the image. + Either a 3-tuple of integer (RGB) values for a colour image, or + a 1-tuple of a single integer for a greyscale image. + + If specified, the `gamma` parameter must be a positive number + (generally, a `float`). + A ``gAMA`` chunk will be created. + Note that this will not change the values of the pixels as + they appear in the PNG file, + they are assumed to have already + been converted appropriately for the gamma specified. + + The `compression` argument specifies the compression level to + be used by the ``zlib`` module. + Values from 1 to 9 (highest) specify compression. + 0 means no compression. + -1 and ``None`` both mean that the ``zlib`` module uses + the default level of compession (which is generally acceptable). + + If `interlace` is true then an interlaced image is created + (using PNG's so far only interace method, *Adam7*). + This does not affect how the pixels should be passed in, + rather it changes how they are arranged into the PNG file. + On slow connexions interlaced images can be + partially decoded by the browser to give + a rough view of the image that is + successively refined as more image data appears. + + .. note :: + + Enabling the `interlace` option requires the entire image + to be processed in working memory. + + `chunk_limit` is used to limit the amount of memory used whilst + compressing the image. + In order to avoid using large amounts of memory, + multiple ``IDAT`` chunks may be created. + """ + + # At the moment the `planes` argument is ignored; + # its purpose is to act as a dummy so that + # ``Writer(x, y, **info)`` works, where `info` is a dictionary + # returned by Reader.read and friends. + # Ditto for `colormap`. + + width, height = check_sizes(size, width, height) + del size + + if not is_natural(width) or not is_natural(height): + raise ProtocolError("width and height must be integers") + if width <= 0 or height <= 0: + raise ProtocolError("width and height must be greater than zero") + # http://www.w3.org/TR/PNG/#7Integers-and-byte-order + if width > 2**31 - 1 or height > 2**31 - 1: + raise ProtocolError("width and height cannot exceed 2**31-1") + + if alpha and transparent is not None: + raise ProtocolError("transparent colour not allowed with alpha channel") + + # bitdepth is either single integer, or tuple of integers. + # Convert to tuple. + try: + len(bitdepth) + except TypeError: + bitdepth = (bitdepth,) + for b in bitdepth: + valid = is_natural(b) and 1 <= b <= 16 + if not valid: + raise ProtocolError( + "each bitdepth %r must be a positive integer <= 16" % (bitdepth,) + ) + + # Calculate channels, and + # expand bitdepth to be one element per channel. + palette = check_palette(palette) + alpha = bool(alpha) + colormap = bool(palette) + if greyscale is Default and palette: + greyscale = False + greyscale = bool(greyscale) + if colormap: + color_planes = 1 + planes = 1 + else: + color_planes = (3, 1)[greyscale] + planes = color_planes + alpha + if len(bitdepth) == 1: + bitdepth *= planes + + bitdepth, self.rescale = check_bitdepth_rescale( + palette, bitdepth, transparent, alpha, greyscale + ) + + # These are assertions, because above logic should have + # corrected or raised all problematic cases. + if bitdepth < 8: + assert greyscale or palette + assert not alpha + if bitdepth > 8: + assert not palette + + transparent = check_color(transparent, greyscale, "transparent") + background = check_color(background, greyscale, "background") + + # It's important that the true boolean values + # (greyscale, alpha, colormap, interlace) are converted + # to bool because Iverson's convention is relied upon later on. + self.width = width + self.height = height + self.transparent = transparent + self.background = background + self.gamma = gamma + self.greyscale = greyscale + self.alpha = alpha + self.colormap = colormap + self.bitdepth = int(bitdepth) + self.compression = compression + self.chunk_limit = chunk_limit + self.interlace = bool(interlace) + self.palette = palette + self.x_pixels_per_unit = x_pixels_per_unit + self.y_pixels_per_unit = y_pixels_per_unit + self.unit_is_meter = bool(unit_is_meter) + + self.color_type = 4 * self.alpha + 2 * (not greyscale) + 1 * self.colormap + assert self.color_type in (0, 2, 3, 4, 6) + + self.color_planes = color_planes + self.planes = planes + # :todo: fix for bitdepth < 8 + self.psize = (self.bitdepth / 8) * self.planes + + def write(self, outfile, rows): + """ + Write a PNG image to the output file. + `rows` should be an iterable that yields each row + (each row is a sequence of values). + The rows should be the rows of the original image, + so there should be ``self.height`` rows of + ``self.width * self.planes`` values. + If `interlace` is specified (when creating the instance), + then an interlaced PNG file will be written. + Supply the rows in the normal image order; + the interlacing is carried out internally. + + .. note :: + + Interlacing requires the entire image to be in working memory. + """ + + # Values per row + vpr = self.width * self.planes + + def check_rows(rows): + """ + Yield each row in rows, + but check each row first (for correct width). + """ + for i, row in enumerate(rows): + try: + wrong_length = len(row) != vpr + except TypeError: + # When using an itertools.ichain object or + # other generator not supporting __len__, + # we set this to False to skip the check. + wrong_length = False + if wrong_length: + # Note: row numbers start at 0. + raise ProtocolError( + "Expected %d values but got %d values, in row %d" + % (vpr, len(row), i) + ) + yield row + + if self.interlace: + fmt = "BH"[self.bitdepth > 8] + a = array(fmt, itertools.chain(*check_rows(rows))) + return self.write_array(outfile, a) + + nrows = self.write_passes(outfile, check_rows(rows)) + if nrows != self.height: + raise ProtocolError( + "rows supplied (%d) does not match height (%d)" % (nrows, self.height) + ) + + def write_passes(self, outfile, rows): + """ + Write a PNG image to the output file. + + Most users are expected to find the :meth:`write` or + :meth:`write_array` method more convenient. + + The rows should be given to this method in the order that + they appear in the output file. + For straightlaced images, this is the usual top to bottom ordering. + For interlaced images the rows should have been interlaced before + passing them to this function. + + `rows` should be an iterable that yields each row + (each row being a sequence of values). + """ + + # Ensure rows are scaled (to 4-/8-/16-bit), + # and packed into bytes. + + if self.rescale: + rows = rescale_rows(rows, self.rescale) + + if self.bitdepth < 8: + rows = pack_rows(rows, self.bitdepth) + elif self.bitdepth == 16: + rows = unpack_rows(rows) + + return self.write_packed(outfile, rows) + + def write_packed(self, outfile, rows): + """ + Write PNG file to `outfile`. + `rows` should be an iterator that yields each packed row; + a packed row being a sequence of packed bytes. + + The rows have a filter byte prefixed and + are then compressed into one or more IDAT chunks. + They are not processed any further, + so if bitdepth is other than 1, 2, 4, 8, 16, + the pixel values should have been scaled + before passing them to this method. + + This method does work for interlaced images but it is best avoided. + For interlaced images, the rows should be + presented in the order that they appear in the file. + """ + + self.write_preamble(outfile) + + # http://www.w3.org/TR/PNG/#11IDAT + if self.compression is not None: + compressor = zlib.compressobj(self.compression) + else: + compressor = zlib.compressobj() + + # data accumulates bytes to be compressed for the IDAT chunk; + # it's compressed when sufficiently large. + data = bytearray() + + for i, row in enumerate(rows): + # Add "None" filter type. + # Currently, it's essential that this filter type be used + # for every scanline as + # we do not mark the first row of a reduced pass image; + # that means we could accidentally compute + # the wrong filtered scanline if we used + # "up", "average", or "paeth" on such a line. + data.append(0) + data.extend(row) + if len(data) > self.chunk_limit: + compressed = compressor.compress(data) + if len(compressed): + write_chunk(outfile, b"IDAT", compressed) + data = bytearray() + + compressed = compressor.compress(bytes(data)) + flushed = compressor.flush() + if len(compressed) or len(flushed): + write_chunk(outfile, b"IDAT", compressed + flushed) + # http://www.w3.org/TR/PNG/#11IEND + write_chunk(outfile, b"IEND") + return i + 1 + + def write_preamble(self, outfile): + # http://www.w3.org/TR/PNG/#5PNG-file-signature + outfile.write(signature) + + # http://www.w3.org/TR/PNG/#11IHDR + write_chunk( + outfile, + b"IHDR", + struct.pack( + "!2I5B", + self.width, + self.height, + self.bitdepth, + self.color_type, + 0, + 0, + self.interlace, + ), + ) + + # See :chunk:order + # http://www.w3.org/TR/PNG/#11gAMA + if self.gamma is not None: + write_chunk( + outfile, b"gAMA", struct.pack("!L", int(round(self.gamma * 1e5))) + ) + + # See :chunk:order + # http://www.w3.org/TR/PNG/#11sBIT + if self.rescale: + write_chunk( + outfile, + b"sBIT", + struct.pack("%dB" % self.planes, *[s[0] for s in self.rescale]), + ) + + # :chunk:order: Without a palette (PLTE chunk), + # ordering is relatively relaxed. + # With one, gAMA chunk must precede PLTE chunk + # which must precede tRNS and bKGD. + # See http://www.w3.org/TR/PNG/#5ChunkOrdering + if self.palette: + p, t = make_palette_chunks(self.palette) + write_chunk(outfile, b"PLTE", p) + if t: + # tRNS chunk is optional; + # Only needed if palette entries have alpha. + write_chunk(outfile, b"tRNS", t) + + # http://www.w3.org/TR/PNG/#11tRNS + if self.transparent is not None: + if self.greyscale: + fmt = "!1H" + else: + fmt = "!3H" + write_chunk(outfile, b"tRNS", struct.pack(fmt, *self.transparent)) + + # http://www.w3.org/TR/PNG/#11bKGD + if self.background is not None: + if self.greyscale: + fmt = "!1H" + else: + fmt = "!3H" + write_chunk(outfile, b"bKGD", struct.pack(fmt, *self.background)) + + # http://www.w3.org/TR/PNG/#11pHYs + if self.x_pixels_per_unit is not None and self.y_pixels_per_unit is not None: + tup = ( + self.x_pixels_per_unit, + self.y_pixels_per_unit, + int(self.unit_is_meter), + ) + write_chunk(outfile, b"pHYs", struct.pack("!LLB", *tup)) + + def write_array(self, outfile, pixels): + """ + Write an array that holds all the image values + as a PNG file on the output file. + See also :meth:`write` method. + """ + + if self.interlace: + if not isarray(pixels): + # Coerce to array type + fmt = "BH"[self.bitdepth > 8] + pixels = array(fmt, pixels) + self.write_passes(outfile, self.array_scanlines_interlace(pixels)) + else: + self.write_passes(outfile, self.array_scanlines(pixels)) + + def array_scanlines(self, pixels): + """ + Generates rows (each a sequence of values) from + a single array of values. + """ + + # Values per row + vpr = self.width * self.planes + stop = 0 + for y in range(self.height): + start = stop + stop = start + vpr + yield pixels[start:stop] + + def array_scanlines_interlace(self, pixels): + """ + Generator for interlaced scanlines from an array. + `pixels` is the full source image as a single array of values. + The generator yields each scanline of the reduced passes in turn, + each scanline being a sequence of values. + """ + + # http://www.w3.org/TR/PNG/#8InterlaceMethods + # Array type. + fmt = "BH"[self.bitdepth > 8] + # Value per row + vpr = self.width * self.planes + + # Each iteration generates a scanline starting at (x, y) + # and consisting of every xstep pixels. + for lines in adam7_generate(self.width, self.height): + for x, y, xstep in lines: + # Pixels per row (of reduced image) + ppr = int(math.ceil((self.width - x) / float(xstep))) + # Values per row (of reduced image) + reduced_row_len = ppr * self.planes + if xstep == 1: + # Easy case: line is a simple slice. + offset = y * vpr + yield pixels[offset : offset + vpr] + continue + # We have to step by xstep, + # which we can do one plane at a time + # using the step in Python slices. + row = array(fmt) + # There's no easier way to set the length of an array + row.extend(pixels[0:reduced_row_len]) + offset = y * vpr + x * self.planes + end_offset = (y + 1) * vpr + skip = self.planes * xstep + for i in range(self.planes): + row[i :: self.planes] = pixels[offset + i : end_offset : skip] + yield row + + +def write_chunk(outfile, tag, data=b""): + """ + Write a PNG chunk to the output file, including length and + checksum. + """ + + data = bytes(data) + # http://www.w3.org/TR/PNG/#5Chunk-layout + outfile.write(struct.pack("!I", len(data))) + outfile.write(tag) + outfile.write(data) + checksum = zlib.crc32(tag) + checksum = zlib.crc32(data, checksum) + checksum &= 2**32 - 1 + outfile.write(struct.pack("!I", checksum)) + + +def write_chunks(out, chunks): + """Create a PNG file by writing out the chunks.""" + + out.write(signature) + for chunk in chunks: + write_chunk(out, *chunk) + + +def rescale_rows(rows, rescale): + """ + Take each row in rows (an iterator) and yield + a fresh row with the pixels scaled according to + the rescale parameters in the list `rescale`. + Each element of `rescale` is a tuple of + (source_bitdepth, target_bitdepth), + with one element per channel. + """ + + # One factor for each channel + fs = [float(2 ** s[1] - 1) / float(2 ** s[0] - 1) for s in rescale] + + # Assume all target_bitdepths are the same + target_bitdepths = set(s[1] for s in rescale) + assert len(target_bitdepths) == 1 + (target_bitdepth,) = target_bitdepths + typecode = "BH"[target_bitdepth > 8] + + # Number of channels + n_chans = len(rescale) + + for row in rows: + rescaled_row = array(typecode, iter(row)) + for i in range(n_chans): + channel = array(typecode, (int(round(fs[i] * x)) for x in row[i::n_chans])) + rescaled_row[i::n_chans] = channel + yield rescaled_row + + +def pack_rows(rows, bitdepth): + """Yield packed rows that are a byte array. + Each byte is packed with the values from several pixels. + """ + + assert bitdepth < 8 + assert 8 % bitdepth == 0 + + # samples per byte + spb = int(8 / bitdepth) + + def make_byte(block): + """Take a block of (2, 4, or 8) values, + and pack them into a single byte. + """ + + res = 0 + for v in block: + res = (res << bitdepth) + v + return res + + for row in rows: + a = bytearray(row) + # Adding padding bytes so we can group into a whole + # number of spb-tuples. + n = float(len(a)) + extra = math.ceil(n / spb) * spb - n + a.extend([0] * int(extra)) + # Pack into bytes. + # Each block is the samples for one byte. + blocks = group(a, spb) + yield bytearray(make_byte(block) for block in blocks) + + +def unpack_rows(rows): + """Unpack each row from being 16-bits per value, + to being a sequence of bytes. + """ + for row in rows: + fmt = "!%dH" % len(row) + yield bytearray(struct.pack(fmt, *row)) + + +def make_palette_chunks(palette): + """ + Create the byte sequences for a ``PLTE`` and + if necessary a ``tRNS`` chunk. + Returned as a pair (*p*, *t*). + *t* will be ``None`` if no ``tRNS`` chunk is necessary. + """ + + p = bytearray() + t = bytearray() + + for x in palette: + p.extend(x[0:3]) + if len(x) > 3: + t.append(x[3]) + if t: + return p, t + return p, None + + +def check_bitdepth_rescale(palette, bitdepth, transparent, alpha, greyscale): + """ + Returns (bitdepth, rescale) pair. + """ + + if palette: + if len(bitdepth) != 1: + raise ProtocolError("with palette, only a single bitdepth may be used") + (bitdepth,) = bitdepth + if bitdepth not in (1, 2, 4, 8): + raise ProtocolError("with palette, bitdepth must be 1, 2, 4, or 8") + if transparent is not None: + raise ProtocolError("transparent and palette not compatible") + if alpha: + raise ProtocolError("alpha and palette not compatible") + if greyscale: + raise ProtocolError("greyscale and palette not compatible") + return bitdepth, None + + # No palette, check for sBIT chunk generation. + + if greyscale and not alpha: + # Single channel, L. + (bitdepth,) = bitdepth + if bitdepth in (1, 2, 4, 8, 16): + return bitdepth, None + if bitdepth > 8: + targetbitdepth = 16 + elif bitdepth == 3: + targetbitdepth = 4 + else: + assert bitdepth in (5, 6, 7) + targetbitdepth = 8 + return targetbitdepth, [(bitdepth, targetbitdepth)] + + assert alpha or not greyscale + + depth_set = tuple(set(bitdepth)) + if depth_set in [(8,), (16,)]: + # No sBIT required. + (bitdepth,) = depth_set + return bitdepth, None + + targetbitdepth = (8, 16)[max(bitdepth) > 8] + return targetbitdepth, [(b, targetbitdepth) for b in bitdepth] + + +# Regex for decoding mode string +RegexModeDecode = re.compile("(LA?|RGBA?);?([0-9]*)", flags=re.IGNORECASE) + + +def from_array(a, mode=None, info={}): + """ + Create a PNG :class:`Image` object from a 2-dimensional array. + One application of this function is easy PIL-style saving: + ``png.from_array(pixels, 'L').save('foo.png')``. + + Unless they are specified using the *info* parameter, + the PNG's height and width are taken from the array size. + The first axis is the height; the second axis is the + ravelled width and channel index. + The array is treated is a sequence of rows, + each row being a sequence of values (``width*channels`` in number). + So an RGB image that is 16 pixels high and 8 wide will + occupy a 2-dimensional array that is 16x24 + (each row will be 8*3 = 24 sample values). + + *mode* is a string that specifies the image colour format in a + PIL-style mode. It can be: + + ``'L'`` + greyscale (1 channel) + ``'LA'`` + greyscale with alpha (2 channel) + ``'RGB'`` + colour image (3 channel) + ``'RGBA'`` + colour image with alpha (4 channel) + + The mode string can also specify the bit depth + (overriding how this function normally derives the bit depth, + see below). + Appending ``';16'`` to the mode will cause the PNG to be + 16 bits per channel; + any decimal from 1 to 16 can be used to specify the bit depth. + + When a 2-dimensional array is used *mode* determines how many + channels the image has, and so allows the width to be derived from + the second array dimension. + + The array is expected to be a ``numpy`` array, + but it can be any suitable Python sequence. + For example, a list of lists can be used: + ``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``. + The exact rules are: ``len(a)`` gives the first dimension, height; + ``len(a[0])`` gives the second dimension. + It's slightly more complicated than that because + an iterator of rows can be used, and it all still works. + Using an iterator allows data to be streamed efficiently. + + The bit depth of the PNG is normally taken from + the array element's datatype + (but if *mode* specifies a bitdepth then that is used instead). + The array element's datatype is determined in a way which + is supposed to work both for ``numpy`` arrays and for Python + ``array.array`` objects. + A 1 byte datatype will give a bit depth of 8, + a 2 byte datatype will give a bit depth of 16. + If the datatype does not have an implicit size, + like the above example where it is a plain Python list of lists, + then a default of 8 is used. + + The *info* parameter is a dictionary that can + be used to specify metadata (in the same style as + the arguments to the :class:`png.Writer` class). + For this function the keys that are useful are: + + height + overrides the height derived from the array dimensions and + allows *a* to be an iterable. + width + overrides the width derived from the array dimensions. + bitdepth + overrides the bit depth derived from the element datatype + (but must match *mode* if that also specifies a bit depth). + + Generally anything specified in the *info* dictionary will + override any implicit choices that this function would otherwise make, + but must match any explicit ones. + For example, if the *info* dictionary has a ``greyscale`` key then + this must be true when mode is ``'L'`` or ``'LA'`` and + false when mode is ``'RGB'`` or ``'RGBA'``. + """ + + # We abuse the *info* parameter by modifying it. Take a copy here. + # (Also typechecks *info* to some extent). + info = dict(info) + + # Syntax check mode string. + match = RegexModeDecode.match(mode) + if not match: + raise Error("mode string should be 'RGB' or 'L;16' or similar.") + + mode, bitdepth = match.groups() + if bitdepth: + bitdepth = int(bitdepth) + + # Colour format. + if "greyscale" in info: + if bool(info["greyscale"]) != ("L" in mode): + raise ProtocolError("info['greyscale'] should match mode.") + info["greyscale"] = "L" in mode + + alpha = "A" in mode + if "alpha" in info: + if bool(info["alpha"]) != alpha: + raise ProtocolError("info['alpha'] should match mode.") + info["alpha"] = alpha + + # Get bitdepth from *mode* if possible. + if bitdepth: + if info.get("bitdepth") and bitdepth != info["bitdepth"]: + raise ProtocolError( + "bitdepth (%d) should match bitdepth of info (%d)." + % (bitdepth, info["bitdepth"]) + ) + info["bitdepth"] = bitdepth + + # Fill in and/or check entries in *info*. + # Dimensions. + width, height = check_sizes(info.get("size"), info.get("width"), info.get("height")) + if width: + info["width"] = width + if height: + info["height"] = height + + if "height" not in info: + try: + info["height"] = len(a) + except TypeError: + raise ProtocolError("len(a) does not work, supply info['height'] instead.") + + planes = len(mode) + if "planes" in info: + if info["planes"] != planes: + raise Error("info['planes'] should match mode.") + + # In order to work out whether we the array is 2D or 3D we need its + # first row, which requires that we take a copy of its iterator. + # We may also need the first row to derive width and bitdepth. + a, t = itertools.tee(a) + row = next(t) + del t + + testelement = row + if "width" not in info: + width = len(row) // planes + info["width"] = width + + if "bitdepth" not in info: + try: + dtype = testelement.dtype + # goto the "else:" clause. Sorry. + except AttributeError: + try: + # Try a Python array.array. + bitdepth = 8 * testelement.itemsize + except AttributeError: + # We can't determine it from the array element's datatype, + # use a default of 8. + bitdepth = 8 + else: + # If we got here without exception, + # we now assume that the array is a numpy array. + if dtype.kind == "b": + bitdepth = 1 + else: + bitdepth = 8 * dtype.itemsize + info["bitdepth"] = bitdepth + + for thing in ["width", "height", "bitdepth", "greyscale", "alpha"]: + assert thing in info + + return Image(a, info) + + +# So that refugee's from PIL feel more at home. Not documented. +fromarray = from_array + + +class Image: + """A PNG image. You can create an :class:`Image` object from + an array of pixels by calling :meth:`png.from_array`. It can be + saved to disk with the :meth:`save` method. + """ + + def __init__(self, rows, info): + """ + .. note :: + + The constructor is not public. Please do not call it. + """ + + self.rows = rows + self.info = info + + def save(self, file): + """Save the image to the named *file*. + + See `.write()` if you already have an open file object. + + In general, you can only call this method once; + after it has been called the first time the PNG image is written, + the source data will have been streamed, and + cannot be streamed again. + """ + + w = Writer(**self.info) + + with open(file, "wb") as fd: + w.write(fd, self.rows) + + def write(self, file): + """Write the image to the open file object. + + See `.save()` if you have a filename. + + In general, you can only call this method once; + after it has been called the first time the PNG image is written, + the source data will have been streamed, and + cannot be streamed again. + """ + + w = Writer(**self.info) + w.write(file, self.rows) + + +class Reader: + """ + Pure Python PNG decoder in pure Python. + """ + + def __init__(self, _guess=None, filename=None, file=None, bytes=None): + """ + The constructor expects exactly one keyword argument. + If you supply a positional argument instead, + it will guess the input type. + Choose from the following keyword arguments: + + filename + Name of input file (a PNG file). + file + A file-like object (object with a read() method). + bytes + ``bytes`` or ``bytearray`` with PNG data. + + """ + keywords_supplied = ( + (_guess is not None) + + (filename is not None) + + (file is not None) + + (bytes is not None) + ) + if keywords_supplied != 1: + raise TypeError("Reader() takes exactly 1 argument") + + # Will be the first 8 bytes, later on. See validate_signature. + self.signature = None + self.transparent = None + # A pair of (len,type) if a chunk has been read but its data and + # checksum have not (in other words the file position is just + # past the 4 bytes that specify the chunk type). + # See preamble method for how this is used. + self.atchunk = None + + if _guess is not None: + if isarray(_guess): + bytes = _guess + elif isinstance(_guess, str): + filename = _guess + elif hasattr(_guess, "read"): + file = _guess + + if bytes is not None: + self.file = io.BytesIO(bytes) + elif filename is not None: + self.file = open(filename, "rb") + elif file is not None: + self.file = file + else: + raise ProtocolError("expecting filename, file or bytes array") + + def chunk(self, lenient=False): + """ + Read the next PNG chunk from the input file; + returns a (*type*, *data*) tuple. + *type* is the chunk's type as a byte string + (all PNG chunk types are 4 bytes long). + *data* is the chunk's data content, as a byte string. + + If the optional `lenient` argument evaluates to `True`, + checksum failures will raise warnings rather than exceptions. + """ + + self.validate_signature() + + # http://www.w3.org/TR/PNG/#5Chunk-layout + if not self.atchunk: + self.atchunk = self._chunk_len_type() + if not self.atchunk: + raise ChunkError("No more chunks.") + length, type = self.atchunk + self.atchunk = None + + data = self.file.read(length) + if len(data) != length: + raise ChunkError( + "Chunk %s too short for required %i octets." % (type, length) + ) + checksum = self.file.read(4) + if len(checksum) != 4: + raise ChunkError("Chunk %s too short for checksum." % type) + verify = zlib.crc32(type) + verify = zlib.crc32(data, verify) + verify = struct.pack("!I", verify) + if checksum != verify: + (a,) = struct.unpack("!I", checksum) + (b,) = struct.unpack("!I", verify) + message = "Checksum error in %s chunk: 0x%08X != 0x%08X." % ( + type.decode("ascii"), + a, + b, + ) + if lenient: + warnings.warn(message, RuntimeWarning) + else: + raise ChunkError(message) + return type, data + + def chunks(self): + """Return an iterator that will yield each chunk as a + (*chunktype*, *content*) pair. + """ + + while True: + t, v = self.chunk() + yield t, v + if t == b"IEND": + break + + def undo_filter(self, filter_type, scanline, previous): + """ + Undo the filter for a scanline. + `scanline` is a sequence of bytes that + does not include the initial filter type byte. + `previous` is decoded previous scanline + (for straightlaced images this is the previous pixel row, + but for interlaced images, it is + the previous scanline in the reduced image, + which in general is not the previous pixel row in the final image). + When there is no previous scanline + (the first row of a straightlaced image, + or the first row in one of the passes in an interlaced image), + then this argument should be ``None``. + + The scanline will have the effects of filtering removed; + the result will be returned as a fresh sequence of bytes. + """ + + # :todo: Would it be better to update scanline in place? + result = scanline + + if filter_type == 0: + return result + + if filter_type not in (1, 2, 3, 4): + raise FormatError( + "Invalid PNG Filter Type. " + "See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters ." + ) + + # Filter unit. The stride from one pixel to the corresponding + # byte from the previous pixel. Normally this is the pixel + # size in bytes, but when this is smaller than 1, the previous + # byte is used instead. + fu = max(1, self.psize) + + # For the first line of a pass, synthesize a dummy previous + # line. An alternative approach would be to observe that on the + # first line 'up' is the same as 'null', 'paeth' is the same + # as 'sub', with only 'average' requiring any special case. + if not previous: + previous = bytearray([0] * len(scanline)) + + # Call appropriate filter algorithm. Note that 0 has already + # been dealt with. + fn = ( + None, + undo_filter_sub, + undo_filter_up, + undo_filter_average, + undo_filter_paeth, + )[filter_type] + fn(fu, scanline, previous, result) + return result + + def _deinterlace(self, raw): + """ + Read raw pixel data, undo filters, deinterlace, and flatten. + Return a single array of values. + """ + + # Values per row (of the target image) + vpr = self.width * self.planes + + # Values per image + vpi = vpr * self.height + # Interleaving writes to the output array randomly + # (well, not quite), so the entire output array must be in memory. + # Make a result array, and make it big enough. + if self.bitdepth > 8: + a = array("H", [0] * vpi) + else: + a = bytearray([0] * vpi) + source_offset = 0 + + for lines in adam7_generate(self.width, self.height): + # The previous (reconstructed) scanline. + # `None` at the beginning of a pass + # to indicate that there is no previous line. + recon = None + for x, y, xstep in lines: + # Pixels per row (reduced pass image) + ppr = int(math.ceil((self.width - x) / float(xstep))) + # Row size in bytes for this pass. + row_size = int(math.ceil(self.psize * ppr)) + + filter_type = raw[source_offset] + source_offset += 1 + scanline = raw[source_offset : source_offset + row_size] + source_offset += row_size + recon = self.undo_filter(filter_type, scanline, recon) + # Convert so that there is one element per pixel value + flat = self._bytes_to_values(recon, width=ppr) + if xstep == 1: + assert x == 0 + offset = y * vpr + a[offset : offset + vpr] = flat + else: + offset = y * vpr + x * self.planes + end_offset = (y + 1) * vpr + skip = self.planes * xstep + for i in range(self.planes): + a[offset + i : end_offset : skip] = flat[i :: self.planes] + + return a + + def _iter_bytes_to_values(self, byte_rows): + """ + Iterator that yields each scanline; + each scanline being a sequence of values. + `byte_rows` should be an iterator that yields + the bytes of each row in turn. + """ + + for row in byte_rows: + yield self._bytes_to_values(row) + + def _bytes_to_values(self, bs, width=None): + """Convert a packed row of bytes into a row of values. + Result will be a freshly allocated object, + not shared with the argument. + """ + + if self.bitdepth == 8: + return bytearray(bs) + if self.bitdepth == 16: + return array("H", struct.unpack("!%dH" % (len(bs) // 2), bs)) + + assert self.bitdepth < 8 + if width is None: + width = self.width + # Samples per byte + spb = 8 // self.bitdepth + out = bytearray() + mask = 2**self.bitdepth - 1 + shifts = [self.bitdepth * i for i in reversed(list(range(spb)))] + for o in bs: + out.extend([mask & (o >> i) for i in shifts]) + return out[:width] + + def _iter_straight_packed(self, byte_blocks): + """Iterator that undoes the effect of filtering; + yields each row as a sequence of packed bytes. + Assumes input is straightlaced. + `byte_blocks` should be an iterable that yields the raw bytes + in blocks of arbitrary size. + """ + + # length of row, in bytes + rb = self.row_bytes + a = bytearray() + # The previous (reconstructed) scanline. + # None indicates first line of image. + recon = None + for some_bytes in byte_blocks: + a.extend(some_bytes) + while len(a) >= rb + 1: + filter_type = a[0] + scanline = a[1 : rb + 1] + del a[: rb + 1] + recon = self.undo_filter(filter_type, scanline, recon) + yield recon + if len(a) != 0: + # :file:format We get here with a file format error: + # when the available bytes (after decompressing) do not + # pack into exact rows. + raise FormatError("Wrong size for decompressed IDAT chunk.") + assert len(a) == 0 + + def validate_signature(self): + """ + If signature (header) has not been read then read and + validate it; otherwise do nothing. + """ + + if self.signature: + return + self.signature = self.file.read(8) + if self.signature != signature: + raise FormatError("PNG file has invalid signature.") + + def preamble(self, lenient=False): + """ + Extract the image metadata by reading + the initial part of the PNG file up to + the start of the ``IDAT`` chunk. + All the chunks that precede the ``IDAT`` chunk are + read and either processed for metadata or discarded. + + If the optional `lenient` argument evaluates to `True`, + checksum failures will raise warnings rather than exceptions. + """ + + self.validate_signature() + + while True: + if not self.atchunk: + self.atchunk = self._chunk_len_type() + if self.atchunk is None: + raise FormatError("This PNG file has no IDAT chunks.") + if self.atchunk[1] == b"IDAT": + return + self.process_chunk(lenient=lenient) + + def _chunk_len_type(self): + """ + Reads just enough of the input to + determine the next chunk's length and type; + return a (*length*, *type*) pair where *type* is a byte sequence. + If there are no more chunks, ``None`` is returned. + """ + + x = self.file.read(8) + if not x: + return None + if len(x) != 8: + raise FormatError("End of file whilst reading chunk length and type.") + length, type = struct.unpack("!I4s", x) + if length > 2**31 - 1: + raise FormatError("Chunk %s is too large: %d." % (type, length)) + # Check that all bytes are in valid ASCII range. + # https://www.w3.org/TR/2003/REC-PNG-20031110/#5Chunk-layout + type_bytes = set(bytearray(type)) + if not (type_bytes <= set(range(65, 91)) | set(range(97, 123))): + raise FormatError("Chunk %r has invalid Chunk Type." % list(type)) + return length, type + + def process_chunk(self, lenient=False): + """ + Process the next chunk and its data. + This only processes the following chunk types: + ``IHDR``, ``PLTE``, ``bKGD``, ``tRNS``, ``gAMA``, ``sBIT``, ``pHYs``. + All other chunk types are ignored. + + If the optional `lenient` argument evaluates to `True`, + checksum failures will raise warnings rather than exceptions. + """ + + type, data = self.chunk(lenient=lenient) + method = "_process_" + type.decode("ascii") + m = getattr(self, method, None) + if m: + m(data) + + def _process_IHDR(self, data): + # http://www.w3.org/TR/PNG/#11IHDR + if len(data) != 13: + raise FormatError("IHDR chunk has incorrect length.") + ( + self.width, + self.height, + self.bitdepth, + self.color_type, + self.compression, + self.filter, + self.interlace, + ) = struct.unpack("!2I5B", data) + + check_bitdepth_colortype(self.bitdepth, self.color_type) + + if self.compression != 0: + raise FormatError("Unknown compression method %d" % self.compression) + if self.filter != 0: + raise FormatError( + "Unknown filter method %d," + " see http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters ." + % self.filter + ) + if self.interlace not in (0, 1): + raise FormatError( + "Unknown interlace method %d, see " + "http://www.w3.org/TR/2003/REC-PNG-20031110/#8InterlaceMethods" + " ." % self.interlace + ) + + # Derived values + # http://www.w3.org/TR/PNG/#6Colour-values + colormap = bool(self.color_type & 1) + greyscale = not (self.color_type & 2) + alpha = bool(self.color_type & 4) + color_planes = (3, 1)[greyscale or colormap] + planes = color_planes + alpha + + self.colormap = colormap + self.greyscale = greyscale + self.alpha = alpha + self.color_planes = color_planes + self.planes = planes + self.psize = float(self.bitdepth) / float(8) * planes + if int(self.psize) == self.psize: + self.psize = int(self.psize) + self.row_bytes = int(math.ceil(self.width * self.psize)) + # Stores PLTE chunk if present, and is used to check + # chunk ordering constraints. + self.plte = None + # Stores tRNS chunk if present, and is used to check chunk + # ordering constraints. + self.trns = None + # Stores sBIT chunk if present. + self.sbit = None + + def _process_PLTE(self, data): + # http://www.w3.org/TR/PNG/#11PLTE + if self.plte: + warnings.warn("Multiple PLTE chunks present.") + self.plte = data + if len(data) % 3 != 0: + raise FormatError("PLTE chunk's length should be a multiple of 3.") + if len(data) > (2**self.bitdepth) * 3: + raise FormatError("PLTE chunk is too long.") + if len(data) == 0: + raise FormatError("Empty PLTE is not allowed.") + + def _process_bKGD(self, data): + try: + if self.colormap: + if not self.plte: + warnings.warn("PLTE chunk is required before bKGD chunk.") + self.background = struct.unpack("B", data) + else: + self.background = struct.unpack("!%dH" % self.color_planes, data) + except struct.error: + raise FormatError("bKGD chunk has incorrect length.") + + def _process_tRNS(self, data): + # http://www.w3.org/TR/PNG/#11tRNS + self.trns = data + if self.colormap: + if not self.plte: + warnings.warn("PLTE chunk is required before tRNS chunk.") + else: + if len(data) > len(self.plte) / 3: + # Was warning, but promoted to Error as it + # would otherwise cause pain later on. + raise FormatError("tRNS chunk is too long.") + else: + if self.alpha: + raise FormatError( + "tRNS chunk is not valid with colour type %d." % self.color_type + ) + try: + self.transparent = struct.unpack("!%dH" % self.color_planes, data) + except struct.error: + raise FormatError("tRNS chunk has incorrect length.") + + def _process_gAMA(self, data): + try: + self.gamma = struct.unpack("!L", data)[0] / 100000.0 + except struct.error: + raise FormatError("gAMA chunk has incorrect length.") + + def _process_sBIT(self, data): + self.sbit = data + if ( + self.colormap + and len(data) != 3 + or not self.colormap + and len(data) != self.planes + ): + raise FormatError("sBIT chunk has incorrect length.") + + def _process_pHYs(self, data): + # http://www.w3.org/TR/PNG/#11pHYs + self.phys = data + fmt = "!LLB" + if len(data) != struct.calcsize(fmt): + raise FormatError("pHYs chunk has incorrect length.") + self.x_pixels_per_unit, self.y_pixels_per_unit, unit = struct.unpack(fmt, data) + self.unit_is_meter = bool(unit) + + def read(self, lenient=False): + """ + Read the PNG file and decode it. + Returns (`width`, `height`, `rows`, `info`). + + May use excessive memory. + + `rows` is a sequence of rows; + each row is a sequence of values. + + If the optional `lenient` argument evaluates to True, + checksum failures will raise warnings rather than exceptions. + """ + + def iteridat(): + """Iterator that yields all the ``IDAT`` chunks as strings.""" + while True: + type, data = self.chunk(lenient=lenient) + if type == b"IEND": + # http://www.w3.org/TR/PNG/#11IEND + break + if type != b"IDAT": + continue + # type == b'IDAT' + # http://www.w3.org/TR/PNG/#11IDAT + if self.colormap and not self.plte: + warnings.warn("PLTE chunk is required before IDAT chunk") + yield data + + self.preamble(lenient=lenient) + raw = decompress(iteridat()) + + if self.interlace: + + def rows_from_interlace(): + """Yield each row from an interlaced PNG.""" + # It's important that this iterator doesn't read + # IDAT chunks until it yields the first row. + bs = bytearray(itertools.chain(*raw)) + arraycode = "BH"[self.bitdepth > 8] + # Like :meth:`group` but + # producing an array.array object for each row. + values = self._deinterlace(bs) + vpr = self.width * self.planes + for i in range(0, len(values), vpr): + row = array(arraycode, values[i : i + vpr]) + yield row + + rows = rows_from_interlace() + else: + rows = self._iter_bytes_to_values(self._iter_straight_packed(raw)) + info = dict() + for attr in "greyscale alpha planes bitdepth interlace".split(): + info[attr] = getattr(self, attr) + info["size"] = (self.width, self.height) + for attr in "gamma transparent background".split(): + a = getattr(self, attr, None) + if a is not None: + info[attr] = a + if getattr(self, "x_pixels_per_unit", None): + info["physical"] = Resolution( + self.x_pixels_per_unit, self.y_pixels_per_unit, self.unit_is_meter + ) + if self.plte: + info["palette"] = self.palette() + return self.width, self.height, rows, info + + def read_flat(self): + """ + Read a PNG file and decode it into a single array of values. + Returns (*width*, *height*, *values*, *info*). + + May use excessive memory. + + `values` is a single array. + + The :meth:`read` method is more stream-friendly than this, + because it returns a sequence of rows. + """ + + x, y, pixel, info = self.read() + arraycode = "BH"[info["bitdepth"] > 8] + pixel = array(arraycode, itertools.chain(*pixel)) + return x, y, pixel, info + + def palette(self, alpha="natural"): + """ + Returns a palette that is a sequence of 3-tuples or 4-tuples, + synthesizing it from the ``PLTE`` and ``tRNS`` chunks. + These chunks should have already been processed (for example, + by calling the :meth:`preamble` method). + All the tuples are the same size: + 3-tuples if there is no ``tRNS`` chunk, + 4-tuples when there is a ``tRNS`` chunk. + + Assumes that the image is colour type + 3 and therefore a ``PLTE`` chunk is required. + + If the `alpha` argument is ``'force'`` then an alpha channel is + always added, forcing the result to be a sequence of 4-tuples. + """ + + if not self.plte: + raise FormatError("Required PLTE chunk is missing in colour type 3 image.") + plte = group(array("B", self.plte), 3) + if self.trns or alpha == "force": + trns = array("B", self.trns or []) + trns.extend([255] * (len(plte) - len(trns))) + plte = list(map(operator.add, plte, group(trns, 1))) + return plte + + def asDirect(self): + """ + Returns the image data as a direct representation of + an ``x * y * planes`` array. + This removes the need for callers to deal with + palettes and transparency themselves. + Images with a palette (colour type 3) are converted to RGB or RGBA; + images with transparency (a ``tRNS`` chunk) are converted to + LA or RGBA as appropriate. + When returned in this format the pixel values represent + the colour value directly without needing to refer + to palettes or transparency information. + + Like the :meth:`read` method this method returns a 4-tuple: + + (*width*, *height*, *rows*, *info*) + + This method normally returns pixel values with + the bit depth they have in the source image, but + when the source PNG has an ``sBIT`` chunk it is inspected and + can reduce the bit depth of the result pixels; + pixel values will be reduced according to the bit depth + specified in the ``sBIT`` chunk. + PNG nerds should note a single result bit depth is + used for all channels: + the maximum of the ones specified in the ``sBIT`` chunk. + An RGB565 image will be rescaled to 6-bit RGB666. + + The *info* dictionary that is returned reflects + the `direct` format and not the original source image. + For example, an RGB source image with a ``tRNS`` chunk + to represent a transparent colour, + will start with ``planes=3`` and ``alpha=False`` for the + source image, + but the *info* dictionary returned by this method + will have ``planes=4`` and ``alpha=True`` because + an alpha channel is synthesized and added. + + *rows* is a sequence of rows; + each row being a sequence of values + (like the :meth:`read` method). + + All the other aspects of the image data are not changed. + """ + + self.preamble() + + # Simple case, no conversion necessary. + if not self.colormap and not self.trns and not self.sbit: + return self.read() + + x, y, pixels, info = self.read() + + if self.colormap: + info["colormap"] = False + info["alpha"] = bool(self.trns) + info["bitdepth"] = 8 + info["planes"] = 3 + bool(self.trns) + plte = self.palette() + + def iterpal(pixels): + for row in pixels: + row = [plte[x] for x in row] + yield array("B", itertools.chain(*row)) + + pixels = iterpal(pixels) + elif self.trns: + # It would be nice if there was some reasonable way + # of doing this without generating a whole load of + # intermediate tuples. But tuples does seem like the + # easiest way, with no other way clearly much simpler or + # much faster. (Actually, the L to LA conversion could + # perhaps go faster (all those 1-tuples!), but I still + # wonder whether the code proliferation is worth it) + it = self.transparent + maxval = 2 ** info["bitdepth"] - 1 + planes = info["planes"] + info["alpha"] = True + info["planes"] += 1 + typecode = "BH"[info["bitdepth"] > 8] + + def itertrns(pixels): + for row in pixels: + # For each row we group it into pixels, then form a + # characterisation vector that says whether each + # pixel is opaque or not. Then we convert + # True/False to 0/maxval (by multiplication), + # and add it as the extra channel. + row = group(row, planes) + opa = map(it.__ne__, row) + opa = map(maxval.__mul__, opa) + opa = list(zip(opa)) # convert to 1-tuples + yield array(typecode, itertools.chain(*map(operator.add, row, opa))) + + pixels = itertrns(pixels) + targetbitdepth = None + if self.sbit: + sbit = struct.unpack("%dB" % len(self.sbit), self.sbit) + targetbitdepth = max(sbit) + if targetbitdepth > info["bitdepth"]: + raise Error("sBIT chunk %r exceeds bitdepth %d" % (sbit, self.bitdepth)) + if min(sbit) <= 0: + raise Error("sBIT chunk %r has a 0-entry" % sbit) + if targetbitdepth: + shift = info["bitdepth"] - targetbitdepth + info["bitdepth"] = targetbitdepth + + def itershift(pixels): + for row in pixels: + yield [p >> shift for p in row] + + pixels = itershift(pixels) + return x, y, pixels, info + + def _as_rescale(self, get, targetbitdepth): + """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" + + width, height, pixels, info = get() + maxval = 2 ** info["bitdepth"] - 1 + targetmaxval = 2**targetbitdepth - 1 + factor = float(targetmaxval) / float(maxval) + info["bitdepth"] = targetbitdepth + + def iterscale(): + for row in pixels: + yield [int(round(x * factor)) for x in row] + + if maxval == targetmaxval: + return width, height, pixels, info + else: + return width, height, iterscale(), info + + def asRGB8(self): + """ + Return the image data as an RGB pixels with 8-bits per sample. + This is like the :meth:`asRGB` method except that + this method additionally rescales the values so that + they are all between 0 and 255 (8-bit). + In the case where the source image has a bit depth < 8 + the transformation preserves all the information; + where the source image has bit depth > 8, then + rescaling to 8-bit values loses precision. + No dithering is performed. + Like :meth:`asRGB`, + an alpha channel in the source image will raise an exception. + + This function returns a 4-tuple: + (*width*, *height*, *rows*, *info*). + *width*, *height*, *info* are as per the :meth:`read` method. + + *rows* is the pixel data as a sequence of rows. + """ + + return self._as_rescale(self.asRGB, 8) + + def asRGBA8(self): + """ + Return the image data as RGBA pixels with 8-bits per sample. + This method is similar to :meth:`asRGB8` and :meth:`asRGBA`: + The result pixels have an alpha channel, *and* + values are rescaled to the range 0 to 255. + The alpha channel is synthesized if necessary + (with a small speed penalty). + """ + + return self._as_rescale(self.asRGBA, 8) + + def asRGB(self): + """ + Return image as RGB pixels. + RGB colour images are passed through unchanged; + greyscales are expanded into RGB triplets + (there is a small speed overhead for doing this). + + An alpha channel in the source image will raise an exception. + + The return values are as for the :meth:`read` method except that + the *info* reflect the returned pixels, not the source image. + In particular, + for this method ``info['greyscale']`` will be ``False``. + """ + + width, height, pixels, info = self.asDirect() + if info["alpha"]: + raise Error("will not convert image with alpha channel to RGB") + if not info["greyscale"]: + return width, height, pixels, info + info["greyscale"] = False + info["planes"] = 3 + + if info["bitdepth"] > 8: + + def newarray(): + return array("H", [0]) + + else: + + def newarray(): + return bytearray([0]) + + def iterrgb(): + for row in pixels: + a = newarray() * 3 * width + for i in range(3): + a[i::3] = row + yield a + + return width, height, iterrgb(), info + + def asRGBA(self): + """ + Return image as RGBA pixels. + Greyscales are expanded into RGB triplets; + an alpha channel is synthesized if necessary. + The return values are as for the :meth:`read` method except that + the *info* reflect the returned pixels, not the source image. + In particular, for this method + ``info['greyscale']`` will be ``False``, and + ``info['alpha']`` will be ``True``. + """ + + width, height, pixels, info = self.asDirect() + if info["alpha"] and not info["greyscale"]: + return width, height, pixels, info + typecode = "BH"[info["bitdepth"] > 8] + maxval = 2 ** info["bitdepth"] - 1 + maxbuffer = struct.pack("=" + typecode, maxval) * 4 * width + + if info["bitdepth"] > 8: + + def newarray(): + return array("H", maxbuffer) + + else: + + def newarray(): + return bytearray(maxbuffer) + + if info["alpha"] and info["greyscale"]: + # LA to RGBA + def convert(): + for row in pixels: + # Create a fresh target row, then copy L channel + # into first three target channels, and A channel + # into fourth channel. + a = newarray() + convert_la_to_rgba(row, a) + yield a + + elif info["greyscale"]: + # L to RGBA + def convert(): + for row in pixels: + a = newarray() + convert_l_to_rgba(row, a) + yield a + + else: + assert not info["alpha"] and not info["greyscale"] + # RGB to RGBA + + def convert(): + for row in pixels: + a = newarray() + convert_rgb_to_rgba(row, a) + yield a + + info["alpha"] = True + info["greyscale"] = False + info["planes"] = 4 + return width, height, convert(), info + + +def decompress(data_blocks): + """ + `data_blocks` should be an iterable that + yields the compressed data (from the ``IDAT`` chunks). + This yields decompressed byte strings. + """ + + # Currently, with no max_length parameter to decompress, + # this routine will do one yield per IDAT chunk: Not very + # incremental. + d = zlib.decompressobj() + # Each IDAT chunk is passed to the decompressor, then any + # remaining state is decompressed out. + for data in data_blocks: + # :todo: add a max_length argument here to limit output size. + yield bytearray(d.decompress(data)) + yield bytearray(d.flush()) + + +def check_bitdepth_colortype(bitdepth, colortype): + """ + Check that `bitdepth` and `colortype` are both valid, + and specified in a valid combination. + Returns (None) if valid, raise an Exception if not valid. + """ + + if bitdepth not in (1, 2, 4, 8, 16): + raise FormatError("invalid bit depth %d" % bitdepth) + if colortype not in (0, 2, 3, 4, 6): + raise FormatError("invalid colour type %d" % colortype) + # Check indexed (palettized) images have 8 or fewer bits + # per pixel; check only indexed or greyscale images have + # fewer than 8 bits per pixel. + if colortype & 1 and bitdepth > 8: + raise FormatError( + "Indexed images (colour type %d) cannot" + " have bitdepth > 8 (bit depth %d)." + " See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ." + % (bitdepth, colortype) + ) + if bitdepth < 8 and colortype not in (0, 3): + raise FormatError( + "Illegal combination of bit depth (%d)" + " and colour type (%d)." + " See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ." + % (bitdepth, colortype) + ) + + +def is_natural(x): + """A non-negative integer.""" + try: + is_integer = int(x) == x + except (TypeError, ValueError): + return False + return is_integer and x >= 0 + + +def undo_filter_sub(filter_unit, scanline, previous, result): + """Undo sub filter.""" + + ai = 0 + # Loops starts at index fu. Observe that the initial part + # of the result is already filled in correctly with + # scanline. + for i in range(filter_unit, len(result)): + x = scanline[i] + a = result[ai] + result[i] = (x + a) & 0xFF + ai += 1 + + +def undo_filter_up(filter_unit, scanline, previous, result): + """Undo up filter.""" + + for i in range(len(result)): + x = scanline[i] + b = previous[i] + result[i] = (x + b) & 0xFF + + +def undo_filter_average(filter_unit, scanline, previous, result): + """Undo up filter.""" + + ai = -filter_unit + for i in range(len(result)): + x = scanline[i] + if ai < 0: + a = 0 + else: + a = result[ai] + b = previous[i] + result[i] = (x + ((a + b) >> 1)) & 0xFF + ai += 1 + + +def undo_filter_paeth(filter_unit, scanline, previous, result): + """Undo Paeth filter.""" + + # Also used for ci. + ai = -filter_unit + for i in range(len(result)): + x = scanline[i] + if ai < 0: + a = c = 0 + else: + a = result[ai] + c = previous[ai] + b = previous[i] + p = a + b - c + pa = abs(p - a) + pb = abs(p - b) + pc = abs(p - c) + if pa <= pb and pa <= pc: + pr = a + elif pb <= pc: + pr = b + else: + pr = c + result[i] = (x + pr) & 0xFF + ai += 1 + + +def convert_la_to_rgba(row, result): + for i in range(3): + result[i::4] = row[0::2] + result[3::4] = row[1::2] + + +def convert_l_to_rgba(row, result): + """ + Convert a grayscale image to RGBA. + This method assumes the alpha channel in result is + already correctly initialized. + """ + for i in range(3): + result[i::4] = row + + +def convert_rgb_to_rgba(row, result): + """ + Convert an RGB image to RGBA. + This method assumes the alpha channel in result is + already correctly initialized. + """ + for i in range(3): + result[i::4] = row[i::3] + + +# Only reason to include this in this module is that +# several utilities need it, and it is small. +def binary_stdin(): + """ + A sys.stdin that returns bytes. + """ + + return sys.stdin.buffer + + +def binary_stdout(): + """ + A sys.stdout that accepts bytes. + """ + + stdout = sys.stdout.buffer + + # On Windows the C runtime file orientation needs changing. + if sys.platform == "win32": + import msvcrt + import os + + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + + return stdout + + +def cli_open(path): + if path == "-": + return binary_stdin() + return open(path, "rb") diff --git a/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/utils.py b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..07a2b9e0b938314627342632fc8f7412cda9c4b2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_plotly_utils/utils.py @@ -0,0 +1,557 @@ +import base64 +import decimal +import json as _json +import sys +import re +from functools import reduce + +from _plotly_utils.optional_imports import get_module +from _plotly_utils.basevalidators import ( + ImageUriValidator, + copy_to_readonly_numpy_array, + is_homogeneous_array, +) + + +int8min = -128 +int8max = 127 +int16min = -32768 +int16max = 32767 +int32min = -2147483648 +int32max = 2147483647 + +uint8max = 255 +uint16max = 65535 +uint32max = 4294967295 + +plotlyjsShortTypes = { + "int8": "i1", + "uint8": "u1", + "int16": "i2", + "uint16": "u2", + "int32": "i4", + "uint32": "u4", + "float32": "f4", + "float64": "f8", +} + + +def to_typed_array_spec(v): + """ + Convert numpy array to plotly.js typed array spec + If not possible return the original value + """ + v = copy_to_readonly_numpy_array(v) + + # Skip b64 encoding if numpy is not installed, + # or if v is not a numpy array, or if v is empty + np = get_module("numpy", should_load=False) + if not np or not isinstance(v, np.ndarray) or v.size == 0: + return v + + dtype = str(v.dtype) + + # convert default Big Ints until we could support them in plotly.js + if dtype == "int64": + max = v.max() + min = v.min() + if max <= int8max and min >= int8min: + v = v.astype("int8") + elif max <= int16max and min >= int16min: + v = v.astype("int16") + elif max <= int32max and min >= int32min: + v = v.astype("int32") + else: + return v + + elif dtype == "uint64": + max = v.max() + min = v.min() + if max <= uint8max and min >= 0: + v = v.astype("uint8") + elif max <= uint16max and min >= 0: + v = v.astype("uint16") + elif max <= uint32max and min >= 0: + v = v.astype("uint32") + else: + return v + + dtype = str(v.dtype) + + if dtype in plotlyjsShortTypes: + arrObj = { + "dtype": plotlyjsShortTypes[dtype], + "bdata": base64.b64encode(v).decode("ascii"), + } + + if v.ndim > 1: + arrObj["shape"] = str(v.shape)[1:-1] + + return arrObj + + return v + + +def is_skipped_key(key): + """ + Return whether the key is skipped for conversion to the typed array spec + """ + skipped_keys = ["geojson", "layer", "layers", "range"] + return any(skipped_key == key for skipped_key in skipped_keys) + + +def convert_to_base64(obj): + if isinstance(obj, dict): + for key, value in obj.items(): + if is_skipped_key(key): + continue + elif is_homogeneous_array(value): + obj[key] = to_typed_array_spec(value) + else: + convert_to_base64(value) + elif isinstance(obj, list) or isinstance(obj, tuple): + for value in obj: + convert_to_base64(value) + + +def cumsum(x): + """ + Custom cumsum to avoid a numpy import. + """ + + def _reducer(a, x): + if len(a) == 0: + return [x] + return a + [a[-1] + x] + + ret = reduce(_reducer, x, []) + return ret + + +class PlotlyJSONEncoder(_json.JSONEncoder): + """ + Meant to be passed as the `cls` kwarg to json.dumps(obj, cls=..) + + See PlotlyJSONEncoder.default for more implementation information. + + Additionally, this encoder overrides nan functionality so that 'Inf', + 'NaN' and '-Inf' encode to 'null'. Which is stricter JSON than the Python + version. + + """ + + def coerce_to_strict(self, const): + """ + This is used to ultimately *encode* into strict JSON, see `encode` + + """ + # before python 2.7, 'true', 'false', 'null', were include here. + if const in ("Infinity", "-Infinity", "NaN"): + return None + else: + return const + + def encode(self, o): + """ + Load and then dump the result using parse_constant kwarg + + Note that setting invalid separators will cause a failure at this step. + + """ + # this will raise errors in a normal-expected way + encoded_o = super(PlotlyJSONEncoder, self).encode(o) + # Brute force guessing whether NaN or Infinity values are in the string + # We catch false positive cases (e.g. strings such as titles, labels etc.) + # but this is ok since the intention is to skip the decoding / reencoding + # step when it's completely safe + + if not ("NaN" in encoded_o or "Infinity" in encoded_o): + return encoded_o + + # now: + # 1. `loads` to switch Infinity, -Infinity, NaN to None + # 2. `dumps` again so you get 'null' instead of extended JSON + try: + new_o = _json.loads(encoded_o, parse_constant=self.coerce_to_strict) + except ValueError: + # invalid separators will fail here. raise a helpful exception + raise ValueError( + "Encoding into strict JSON failed. Did you set the separators " + "valid JSON separators?" + ) + else: + return _json.dumps( + new_o, + sort_keys=self.sort_keys, + indent=self.indent, + separators=(self.item_separator, self.key_separator), + ) + + def default(self, obj): + """ + Accept an object (of unknown type) and try to encode with priority: + 1. builtin: user-defined objects + 2. sage: sage math cloud + 3. pandas: dataframes/series + 4. numpy: ndarrays + 5. datetime: time/datetime objects + + Each method throws a NotEncoded exception if it fails. + + The default method will only get hit if the object is not a type that + is naturally encoded by json: + + Normal objects: + dict object + list, tuple array + str, unicode string + int, long, float number + True true + False false + None null + + Extended objects: + float('nan') 'NaN' + float('infinity') 'Infinity' + float('-infinity') '-Infinity' + + Therefore, we only anticipate either unknown iterables or values here. + + """ + # TODO: The ordering if these methods is *very* important. Is this OK? + encoding_methods = ( + self.encode_as_plotly, + self.encode_as_sage, + self.encode_as_numpy, + self.encode_as_pandas, + self.encode_as_datetime, + self.encode_as_date, + self.encode_as_list, # because some values have `tolist` do last. + self.encode_as_decimal, + self.encode_as_pil, + ) + for encoding_method in encoding_methods: + try: + return encoding_method(obj) + except NotEncodable: + pass + return _json.JSONEncoder.default(self, obj) + + @staticmethod + def encode_as_plotly(obj): + """Attempt to use a builtin `to_plotly_json` method.""" + try: + return obj.to_plotly_json() + except AttributeError: + raise NotEncodable + + @staticmethod + def encode_as_list(obj): + """Attempt to use `tolist` method to convert to normal Python list.""" + if hasattr(obj, "tolist"): + return obj.tolist() + else: + raise NotEncodable + + @staticmethod + def encode_as_sage(obj): + """Attempt to convert sage.all.RR to floats and sage.all.ZZ to ints""" + sage_all = get_module("sage.all") + if not sage_all: + raise NotEncodable + + if obj in sage_all.RR: + return float(obj) + elif obj in sage_all.ZZ: + return int(obj) + else: + raise NotEncodable + + @staticmethod + def encode_as_pandas(obj): + """Attempt to convert pandas.NaT / pandas.NA""" + pandas = get_module("pandas", should_load=False) + if not pandas: + raise NotEncodable + + if obj is pandas.NaT: + return None + + # pandas.NA was introduced in pandas 1.0 + if hasattr(pandas, "NA") and obj is pandas.NA: + return None + + raise NotEncodable + + @staticmethod + def encode_as_numpy(obj): + """Attempt to convert numpy.ma.core.masked""" + numpy = get_module("numpy", should_load=False) + if not numpy: + raise NotEncodable + + if obj is numpy.ma.core.masked: + return float("nan") + elif isinstance(obj, numpy.ndarray) and obj.dtype.kind == "M": + try: + return numpy.datetime_as_string(obj).tolist() + except TypeError: + pass + + raise NotEncodable + + @staticmethod + def encode_as_datetime(obj): + """Convert datetime objects to iso-format strings""" + try: + return obj.isoformat() + except AttributeError: + raise NotEncodable + + @staticmethod + def encode_as_date(obj): + """Attempt to convert to utc-iso time string using date methods.""" + try: + time_string = obj.isoformat() + except AttributeError: + raise NotEncodable + else: + return iso_to_plotly_time_string(time_string) + + @staticmethod + def encode_as_decimal(obj): + """Attempt to encode decimal by converting it to float""" + if isinstance(obj, decimal.Decimal): + return float(obj) + else: + raise NotEncodable + + @staticmethod + def encode_as_pil(obj): + """Attempt to convert PIL.Image.Image to base64 data uri""" + image = get_module("PIL.Image") + if image is not None and isinstance(obj, image.Image): + return ImageUriValidator.pil_image_to_uri(obj) + else: + raise NotEncodable + + +class NotEncodable(Exception): + pass + + +def iso_to_plotly_time_string(iso_string): + """Remove timezone info and replace 'T' delimeter with ' ' (ws).""" + # make sure we don't send timezone info to plotly + if (iso_string.split("-")[:3] == "00:00") or (iso_string.split("+")[0] == "00:00"): + raise Exception( + "Plotly won't accept timestrings with timezone info.\n" + "All timestrings are assumed to be in UTC." + ) + + iso_string = iso_string.replace("-00:00", "").replace("+00:00", "") + + if iso_string.endswith("T00:00:00"): + return iso_string.replace("T00:00:00", "") + else: + return iso_string.replace("T", " ") + + +def template_doc(**names): + def _decorator(func): + if not sys.version_info[:2] == (3, 2): + if func.__doc__ is not None: + func.__doc__ = func.__doc__.format(**names) + return func + + return _decorator + + +def _natural_sort_strings(vals, reverse=False): + def key(v): + v_parts = re.split(r"(\d+)", v) + for i in range(len(v_parts)): + try: + v_parts[i] = int(v_parts[i]) + except ValueError: + # not an int + pass + return tuple(v_parts) + + return sorted(vals, key=key, reverse=reverse) + + +def _get_int_type(): + np = get_module("numpy", should_load=False) + if np: + int_type = (int, np.integer) + else: + int_type = (int,) + return int_type + + +def split_multichar(ss, chars): + """ + Split all the strings in ss at any of the characters in chars. + Example: + + >>> ss = ["a.string[0].with_separators"] + >>> chars = list(".[]_") + >>> split_multichar(ss, chars) + ['a', 'string', '0', '', 'with', 'separators'] + + :param (list) ss: A list of strings. + :param (list) chars: Is a list of chars (note: not a string). + """ + if len(chars) == 0: + return ss + c = chars.pop() + ss = reduce(lambda x, y: x + y, map(lambda x: x.split(c), ss)) + return split_multichar(ss, chars) + + +def split_string_positions(ss): + """ + Given a list of strings split using split_multichar, return a list of + integers representing the indices of the first character of every string in + the original string. + Example: + + >>> ss = ["a.string[0].with_separators"] + >>> chars = list(".[]_") + >>> ss_split = split_multichar(ss, chars) + >>> ss_split + ['a', 'string', '0', '', 'with', 'separators'] + >>> split_string_positions(ss_split) + [0, 2, 9, 11, 12, 17] + + :param (list) ss: A list of strings. + """ + return list( + map( + lambda t: t[0] + t[1], + zip(range(len(ss)), cumsum([0] + list(map(len, ss[:-1])))), + ) + ) + + +def display_string_positions(p, i=None, offset=0, length=1, char="^", trim=True): + """ + Return a string that is whitespace except at p[i] which is replaced with char. + If i is None then all the indices of the string in p are replaced with char. + + Example: + + >>> ss = ["a.string[0].with_separators"] + >>> chars = list(".[]_") + >>> ss_split = split_multichar(ss, chars) + >>> ss_split + ['a', 'string', '0', '', 'with', 'separators'] + >>> ss_pos = split_string_positions(ss_split) + >>> ss[0] + 'a.string[0].with_separators' + >>> display_string_positions(ss_pos,4) + ' ^' + >>> display_string_positions(ss_pos,4,offset=1,length=3,char="~",trim=False) + ' ~~~ ' + >>> display_string_positions(ss_pos) + '^ ^ ^ ^^ ^' + :param (list) p: A list of integers. + :param (integer|None) i: Optional index of p to display. + :param (integer) offset: Allows adding a number of spaces to the replacement. + :param (integer) length: Allows adding a replacement that is the char + repeated length times. + :param (str) char: allows customizing the replacement character. + :param (boolean) trim: trims the remaining whitespace if True. + """ + s = [" " for _ in range(max(p) + 1 + offset + length)] + maxaddr = 0 + if i is None: + for p_ in p: + for temp in range(length): + maxaddr = p_ + offset + temp + s[maxaddr] = char + else: + for temp in range(length): + maxaddr = p[i] + offset + temp + s[maxaddr] = char + ret = "".join(s) + if trim: + ret = ret[: maxaddr + 1] + return ret + + +def chomp_empty_strings(strings, c, reverse=False): + """ + Given a list of strings, some of which are the empty string "", replace the + empty strings with c and combine them with the closest non-empty string on + the left or "" if it is the first string. + Examples: + for c="_" + ['hey', '', 'why', '', '', 'whoa', '', ''] -> ['hey_', 'why__', 'whoa__'] + ['', 'hi', '', "I'm", 'bob', '', ''] -> ['_', 'hi_', "I'm", 'bob__'] + ['hi', "i'm", 'a', 'good', 'string'] -> ['hi', "i'm", 'a', 'good', 'string'] + Some special cases are: + [] -> [] + [''] -> [''] + ['', ''] -> ['_'] + ['', '', '', ''] -> ['___'] + If reverse is true, empty strings are combined with closest non-empty string + on the right or "" if it is the last string. + """ + + def _rev(vals): + return [s[::-1] for s in vals][::-1] + + if reverse: + return _rev(chomp_empty_strings(_rev(strings), c)) + if not len(strings): + return strings + if sum(map(len, strings)) == 0: + return [c * (len(strings) - 1)] + + class _Chomper: + def __init__(self, c): + self.c = c + + def __call__(self, x, y): + # x is list up to now + # y is next item in list + # x should be [""] initially, and then empty strings filtered out at the + # end + if len(y) == 0: + return x[:-1] + [x[-1] + self.c] + else: + return x + [y] + + return list(filter(len, reduce(_Chomper(c), strings, [""]))) + + +# taken from +# https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python +def levenshtein(s1, s2): + if len(s1) < len(s2): + return levenshtein(s2, s1) # len(s1) >= len(s2) + if len(s2) == 0: + return len(s1) + previous_row = range(len(s2) + 1) + for i, c1 in enumerate(s1): + current_row = [i + 1] + for j, c2 in enumerate(s2): + # j+1 instead of j since previous_row and current_row are one character longer + # than s2 + insertions = previous_row[j + 1] + 1 + deletions = current_row[j] + 1 + substitutions = previous_row[j] + (c1 != c2) + current_row.append(min(insertions, deletions, substitutions)) + previous_row = current_row + return previous_row[-1] + + +def find_closest_string(string, strings): + def _key(s): + # sort by levenshtein distance and lexographically to maintain a stable + # sort for different keys with the same levenshtein distance + return (levenshtein(s, string), s) + + return sorted(strings, key=_key)[0] diff --git a/.venv_haddock/lib/python3.12/site-packages/_yaml/__init__.py b/.venv_haddock/lib/python3.12/site-packages/_yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7baa8c4b68127d5cdf0be9a799429e61347c2694 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/_yaml/__init__.py @@ -0,0 +1,33 @@ +# This is a stub package designed to roughly emulate the _yaml +# extension module, which previously existed as a standalone module +# and has been moved into the `yaml` package namespace. +# It does not perfectly mimic its old counterpart, but should get +# close enough for anyone who's relying on it even when they shouldn't. +import yaml + +# in some circumstances, the yaml module we imoprted may be from a different version, so we need +# to tread carefully when poking at it here (it may not have the attributes we expect) +if not getattr(yaml, '__with_libyaml__', False): + from sys import version_info + + exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError + raise exc("No module named '_yaml'") +else: + from yaml._yaml import * + import warnings + warnings.warn( + 'The _yaml extension module is now located at yaml._yaml' + ' and its location is subject to change. To use the' + ' LibYAML-based parser and emitter, import from `yaml`:' + ' `from yaml import CLoader as Loader, CDumper as Dumper`.', + DeprecationWarning + ) + del warnings + # Don't `del yaml` here because yaml is actually an existing + # namespace member of _yaml. + +__name__ = '_yaml' +# If the module is top-level (i.e. not a part of any specific package) +# then the attribute should be set to ''. +# https://docs.python.org/3.8/library/types.html +__package__ = '' diff --git a/.venv_haddock/lib/python3.12/site-packages/haddock/__init__.py b/.venv_haddock/lib/python3.12/site-packages/haddock/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6d7ebc862b9cf00bf77a7341904708973405541 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/haddock/__init__.py @@ -0,0 +1,47 @@ +"""HADDOCK3 library.""" +import logging +import sys +from pathlib import Path +from importlib.metadata import version as package_version + +log = logging.getLogger(__name__) +log.handlers.clear() +log.setLevel(logging.DEBUG) +handler = logging.StreamHandler(sys.stdout) +handler.setFormatter(logging.Formatter( + "[%(asctime)s %(module)s %(levelname)s] %(message)s")) +log.addHandler(handler) + +haddock3_source_path = Path(__file__).resolve().parent +haddock3_repository_path = haddock3_source_path.parents[1] +core_path = Path(haddock3_source_path, "core") +toppar_path = Path(haddock3_source_path, "cns", "toppar") +modules_defaults_path = Path(haddock3_source_path, "modules", "defaults.yaml") + +FCC_path = Path(haddock3_source_path.parent, 'fcc') +RMSD_path = Path(haddock3_source_path.parent, 'fast-rmsdmatrix') + +config_expert_levels = ("easy", "expert", "guru") +# yaml parameters with this `explevel` should be ignored when reading the yaml +_hidden_level = "hidden" + + +class EmptyPath: + """Define the type EmptyPath.""" + + def __str__(self) -> str: + return "" + + def __repr__(self) -> str: + return "" + + def __bool__(self) -> bool: + return False + + +# version +version = package_version("haddock3") + +v_major, v_minor, v_patch = version.split('.') + +contact_us = 'https://github.com/haddocking/haddock3/issues' diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/__init__.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8917c598a4da370f58e25d8ef0357c645d0d4e32 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/__init__.py @@ -0,0 +1,94 @@ +# Copyright (C) 2008 John Paulett (john -at- paulett.org) +# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com) +# All rights reserved. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. + +"""Python library for serializing any arbitrary object graph into JSON. + +.. warning:: + + The jsonpickle module **is not secure**. Only unpickle data you trust. + + It is possible to construct malicious pickle data which will **execute + arbitrary code during unpickling**. Never unpickle data that could have come + from an untrusted source, or that could have been tampered with. + + Consider signing data with an HMAC if you need to ensure that it has not + been tampered with. + + Safer deserialization approaches, such as reading the raw JSON + directly, may be more appropriate if you are processing untrusted data. + +jsonpickle can take almost any Python object and turn the object into JSON. +Additionally, it can reconstitute the object back into Python. + +The object must be accessible globally via a module and must +inherit from object (AKA new-style classes). + +Create an object:: + + class Thing(object): + def __init__(self, name): + self.name = name + + obj = Thing('Awesome') + +Use jsonpickle to transform the object into a JSON string:: + + import jsonpickle + frozen = jsonpickle.encode(obj) + +Use jsonpickle to recreate a Python object from a JSON string:: + + thawed = jsonpickle.decode(frozen) + +The new object has the same type and data, but essentially is now a copy of +the original. + +.. code-block:: python + + assert obj.name == thawed.name + +If you will never need to load (regenerate the Python class from JSON), you can +pass in the keyword unpicklable=False to prevent extra information from being +added to JSON:: + + oneway = jsonpickle.encode(obj, unpicklable=False) + result = jsonpickle.decode(oneway) + assert obj.name == result['name'] == 'Awesome' + +.. note:: + + Please see the note in the :ref:`api-docs` when serializing dictionaries + that contain non-string dictionary keys. + +""" +# Export other names not in __all__ +from .backend import JSONBackend # noqa: F401 +from .backend import json +from .handlers import register # noqa: F401 +from .handlers import unregister # noqa: F401 +from .pickler import Pickler # noqa: F401 +from .pickler import encode +from .unpickler import Unpickler # noqa: F401 +from .unpickler import decode +from .version import __version__ # noqa: F401 + +__all__ = ('encode', 'decode') + +# register built-in handlers +__import__('jsonpickle.handlers', level=0) + +# Export specific JSONPluginMgr methods into the jsonpickle namespace +set_preferred_backend = json.set_preferred_backend +set_decoder_options = json.set_decoder_options +set_encoder_options = json.set_encoder_options +load_backend = json.load_backend +remove_backend = json.remove_backend +enable_fallthrough = json.enable_fallthrough + +# json.load(), loads(), dump(), dumps() compatibility +dumps = encode +loads = decode diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/backend.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..a1dc6727d993e17b6dd7a0dfb95b071c3ac27230 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/backend.py @@ -0,0 +1,283 @@ +class JSONBackend: + """Manages encoding and decoding using various backends. + + It tries these modules in this order: + simplejson, json, ujson + + simplejson is a fast and popular backend and is tried first. + json comes with Python and is tried second. + + """ + + def _verify(self): + """Ensures that we've loaded at least one JSON backend.""" + if self._verified: + return + raise AssertionError('jsonpickle could not load any json modules') + + def encode(self, obj, indent=None, separators=None): + """ + Attempt to encode an object into JSON. + + This tries the loaded backends in order and passes along the last + exception if no backend is able to encode the object. + + """ + self._verify() + + if not self._fallthrough: + name = self._backend_names[0] + return self.backend_encode(name, obj, indent=indent, separators=separators) + + for idx, name in enumerate(self._backend_names): + try: + return self.backend_encode( + name, obj, indent=indent, separators=separators + ) + except Exception as e: + if idx == len(self._backend_names) - 1: + raise e + + # def dumps + dumps = encode + + def decode(self, string): + """ + Attempt to decode an object from a JSON string. + + This tries the loaded backends in order and passes along the last + exception if no backends are able to decode the string. + + """ + self._verify() + + if not self._fallthrough: + name = self._backend_names[0] + return self.backend_decode(name, string) + + for idx, name in enumerate(self._backend_names): + try: + return self.backend_decode(name, string) + except self._decoder_exceptions[name] as e: + if idx == len(self._backend_names) - 1: + raise e + else: + pass # and try a more forgiving encoder + + # def loads + loads = decode + + def __init__(self, fallthrough=True): + # Whether we should fallthrough to the next backend + self._fallthrough = fallthrough + # The names of backends that have been successfully imported + self._backend_names = [] + + # A dictionary mapping backend names to encode/decode functions + self._encoders = {} + self._decoders = {} + + # Options to pass to specific encoders + self._encoder_options = {} + + # Options to pass to specific decoders + self._decoder_options = {} + + # The exception class that is thrown when a decoding error occurs + self._decoder_exceptions = {} + + # Whether we've loaded any backends successfully + self._verified = False + + self.load_backend('simplejson') + self.load_backend('json') + self.load_backend('ujson') + # TODO: remove default registration of the YAML backend in v5.0.0. + self.load_backend( + 'yaml', dumps='dump', loads='safe_load', loads_exc='YAMLError' + ) + + # Defaults for various encoders + json_opts = ((), {'sort_keys': False}) + self._encoder_options = { + 'ujson': ((), {'sort_keys': False, 'escape_forward_slashes': False}), + 'json': json_opts, + 'simplejson': json_opts, + 'django.util.simplejson': json_opts, + } + + def enable_fallthrough(self, enable): + """ + Disable jsonpickle's fallthrough-on-error behavior + + By default, jsonpickle tries the next backend when decoding or + encoding using a backend fails. + + This can make it difficult to force jsonpickle to use a specific + backend, and catch errors, because the error will be suppressed and + may not be raised by the subsequent backend. + + Calling `enable_backend(False)` will make jsonpickle immediately + re-raise any exceptions raised by the backends. + + """ + self._fallthrough = enable + + def _store(self, dct, backend, obj, name): + try: + dct[backend] = getattr(obj, name) + except AttributeError: + self.remove_backend(backend) + return False + return True + + def load_backend(self, name, dumps='dumps', loads='loads', loads_exc=ValueError): + """Load a JSON backend by name. + + This method loads a backend and sets up references to that + backend's loads/dumps functions and exception classes. + + :param dumps: is the name of the backend's encode method. + The method should take an object and return a string. + Defaults to 'dumps'. + :param loads: names the backend's method for the reverse + operation -- returning a Python object from a string. + :param loads_exc: can be either the name of the exception class + used to denote decoding errors, or it can be a direct reference + to the appropriate exception class itself. If it is a name, + then the assumption is that an exception class of that name + can be found in the backend module's namespace. + :param load: names the backend's 'load' method. + :param dump: names the backend's 'dump' method. + :rtype bool: True on success, False if the backend could not be loaded. + + """ + try: + # Load the JSON backend + mod = __import__(name) + except ImportError: + return False + + # Handle submodules, e.g. django.utils.simplejson + try: + for attr in name.split('.')[1:]: + mod = getattr(mod, attr) + except AttributeError: + return False + + if not self._store(self._encoders, name, mod, dumps) or not self._store( + self._decoders, name, mod, loads + ): + return False + + if isinstance(loads_exc, str): + # This backend's decoder exception is part of the backend + if not self._store(self._decoder_exceptions, name, mod, loads_exc): + return False + else: + # simplejson uses ValueError + self._decoder_exceptions[name] = loads_exc + + # Setup the default args and kwargs for this encoder/decoder + self._encoder_options.setdefault(name, ([], {})) + self._decoder_options.setdefault(name, ([], {})) + + # Add this backend to the list of candidate backends + self._backend_names.append(name) + + # Indicate that we successfully loaded a JSON backend + self._verified = True + return True + + def remove_backend(self, name): + """Remove all entries for a particular backend.""" + self._encoders.pop(name, None) + self._decoders.pop(name, None) + self._decoder_exceptions.pop(name, None) + self._decoder_options.pop(name, None) + self._encoder_options.pop(name, None) + if name in self._backend_names: + self._backend_names.remove(name) + self._verified = bool(self._backend_names) + + def backend_encode(self, name, obj, indent=None, separators=None): + optargs, optkwargs = self._encoder_options.get(name, ([], {})) + encoder_kwargs = optkwargs.copy() + if indent is not None: + encoder_kwargs['indent'] = indent + if separators is not None: + encoder_kwargs['separators'] = separators + encoder_args = (obj,) + tuple(optargs) + return self._encoders[name](*encoder_args, **encoder_kwargs) + + def backend_decode(self, name, string): + optargs, optkwargs = self._decoder_options.get(name, ((), {})) + decoder_kwargs = optkwargs.copy() + return self._decoders[name](string, *optargs, **decoder_kwargs) + + def set_preferred_backend(self, name): + """ + Set the preferred json backend. + + If a preferred backend is set then jsonpickle tries to use it + before any other backend. + + For example:: + + set_preferred_backend('simplejson') + + If the backend is not one of the built-in jsonpickle backends + (json/simplejson) then you must load the backend + prior to calling set_preferred_backend. + + AssertionError is raised if the backend has not been loaded. + + """ + if name in self._backend_names: + self._backend_names.remove(name) + self._backend_names.insert(0, name) + else: + errmsg = 'The "%s" backend has not been loaded.' % name + raise AssertionError(errmsg) + + def set_encoder_options(self, name, *args, **kwargs): + """ + Associate encoder-specific options with an encoder. + + After calling set_encoder_options, any calls to jsonpickle's + encode method will pass the supplied args and kwargs along to + the appropriate backend's encode method. + + For example:: + + set_encoder_options('simplejson', sort_keys=True, indent=4) + + See the appropriate encoder's documentation for details about + the supported arguments and keyword arguments. + + WARNING: If you pass sort_keys=True, and the object to encode + contains ``__slots__``, and you set ``warn`` to True, + a TypeError will be raised! + """ + self._encoder_options[name] = (args, kwargs) + + def set_decoder_options(self, name, *args, **kwargs): + """ + Associate decoder-specific options with a decoder. + + After calling set_decoder_options, any calls to jsonpickle's + decode method will pass the supplied args and kwargs along to + the appropriate backend's decode method. + + For example:: + + set_decoder_options('simplejson', encoding='utf8', cls=JSONDecoder) + + See the appropriate decoder's documentation for details about + the supported arguments and keyword arguments. + + """ + self._decoder_options[name] = (args, kwargs) + + +json = JSONBackend() diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/compat.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..c8ed87213135483099a2beb30863dfb850023d5e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/compat.py @@ -0,0 +1,18 @@ +"""jsonpickle.compat is a deprecated private module and will be removed in the future""" + +import queue # noqa +import sys +from collections.abc import Iterator as abc_iterator # noqa + +PY_MAJOR = sys.version_info[0] + +class_types = (type,) +iterator_types = (type(iter('')),) + +string_types = (str,) +numeric_types = (int, float) +ustr = str + + +def iterator(class_): + return class_ diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/errors.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..178b18df1313bc3c527972d53e949434d5691a15 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/errors.py @@ -0,0 +1,8 @@ +""" +Stores custom jsonpickle errors. +""" + + +class ClassNotFoundError(BaseException): + def __init__(*args, **kwargs): + pass diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/handlers.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..b6bdb815599282b6f1b94c810f5adfdfe5301e5a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/handlers.py @@ -0,0 +1,291 @@ +""" +Custom handlers may be created to handle other objects. Each custom handler +must derive from :class:`jsonpickle.handlers.BaseHandler` and +implement ``flatten`` and ``restore``. + +A handler can be bound to other types by calling +:func:`jsonpickle.handlers.register`. + +""" + +import array +import copy +import datetime +import io +import queue +import re +import threading +import uuid + +from . import util + + +class Registry: + def __init__(self): + self._handlers = {} + self._base_handlers = {} + + def get(self, cls_or_name, default=None): + """ + :param cls_or_name: the type or its fully qualified name + :param default: default value, if a matching handler is not found + + Looks up a handler by type reference or its fully + qualified name. If a direct match + is not found, the search is performed over all + handlers registered with base=True. + """ + handler = self._handlers.get(cls_or_name) + # attempt to find a base class + if handler is None and util.is_type(cls_or_name): + for cls, base_handler in self._base_handlers.items(): + if issubclass(cls_or_name, cls): + return base_handler + return default if handler is None else handler + + def register(self, cls, handler=None, base=False): + """Register the a custom handler for a class + + :param cls: The custom object class to handle + :param handler: The custom handler class (if + None, a decorator wrapper is returned) + :param base: Indicates whether the handler should + be registered for all subclasses + + This function can be also used as a decorator + by omitting the `handler` argument:: + + @jsonpickle.handlers.register(Foo, base=True) + class FooHandler(jsonpickle.handlers.BaseHandler): + pass + + """ + if handler is None: + + def _register(handler_cls): + self.register(cls, handler=handler_cls, base=base) + return handler_cls + + return _register + if not util.is_type(cls): + raise TypeError(f'{cls!r} is not a class/type') + # store both the name and the actual type for the ugly cases like + # _sre.SRE_Pattern that cannot be loaded back directly + self._handlers[util.importable_name(cls)] = self._handlers[cls] = handler + if base: + # only store the actual type for subclass checking + self._base_handlers[cls] = handler + + def unregister(self, cls): + self._handlers.pop(cls, None) + self._handlers.pop(util.importable_name(cls), None) + self._base_handlers.pop(cls, None) + + +registry = Registry() +register = registry.register +unregister = registry.unregister +get = registry.get + + +class BaseHandler: + def __init__(self, context): + """ + Initialize a new handler to handle a registered type. + + :Parameters: + - `context`: reference to pickler/unpickler + + """ + self.context = context + + def flatten(self, obj, data): + """ + Flatten `obj` into a json-friendly form and write result to `data`. + + :param object obj: The object to be serialized. + :param dict data: A partially filled dictionary which will contain the + json-friendly representation of `obj` once this method has + finished. + """ + raise NotImplementedError('You must implement flatten() in %s' % self.__class__) + + def restore(self, obj): + """ + Restore an object of the registered type from the json-friendly + representation `obj` and return it. + """ + raise NotImplementedError('You must implement restore() in %s' % self.__class__) + + @classmethod + def handles(self, cls): + """ + Register this handler for the given class. Suitable as a decorator, + e.g.:: + + @MyCustomHandler.handles + class MyCustomClass: + def __reduce__(self): + ... + """ + registry.register(cls, self) + return cls + + def __call__(self, context): + """This permits registering either Handler instances or classes + + :Parameters: + - `context`: reference to pickler/unpickler + """ + self.context = context + return self + + +class ArrayHandler(BaseHandler): + """Flatten and restore array.array objects""" + + def flatten(self, obj, data): + data['typecode'] = obj.typecode + data['values'] = self.context.flatten(obj.tolist(), reset=False) + return data + + def restore(self, data): + typecode = data['typecode'] + values = self.context.restore(data['values'], reset=False) + if typecode == 'c': + values = [bytes(x) for x in values] + return array.array(typecode, values) + + +ArrayHandler.handles(array.array) + + +class DatetimeHandler(BaseHandler): + """Custom handler for datetime objects + + Datetime objects use __reduce__, and they generate binary strings encoding + the payload. This handler encodes that payload to reconstruct the + object. + + """ + + def flatten(self, obj, data): + pickler = self.context + if not pickler.unpicklable: + if hasattr(obj, 'isoformat'): + result = obj.isoformat() + else: + result = str(obj) + return result + cls, args = obj.__reduce__() + flatten = pickler.flatten + payload = util.b64encode(args[0]) + args = [payload] + [flatten(i, reset=False) for i in args[1:]] + data['__reduce__'] = (flatten(cls, reset=False), args) + return data + + def restore(self, data): + cls, args = data['__reduce__'] + unpickler = self.context + restore = unpickler.restore + cls = restore(cls, reset=False) + value = util.b64decode(args[0]) + params = (value,) + tuple([restore(i, reset=False) for i in args[1:]]) + return cls.__new__(cls, *params) + + +DatetimeHandler.handles(datetime.datetime) +DatetimeHandler.handles(datetime.date) +DatetimeHandler.handles(datetime.time) + + +class RegexHandler(BaseHandler): + """Flatten _sre.SRE_Pattern (compiled regex) objects""" + + def flatten(self, obj, data): + data['pattern'] = obj.pattern + return data + + def restore(self, data): + return re.compile(data['pattern']) + + +RegexHandler.handles(type(re.compile(''))) + + +class QueueHandler(BaseHandler): + """Opaquely serializes Queue objects + + Queues contains mutex and condition variables which cannot be serialized. + Construct a new Queue instance when restoring. + + """ + + def flatten(self, obj, data): + return data + + def restore(self, data): + return queue.Queue() + + +QueueHandler.handles(queue.Queue) + + +class CloneFactory: + """Serialization proxy for collections.defaultdict's default_factory""" + + def __init__(self, exemplar): + self.exemplar = exemplar + + def __call__(self, clone=copy.copy): + """Create new instances by making copies of the provided exemplar""" + return clone(self.exemplar) + + def __repr__(self): + return f'' + + +class UUIDHandler(BaseHandler): + """Serialize uuid.UUID objects""" + + def flatten(self, obj, data): + data['hex'] = obj.hex + return data + + def restore(self, data): + return uuid.UUID(data['hex']) + + +UUIDHandler.handles(uuid.UUID) + + +class LockHandler(BaseHandler): + """Serialize threading.Lock objects""" + + def flatten(self, obj, data): + data['locked'] = obj.locked() + return data + + def restore(self, data): + lock = threading.Lock() + if data.get('locked', False): + lock.acquire() + return lock + + +_lock = threading.Lock() +LockHandler.handles(_lock.__class__) + + +class TextIOHandler(BaseHandler): + """Serialize file descriptors as None because we cannot roundtrip""" + + def flatten(self, obj, data): + return None + + def restore(self, data): + """Restore should never get called because flatten() returns None""" + raise AssertionError('Restoring IO.TextIOHandler is not supported') + + +TextIOHandler.handles(io.TextIOWrapper) diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/pickler.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/pickler.py new file mode 100644 index 0000000000000000000000000000000000000000..cad514213ad5d30c91be47ac8058cbb2d2a3e852 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/pickler.py @@ -0,0 +1,870 @@ +# Copyright (C) 2008 John Paulett (john -at- paulett.org) +# Copyright (C) 2009-2024 David Aguilar (davvid -at- gmail.com) +# All rights reserved. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. +import decimal +import inspect +import itertools +import sys +import types +import warnings +from itertools import chain, islice + +from . import handlers, tags, util +from .backend import json + + +def encode( + value, + unpicklable=True, + make_refs=True, + keys=False, + max_depth=None, + reset=True, + backend=None, + warn=False, + context=None, + max_iter=None, + use_decimal=False, + numeric_keys=False, + use_base85=False, + fail_safe=None, + indent=None, + separators=None, + include_properties=False, + handle_readonly=False, +): + """Return a JSON formatted representation of value, a Python object. + + :param unpicklable: If set to ``False`` then the output will not contain the + information necessary to turn the JSON data back into Python objects, + but a simpler JSON stream is produced. It's recommended to set this + parameter to ``False`` when your code does not rely on two objects + having the same ``id()`` value, and when it is sufficient for those two + objects to be equal by ``==``, such as when serializing sklearn + instances. If you experience (de)serialization being incorrect when you + use numpy, pandas, or sklearn handlers, this should be set to ``False``. + If you want the output to not include the dtype for numpy arrays, add:: + + jsonpickle.register( + numpy.generic, UnpicklableNumpyGenericHandler, base=True + ) + + before your pickling code. + :param make_refs: If set to False jsonpickle's referencing support is + disabled. Objects that are id()-identical won't be preserved across + encode()/decode(), but the resulting JSON stream will be conceptually + simpler. jsonpickle detects cyclical objects and will break the cycle + by calling repr() instead of recursing when make_refs is set False. + :param keys: If set to True then jsonpickle will encode non-string + dictionary keys instead of coercing them into strings via `repr()`. + This is typically what you want if you need to support Integer or + objects as dictionary keys. + :param max_depth: If set to a non-negative integer then jsonpickle will + not recurse deeper than 'max_depth' steps into the object. Anything + deeper than 'max_depth' is represented using a Python repr() of the + object. + :param reset: Custom pickle handlers that use the `Pickler.flatten` method or + `jsonpickle.encode` function must call `encode` with `reset=False` + in order to retain object references during pickling. + This flag is not typically used outside of a custom handler or + `__getstate__` implementation. + :param backend: If set to an instance of jsonpickle.backend.JSONBackend, + jsonpickle will use that backend for deserialization. + :param warn: If set to True then jsonpickle will warn when it + returns None for an object which it cannot pickle + (e.g. file descriptors). + :param context: Supply a pre-built Pickler or Unpickler object to the + `jsonpickle.encode` and `jsonpickle.decode` machinery instead + of creating a new instance. The `context` represents the currently + active Pickler and Unpickler objects when custom handlers are + invoked by jsonpickle. + :param max_iter: If set to a non-negative integer then jsonpickle will + consume at most `max_iter` items when pickling iterators. + :param use_decimal: If set to True jsonpickle will allow Decimal + instances to pass-through, with the assumption that the simplejson + backend will be used in `use_decimal` mode. In order to use this mode + you will need to configure simplejson:: + + jsonpickle.set_encoder_options('simplejson', + use_decimal=True, sort_keys=True) + jsonpickle.set_decoder_options('simplejson', + use_decimal=True) + jsonpickle.set_preferred_backend('simplejson') + + NOTE: A side-effect of the above settings is that float values will be + converted to Decimal when converting to json. + :param numeric_keys: Only use this option if the backend supports integer + dict keys natively. This flag tells jsonpickle to leave numeric keys + as-is rather than conforming them to json-friendly strings. + Using ``keys=True`` is the typical solution for integer keys, so only + use this if you have a specific use case where you want to allow the + backend to handle serialization of numeric dict keys. + :param use_base85: + If possible, use base85 to encode binary data. Base85 bloats binary data + by 1/4 as opposed to base64, which expands it by 1/3. This argument is + ignored on Python 2 because it doesn't support it. + :param fail_safe: If set to a function exceptions are ignored when pickling + and if a exception happens the function is called and the return value + is used as the value for the object that caused the error + :param indent: When `indent` is a non-negative integer, then JSON array + elements and object members will be pretty-printed with that indent + level. An indent level of 0 will only insert newlines. ``None`` is + the most compact representation. Since the default item separator is + ``(', ', ': ')``, the output might include trailing whitespace when + ``indent`` is specified. You can use ``separators=(',', ': ')`` to + avoid this. This value is passed directly to the active JSON backend + library and not used by jsonpickle directly. + :param separators: + If ``separators`` is an ``(item_separator, dict_separator)`` tuple + then it will be used instead of the default ``(', ', ': ')`` + separators. ``(',', ':')`` is the most compact JSON representation. + This value is passed directly to the active JSON backend library and + not used by jsonpickle directly. + :param include_properties: + Include the names and values of class properties in the generated json. + Properties are unpickled properly regardless of this setting, this is + meant to be used if processing the json outside of Python. Certain types + such as sets will not pickle due to not having a native-json equivalent. + Defaults to ``False``. + :param handle_readonly: + Handle objects with readonly methods, such as Django's SafeString. This + basically prevents jsonpickle from raising an exception for such objects. + You MUST set ``handle_readonly=True`` for the decoding if you encode with + this flag set to ``True``. + + >>> encode('my string') == '"my string"' + True + >>> encode(36) == '36' + True + >>> encode({'foo': True}) == '{"foo": true}' + True + >>> encode({'foo': [1, 2, [3, 4]]}, max_depth=1) + '{"foo": "[1, 2, [3, 4]]"}' + + """ + backend = backend or json + context = context or Pickler( + unpicklable=unpicklable, + make_refs=make_refs, + keys=keys, + backend=backend, + max_depth=max_depth, + warn=warn, + max_iter=max_iter, + numeric_keys=numeric_keys, + use_decimal=use_decimal, + use_base85=use_base85, + fail_safe=fail_safe, + include_properties=include_properties, + handle_readonly=handle_readonly, + original_object=value, + ) + return backend.encode( + context.flatten(value, reset=reset), indent=indent, separators=separators + ) + + +def _in_cycle(obj, objs, max_reached, make_refs): + """Detect cyclic structures that would lead to infinite recursion""" + return ( + (max_reached or (not make_refs and id(obj) in objs)) + and not util.is_primitive(obj) + and not util.is_enum(obj) + ) + + +def _mktyperef(obj): + """Return a typeref dictionary + + >>> _mktyperef(AssertionError) == {'py/type': 'builtins.AssertionError'} + True + + """ + return {tags.TYPE: util.importable_name(obj)} + + +def _wrap_string_slot(string): + """Converts __slots__ = 'a' into __slots__ = ('a',)""" + if isinstance(string, str): + return (string,) + return string + + +class Pickler: + def __init__( + self, + unpicklable=True, + make_refs=True, + max_depth=None, + backend=None, + keys=False, + warn=False, + max_iter=None, + numeric_keys=False, + use_decimal=False, + use_base85=False, + fail_safe=None, + include_properties=False, + handle_readonly=False, + original_object=None, + ): + self.unpicklable = unpicklable + self.make_refs = make_refs + self.backend = backend or json + self.keys = keys + self.warn = warn + self.numeric_keys = numeric_keys + self.use_base85 = use_base85 + # The current recursion depth + self._depth = -1 + # The maximal recursion depth + self._max_depth = max_depth + # Maps id(obj) to reference IDs + self._objs = {} + # Avoids garbage collection + self._seen = [] + # maximum amount of items to take from a pickled iterator + self._max_iter = max_iter + # Whether to allow decimals to pass-through + self._use_decimal = use_decimal + # A cache of objects that have already been flattened. + self._flattened = {} + # Used for util.is_readonly, see +483 + self.handle_readonly = handle_readonly + + if self.use_base85: + self._bytes_tag = tags.B85 + self._bytes_encoder = util.b85encode + else: + self._bytes_tag = tags.B64 + self._bytes_encoder = util.b64encode + + # ignore exceptions + self.fail_safe = fail_safe + self.include_properties = include_properties + + self._original_object = original_object + + def _determine_sort_keys(self): + for _, options in getattr(self.backend, '_encoder_options', {}).values(): + if options.get('sort_keys', False): + # the user has set one of the backends to sort keys + return True + return False + + def _sort_attrs(self, obj): + if hasattr(obj, '__slots__') and self.warn: + # Slots are read-only by default, the only way + # to sort keys is to do it in a subclass + # and that would require calling the init function + # of the parent again. That could cause issues + # so we refuse to handle it. + raise TypeError( + 'Objects with __slots__ cannot have their keys reliably sorted by ' + 'jsonpickle! Please sort the keys in the __slots__ definition instead.' + ) + # Somehow some classes don't have slots or dict + elif hasattr(obj, '__dict__'): + try: + obj.__dict__ = dict(sorted(obj.__dict__.items())) + except (TypeError, AttributeError): + # Can't set attributes of builtin/extension type + pass + return obj + + def reset(self): + self._objs = {} + self._depth = -1 + self._seen = [] + self._flattened = {} + + def _push(self): + """Steps down one level in the namespace.""" + self._depth += 1 + + def _pop(self, value): + """Step up one level in the namespace and return the value. + If we're at the root, reset the pickler's state. + """ + self._depth -= 1 + if self._depth == -1: + self.reset() + return value + + def _log_ref(self, obj): + """ + Log a reference to an in-memory object. + Return True if this object is new and was assigned + a new ID. Otherwise return False. + """ + objid = id(obj) + is_new = objid not in self._objs + if is_new: + new_id = len(self._objs) + self._objs[objid] = new_id + return is_new + + def _mkref(self, obj): + """ + Log a reference to an in-memory object, and return + if that object should be considered newly logged. + """ + is_new = self._log_ref(obj) + # Pretend the object is new + pretend_new = not self.unpicklable or not self.make_refs + return pretend_new or is_new + + def _getref(self, obj): + """Return a "py/id" entry for the specified object""" + return {tags.ID: self._objs.get(id(obj))} + + def _flatten(self, obj): + """Flatten an object and its guts into a json-safe representation""" + if self.unpicklable and self.make_refs: + result = self._flatten_impl(obj) + else: + try: + result = self._flattened[id(obj)] + except KeyError: + result = self._flattened[id(obj)] = self._flatten_impl(obj) + return result + + def flatten(self, obj, reset=True): + """Takes an object and returns a JSON-safe representation of it. + + Simply returns any of the basic builtin datatypes + + >>> p = Pickler() + >>> p.flatten('hello world') == 'hello world' + True + >>> p.flatten(49) + 49 + >>> p.flatten(350.0) + 350.0 + >>> p.flatten(True) + True + >>> p.flatten(False) + False + >>> r = p.flatten(None) + >>> r is None + True + >>> p.flatten(False) + False + >>> p.flatten([1, 2, 3, 4]) + [1, 2, 3, 4] + >>> p.flatten((1,2,))[tags.TUPLE] + [1, 2] + >>> p.flatten({'key': 'value'}) == {'key': 'value'} + True + """ + if reset: + self.reset() + if self._determine_sort_keys(): + obj = self._sort_attrs(obj) + return self._flatten(obj) + + def _flatten_bytestring(self, obj): + return {self._bytes_tag: self._bytes_encoder(obj)} + + def _flatten_impl(self, obj): + ######################################### + # if obj is nonrecursive return immediately + # for performance reasons we don't want to do recursive checks + if type(obj) is bytes: + return self._flatten_bytestring(obj) + + # Decimal is a primitive when use_decimal is True + if type(obj) in (str, bool, int, float, type(None)) or ( + self._use_decimal and isinstance(obj, decimal.Decimal) + ): + return obj + ######################################### + + self._push() + return self._pop(self._flatten_obj(obj)) + + def _max_reached(self): + return self._depth == self._max_depth + + def _pickle_warning(self, obj): + if self.warn: + msg = 'jsonpickle cannot pickle %r: replaced with None' % obj + warnings.warn(msg) + + def _flatten_obj(self, obj): + self._seen.append(obj) + + max_reached = self._max_reached() + + try: + in_cycle = _in_cycle(obj, self._objs, max_reached, self.make_refs) + if in_cycle: + # break the cycle + flatten_func = repr + else: + flatten_func = self._get_flattener(obj) + + if flatten_func is None: + self._pickle_warning(obj) + return None + + return flatten_func(obj) + + except (KeyboardInterrupt, SystemExit) as e: + raise e + except Exception as e: + if self.fail_safe is None: + raise e + else: + return self.fail_safe(e) + + def _list_recurse(self, obj): + return [self._flatten(v) for v in obj] + + def _flatten_function(self, obj): + if self.unpicklable: + data = {tags.FUNCTION: util.importable_name(obj)} + else: + data = None + + return data + + def _getstate(self, obj, data): + state = self._flatten(obj) + if self.unpicklable: + data[tags.STATE] = state + else: + data = state + return data + + def _flatten_key_value_pair(self, k, v, data): + """Flatten a key/value pair into the passed-in dictionary.""" + if not util.is_picklable(k, v): + return data + # TODO: use inspect.getmembers_static on 3.11+ because it avoids dynamic + # attribute lookups + if ( + self.handle_readonly + and k in {attr for attr, val in inspect.getmembers(self._original_object)} + and util.is_readonly(self._original_object, k, v) + ): + return data + + if k is None: + k = 'null' # for compatibility with common json encoders + + if self.numeric_keys and isinstance(k, (int, float)): + pass + elif not isinstance(k, str): + try: + k = repr(k) + except Exception: + k = str(k) + + data[k] = self._flatten(v) + return data + + def _flatten_obj_attrs(self, obj, attrs, data): + flatten = self._flatten_key_value_pair + ok = False + for k in attrs: + try: + if not k.startswith('__'): + value = getattr(obj, k) + else: + value = getattr(obj, f"_{obj.__class__.__name__}{k}") + flatten(k, value, data) + except AttributeError: + # The attribute may have been deleted + continue + ok = True + return ok + + def _flatten_properties(self, obj, data, allslots=None): + if allslots is None: + # setting a list as a default argument can lead to some weird errors + allslots = [] + + # convert to set in case there are a lot of slots + allslots_set = set(itertools.chain.from_iterable(allslots)) + + # i don't like lambdas + def valid_property(x): + return not x[0].startswith('__') and x[0] not in allslots_set + + properties = [ + x[0] for x in inspect.getmembers(obj.__class__) if valid_property(x) + ] + + properties_dict = {} + for p_name in properties: + p_val = getattr(obj, p_name) + if util.is_not_class(p_val): + properties_dict[p_name] = p_val + else: + properties_dict[p_name] = self._flatten(p_val) + + data[tags.PROPERTY] = properties_dict + + return data + + def _flatten_newstyle_with_slots(self, obj, data): + """Return a json-friendly dict for new-style objects with __slots__.""" + allslots = [ + _wrap_string_slot(getattr(cls, '__slots__', tuple())) + for cls in obj.__class__.mro() + ] + + # add properties to the attribute list + if self.include_properties: + data = self._flatten_properties(obj, data, allslots) + + if not self._flatten_obj_attrs(obj, chain(*allslots), data): + attrs = [ + x for x in dir(obj) if not x.startswith('__') and not x.endswith('__') + ] + self._flatten_obj_attrs(obj, attrs, data) + + return data + + def _flatten_obj_instance(self, obj): + """Recursively flatten an instance and return a json-friendly dict""" + data = {} + has_class = hasattr(obj, '__class__') + has_dict = hasattr(obj, '__dict__') + has_slots = not has_dict and hasattr(obj, '__slots__') + has_getnewargs = util.has_method(obj, '__getnewargs__') + has_getnewargs_ex = util.has_method(obj, '__getnewargs_ex__') + has_getinitargs = util.has_method(obj, '__getinitargs__') + has_reduce, has_reduce_ex = util.has_reduce(obj) + exclude = set(getattr(obj, '_jsonpickle_exclude', ())) + + # Support objects with __getstate__(); this ensures that + # both __setstate__() and __getstate__() are implemented + has_own_getstate = hasattr(type(obj), '__getstate__') and type( + obj + ).__getstate__ is not getattr(object, '__getstate__', None) + # not using has_method since __getstate__() is handled separately below + # Note: on Python 3.11+, all objects have __getstate__. + + if has_class: + cls = obj.__class__ + else: + cls = type(obj) + + # Check for a custom handler + class_name = util.importable_name(cls) + handler = handlers.get(cls, handlers.get(class_name)) + if handler is not None: + if self.unpicklable: + data[tags.OBJECT] = class_name + result = handler(self).flatten(obj, data) + if result is None: + self._pickle_warning(obj) + return result + + reduce_val = None + + if self.include_properties: + data = self._flatten_properties(obj, data) + + if self.unpicklable: + if has_reduce and not has_reduce_ex: + try: + reduce_val = obj.__reduce__() + except TypeError: + # A lot of builtin types have a reduce which + # just raises a TypeError + # we ignore those + pass + + # test for a reduce implementation, and redirect before + # doing anything else if that is what reduce requests + elif has_reduce_ex: + try: + # we're implementing protocol 2 + reduce_val = obj.__reduce_ex__(2) + except TypeError: + # A lot of builtin types have a reduce which + # just raises a TypeError + # we ignore those + pass + + if reduce_val and isinstance(reduce_val, str): + try: + varpath = iter(reduce_val.split('.')) + # curmod will be transformed by the + # loop into the value to pickle + curmod = sys.modules[next(varpath)] + for modname in varpath: + curmod = getattr(curmod, modname) + # replace obj with value retrieved + return self._flatten(curmod) + except KeyError: + # well, we can't do anything with that, so we ignore it + pass + + elif reduce_val: + # at this point, reduce_val should be some kind of iterable + # pad out to len 5 + rv_as_list = list(reduce_val) + insufficiency = 5 - len(rv_as_list) + if insufficiency: + rv_as_list += [None] * insufficiency + + if getattr(rv_as_list[0], '__name__', '') == '__newobj__': + rv_as_list[0] = tags.NEWOBJ + + f, args, state, listitems, dictitems = rv_as_list + + # check that getstate/setstate is sane + if not ( + state + and has_own_getstate + and not hasattr(obj, '__setstate__') + and not isinstance(obj, dict) + ): + # turn iterators to iterables for convenient serialization + if rv_as_list[3]: + rv_as_list[3] = tuple(rv_as_list[3]) + + if rv_as_list[4]: + rv_as_list[4] = tuple(rv_as_list[4]) + + reduce_args = list(map(self._flatten, rv_as_list)) + last_index = len(reduce_args) - 1 + while last_index >= 2 and reduce_args[last_index] is None: + last_index -= 1 + data[tags.REDUCE] = reduce_args[: last_index + 1] + + return data + + if has_class and not isinstance(obj, types.ModuleType): + if self.unpicklable: + data[tags.OBJECT] = class_name + + if has_getnewargs_ex: + data[tags.NEWARGSEX] = [ + self._flatten(arg) for arg in obj.__getnewargs_ex__() + ] + + if has_getnewargs and not has_getnewargs_ex: + data[tags.NEWARGS] = self._flatten(obj.__getnewargs__()) + + if has_getinitargs: + data[tags.INITARGS] = self._flatten(obj.__getinitargs__()) + + if has_own_getstate: + try: + state = obj.__getstate__() + except TypeError: + # Has getstate but it cannot be called, e.g. file descriptors + # in Python3 + self._pickle_warning(obj) + return None + else: + if state: + return self._getstate(state, data) + + if isinstance(obj, types.ModuleType): + if self.unpicklable: + data[tags.MODULE] = '{name}/{name}'.format(name=obj.__name__) + else: + data = str(obj) + return data + + if util.is_dictionary_subclass(obj): + self._flatten_dict_obj(obj, data, exclude=exclude) + return data + + if util.is_sequence_subclass(obj): + return self._flatten_sequence_obj(obj, data) + + if util.is_iterator(obj): + # force list in python 3 + data[tags.ITERATOR] = list(map(self._flatten, islice(obj, self._max_iter))) + return data + + if has_dict: + # Support objects that subclasses list and set + if util.is_sequence_subclass(obj): + return self._flatten_sequence_obj(obj, data) + + # hack for zope persistent objects; this unghostifies the object + getattr(obj, '_', None) + return self._flatten_dict_obj(obj.__dict__, data, exclude=exclude) + + if has_slots: + return self._flatten_newstyle_with_slots(obj, data) + + # catchall return for data created above without a return + # (e.g. __getnewargs__ is not supposed to be the end of the story) + if data: + return data + + self._pickle_warning(obj) + return None + + def _ref_obj_instance(self, obj): + """Reference an existing object or flatten if new""" + if self.unpicklable: + if self._mkref(obj): + # We've never seen this object so return its + # json representation. + return self._flatten_obj_instance(obj) + # We've seen this object before so place an object + # reference tag in the data. This avoids infinite recursion + # when processing cyclical objects. + return self._getref(obj) + else: + max_reached = self._max_reached() + in_cycle = _in_cycle(obj, self._objs, max_reached, False) + if in_cycle: + # A circular becomes None. + return None + + self._mkref(obj) + return self._flatten_obj_instance(obj) + + def _escape_key(self, k): + return tags.JSON_KEY + encode( + k, + reset=False, + keys=True, + context=self, + backend=self.backend, + make_refs=self.make_refs, + ) + + def _flatten_non_string_key_value_pair(self, k, v, data): + """Flatten only non-string key/value pairs""" + if not util.is_picklable(k, v): + return data + if self.keys and not isinstance(k, str): + k = self._escape_key(k) + data[k] = self._flatten(v) + return data + + def _flatten_string_key_value_pair(self, k, v, data): + """Flatten string key/value pairs only.""" + if not util.is_picklable(k, v): + return data + if self.keys: + if not isinstance(k, str): + return data + elif k.startswith(tags.JSON_KEY): + k = self._escape_key(k) + else: + if k is None: + k = 'null' # for compatibility with common json encoders + + if self.numeric_keys and isinstance(k, (int, float)): + pass + elif not isinstance(k, str): + try: + k = repr(k) + except Exception: + k = str(k) + + data[k] = self._flatten(v) + return data + + def _flatten_dict_obj(self, obj, data=None, exclude=()): + """Recursively call flatten() and return json-friendly dict""" + if data is None: + data = obj.__class__() + + # If we allow non-string keys then we have to do a two-phase + # encoding to ensure that the reference IDs are deterministic. + if self.keys: + # Phase 1: serialize regular objects, ignore fancy keys. + flatten = self._flatten_string_key_value_pair + for k, v in util.items(obj, exclude=exclude): + flatten(k, v, data) + + # Phase 2: serialize non-string keys. + flatten = self._flatten_non_string_key_value_pair + for k, v in util.items(obj, exclude=exclude): + flatten(k, v, data) + else: + # If we have string keys only then we only need a single pass. + flatten = self._flatten_key_value_pair + for k, v in util.items(obj, exclude=exclude): + flatten(k, v, data) + + # the collections.defaultdict protocol + if hasattr(obj, 'default_factory') and callable(obj.default_factory): + factory = obj.default_factory + if util.is_type(factory): + # Reference the class/type + value = _mktyperef(factory) + else: + # The factory is not a type and could reference e.g. functions + # or even the object instance itself, which creates a cycle. + if self._mkref(factory): + # We've never seen this object before so pickle it in-place. + # Create an instance from the factory and assume that the + # resulting instance is a suitable exemplar. + value = self._flatten_obj_instance(handlers.CloneFactory(factory())) + else: + # We've seen this object before. + # Break the cycle by emitting a reference. + value = self._getref(factory) + data['default_factory'] = value + + # Sub-classes of dict + if hasattr(obj, '__dict__') and self.unpicklable and obj != obj.__dict__: + if self._mkref(obj.__dict__): + dict_data = {} + self._flatten_dict_obj(obj.__dict__, dict_data, exclude=exclude) + data['__dict__'] = dict_data + else: + data['__dict__'] = self._getref(obj.__dict__) + + return data + + def _get_flattener(self, obj): + if type(obj) in (list, dict): + if self._mkref(obj): + return ( + self._list_recurse if type(obj) is list else self._flatten_dict_obj + ) + else: + return self._getref + + # We handle tuples and sets by encoding them in a "(tuple|set)dict" + elif type(obj) in (tuple, set): + if not self.unpicklable: + return self._list_recurse + return lambda obj: { + tags.TUPLE if type(obj) is tuple else tags.SET: [ + self._flatten(v) for v in obj + ] + } + + elif util.is_module_function(obj): + return self._flatten_function + + elif util.is_object(obj): + return self._ref_obj_instance + + elif util.is_type(obj): + return _mktyperef + + # instance methods, lambdas, old style classes... + self._pickle_warning(obj) + return None + + def _flatten_sequence_obj(self, obj, data): + """Return a json-friendly dict for a sequence subclass.""" + if hasattr(obj, '__dict__'): + self._flatten_dict_obj(obj.__dict__, data) + value = [self._flatten(v) for v in obj] + if self.unpicklable: + data[tags.SEQ] = value + else: + return value + return data diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/tags.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b346fb88ade61ab88d7fbd1d8a251ff11e30bd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/tags.py @@ -0,0 +1,54 @@ +"""The jsonpickle.tags module provides the custom tags +used for pickling and unpickling Python objects. + +These tags are keys into the flattened dictionaries +created by the Pickler class. The Unpickler uses +these custom key names to identify dictionaries +that need to be specially handled. +""" + +BYTES = 'py/bytes' +B64 = 'py/b64' +B85 = 'py/b85' +FUNCTION = 'py/function' +ID = 'py/id' +INITARGS = 'py/initargs' +ITERATOR = 'py/iterator' +JSON_KEY = 'json://' +MODULE = 'py/mod' +NEWARGS = 'py/newargs' +NEWARGSEX = 'py/newargsex' +NEWOBJ = 'py/newobj' +OBJECT = 'py/object' +PROPERTY = 'py/property' +REDUCE = 'py/reduce' +REF = 'py/ref' +REPR = 'py/repr' +SEQ = 'py/seq' +SET = 'py/set' +STATE = 'py/state' +TUPLE = 'py/tuple' +TYPE = 'py/type' + +# All reserved tag names +RESERVED = { + BYTES, + FUNCTION, + ID, + INITARGS, + ITERATOR, + MODULE, + NEWARGS, + NEWARGSEX, + NEWOBJ, + OBJECT, + PROPERTY, + REDUCE, + REF, + REPR, + SEQ, + SET, + STATE, + TUPLE, + TYPE, +} diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/tags_pd.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/tags_pd.py new file mode 100644 index 0000000000000000000000000000000000000000..6d86c842c42ef68b73a1e928e3ad031450f16212 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/tags_pd.py @@ -0,0 +1,235 @@ +""" +This file exists to automatically generate tags for numpy/pandas extensions. Because numpy/pandas follow a (relatively) rapid release schedule, updating types for new versions as bug reports come in could be infeasible, so we auto-generate them. Unfortunately, this file can't go into the ext folder because then the imports would break. +""" + +import re + +import numpy as np +import pandas as pd +from pandas.api.extensions import ExtensionDtype + + +def split_letters_numbers_brackets(s): + """ + Split the string into letters, numbers, and brackets (with their content). + This is a helper function for getting the smallest unique substring, for determining tags. + """ + # extract brackets and their content + brackets_match = re.search(r"\[.*?\]", s) + if brackets_match: + brackets_part = brackets_match.group() + s_clean = s.replace(brackets_part, "") + else: + brackets_part = "" + s_clean = s + + # find where the trailing digits start + index = len(s_clean) + while index > 0 and s_clean[index - 1].isdigit(): + index -= 1 + letters_part = s_clean[:index] + numbers_part = s_clean[index:] + return letters_part, numbers_part, brackets_part + + +def get_smallest_unique_substrings(strings, prefix="np"): + used_substrings = set() + used_letters_parts = set() + result = {} + + for s in strings: + if not isinstance(s, str): + s2 = s.__name__ + else: + s2 = s + letters_part, numbers_part, brackets_part = split_letters_numbers_brackets(s2) + letters_part = letters_part.lower() + unique_substring_found = False + + # handle the weird datetime64[...] and timedelta64[...] cases + if letters_part == "datetime" and numbers_part == "64" and brackets_part: + substr = "d64" + brackets_part + if substr not in used_substrings: + result[s] = substr + used_substrings.add(substr) + unique_substring_found = True + elif letters_part == "timedelta" and numbers_part == "64" and brackets_part: + substr = "t64" + brackets_part + if substr not in used_substrings: + result[s] = substr + used_substrings.add(substr) + unique_substring_found = True + else: + if letters_part in used_letters_parts: + # letters have been seen before, so use letters + numbers_part + brackets_part + if numbers_part or brackets_part: + # try first letter + numbers_part + brackets_part + substr = letters_part[0] + if numbers_part: + substr += numbers_part + if brackets_part: + substr += brackets_part + if substr not in used_substrings: + result[s] = substr + used_substrings.add(substr) + unique_substring_found = True + else: + # try letters_part + numbers_part + brackets_part + substr = letters_part + if numbers_part: + substr += numbers_part + if brackets_part: + substr += brackets_part + if substr not in used_substrings: + result[s] = substr + used_substrings.add(substr) + unique_substring_found = True + else: + # find a unique substring of just letters_part + for length in range(1, len(letters_part) + 1): + substr = letters_part[:length] + if substr not in used_substrings: + result[s] = substr + used_substrings.add(substr) + unique_substring_found = True + break + else: + # assign the smallest substring of letters_part + for length in range(1, len(letters_part) + 1): + substr = letters_part[:length] + if substr not in used_substrings: + result[s] = substr + used_substrings.add(substr) + unique_substring_found = True + break + used_letters_parts.add(letters_part) + + # last resort: assign the entire string + if not unique_substring_found: + result[s] = s + used_substrings.add(s) + + for key in result: + result[key] = f"{prefix}/" + result[key] + + return result + + +def all_subclasses(cls): + # use a set to avoid adding duplicates + subclasses = set() + for subclass in cls.__subclasses__(): + subclasses.add(subclass) + subclasses.update(all_subclasses(subclass)) + return list(subclasses) + + +def get_all_numpy_dtype_strings(): + dtypes = [] + + # sctypeDict is the dict of all possible numpy dtypes + some invalid dtypes too + for dtype in np.sctypeDict.values(): + try: + dtype_obj = np.dtype(dtype) + dtypes.append(dtype_obj.name.lower()) + except TypeError: + continue + + try: + char_codes = np._typing._char_codes + # datetime64 and timedelta64 are special, they have multiple variants + # python internally compiles and caches regex like this to speed it up + dt_variants = list( + dict.fromkeys( + [ + "datetime64[" + re.search(r"\[(.*?)\]", var).group(1) + "]" + for var in char_codes._DT64Codes.__args__ + if re.search(r"\[(.*?)\]", var) + ] + ) + ) + td_variants = list( + dict.fromkeys( + [ + "timedelta64[" + re.search(r"\[(.*?)\]", var).group(1) + "]" + for var in char_codes._TD64Codes.__args__ + if re.search(r"\[(.*?)\]", var) + ] + ) + ) + except AttributeError: + # AttributeError happens on numpy <1.25 because _typing isn't exposed to users + dt_variants = [ + 'datetime64[Y]', + 'datetime64[M]', + 'datetime64[W]', + 'datetime64[D]', + 'datetime64[h]', + 'datetime64[m]', + 'datetime64[s]', + 'datetime64[ms]', + 'datetime64[us]', + 'datetime64[ns]', + 'datetime64[ps]', + 'datetime64[fs]', + 'datetime64[as]', + ] + td_variants = [ + 'timedelta64[Y]', + 'timedelta64[M]', + 'timedelta64[W]', + 'timedelta64[D]', + 'timedelta64[h]', + 'timedelta64[m]', + 'timedelta64[s]', + 'timedelta64[ms]', + 'timedelta64[us]', + 'timedelta64[ns]', + 'timedelta64[ps]', + 'timedelta64[fs]', + 'timedelta64[as]', + ] + + dtypes += dt_variants + td_variants + + return list(dict.fromkeys(dtypes)) + + +def get_all_pandas_dtype_strings(): + dtypes = [] + + # get all pandas dtypes since it doesnt have a built-in api + extension_dtypes = all_subclasses(ExtensionDtype) + + for dtype_cls in extension_dtypes: + # some ExtensionDtype subclasses might not have a name attribute + if hasattr(dtype_cls, "name"): + try: + dtype_name = dtype_cls.name + dtypes.append(dtype_name.lower()) + except Exception: + continue + + # use the class object for things that np.dtype can't reconstruct + dtypes.extend([pd.Timestamp, pd.Timedelta, pd.Period, pd.Interval]) + + return list(dict.fromkeys(dtypes)) + + +np_dtypes = list( + dict.fromkeys( + [dtype for dtype in get_all_numpy_dtype_strings() if isinstance(dtype, str)] + ) +) + +pd_dtypes = list( + dict.fromkeys( + [dtype for dtype in get_all_pandas_dtype_strings() if isinstance(dtype, str)] + ) +) + + +TYPE_MAP = get_smallest_unique_substrings(np_dtypes, prefix="np") +TYPE_MAP.update(get_smallest_unique_substrings(pd_dtypes, prefix="pd")) + +REVERSE_TYPE_MAP = {v: k for k, v in TYPE_MAP.items()} diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/unpickler.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/unpickler.py new file mode 100644 index 0000000000000000000000000000000000000000..1d07da7df5c1fa80bfc1122c9c52d71e42480ef9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/unpickler.py @@ -0,0 +1,984 @@ +# Copyright (C) 2008 John Paulett (john -at- paulett.org) +# Copyright (C) 2009-2024 David Aguilar (davvid -at- gmail.com) +# All rights reserved. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. +import dataclasses +import sys +import warnings + +from . import errors, handlers, tags, util +from .backend import json + + +def decode( + string, + backend=None, + context=None, + keys=False, + reset=True, + safe=True, + classes=None, + v1_decode=False, + on_missing='ignore', + handle_readonly=False, +): + """Convert a JSON string into a Python object. + + :param backend: If set to an instance of jsonpickle.backend.JSONBackend, jsonpickle + will use that backend for deserialization. + + :param context: Supply a pre-built Pickler or Unpickler object to the + `jsonpickle.encode` and `jsonpickle.decode` machinery instead + of creating a new instance. The `context` represents the currently + active Pickler and Unpickler objects when custom handlers are + invoked by jsonpickle. + + :param keys: If set to True then jsonpickle will decode non-string dictionary keys + into python objects via the jsonpickle protocol. + + :param reset: Custom pickle handlers that use the `Pickler.flatten` method or + `jsonpickle.encode` function must call `encode` with `reset=False` + in order to retain object references during pickling. + This flag is not typically used outside of a custom handler or + `__getstate__` implementation. + + :param safe: If set to ``False``, use of ``eval()`` for backwards-compatible (pre-0.7.0) + deserialization of repr-serialized objects is enabled. Defaults to ``True``. + The default value was ``False`` in jsonpickle v3 and changed to ``True`` in jsonpickle v4. + + .. warning:: + + ``eval()`` is used when set to ``False`` and is not secure against + malicious inputs. You should avoid setting ``safe=False``. + + :param classes: If set to a single class, or a sequence (list, set, tuple) of + classes, then the classes will be made available when constructing objects. + If set to a dictionary of class names to class objects, the class object + will be provided to jsonpickle to deserialize the class name into. + This can be used to give jsonpickle access to local classes that are not + available through the global module import scope, and the dict method can + be used to deserialize encoded objects into a new class. + + :param v1_decode: If set to True it enables you to decode objects serialized in + jsonpickle v1. Please do not attempt to re-encode the objects in the v1 format! + Version 2's format fixes issue #255, and allows dictionary identity to be + preserved through an encode/decode cycle. + + :param on_missing: If set to 'error', it will raise an error if the class it's + decoding is not found. If set to 'warn', it will warn you in said case. + If set to a non-awaitable function, it will call said callback function + with the class name (a string) as the only parameter. Strings passed to + `on_missing` are lowercased automatically. + + :param handle_readonly: If set to True, the Unpickler will handle objects encoded + with 'handle_readonly' properly. Do not set this flag for objects not encoded + with 'handle_readonly' set to True. + + + >>> decode('"my string"') == 'my string' + True + >>> decode('36') + 36 + """ + + if isinstance(on_missing, str): + on_missing = on_missing.lower() + elif not util.is_function(on_missing): + warnings.warn( + "Unpickler.on_missing must be a string or a function! It will be ignored!" + ) + + backend = backend or json + context = context or Unpickler( + keys=keys, + backend=backend, + safe=safe, + v1_decode=v1_decode, + on_missing=on_missing, + handle_readonly=handle_readonly, + ) + data = backend.decode(string) + return context.restore(data, reset=reset, classes=classes) + + +def _safe_hasattr(obj, attr): + """Workaround unreliable hasattr() availability on sqlalchemy objects""" + try: + object.__getattribute__(obj, attr) + return True + except AttributeError: + return False + + +def _is_json_key(key): + """Has this key a special object that has been encoded to JSON?""" + return isinstance(key, str) and key.startswith(tags.JSON_KEY) + + +class _Proxy: + """Proxies are dummy objects that are later replaced by real instances + + The `restore()` function has to solve a tricky problem when pickling + objects with cyclical references -- the parent instance does not yet + exist. + + The problem is that `__getnewargs__()`, `__getstate__()`, custom handlers, + and cyclical objects graphs are allowed to reference the yet-to-be-created + object via the referencing machinery. + + In other words, objects are allowed to depend on themselves for + construction! + + We solve this problem by placing dummy Proxy objects into the referencing + machinery so that we can construct the child objects before constructing + the parent. Objects are initially created with Proxy attribute values + instead of real references. + + We collect all objects that contain references to proxies and run + a final sweep over them to swap in the real instance. This is done + at the very end of the top-level `restore()`. + + The `instance` attribute below is replaced with the real instance + after `__new__()` has been used to construct the object and is used + when swapping proxies with real instances. + + """ + + def __init__(self): + self.instance = None + + def get(self): + return self.instance + + def reset(self, instance): + self.instance = instance + + +class _IDProxy(_Proxy): + def __init__(self, objs, index): + self._index = index + self._objs = objs + + def get(self): + try: + return self._objs[self._index] + except IndexError: + return None + + +def _obj_setattr(obj, attr, proxy): + """Use setattr to update a proxy entry""" + setattr(obj, attr, proxy.get()) + + +def _obj_setvalue(obj, idx, proxy): + """Use obj[key] assignments to update a proxy entry""" + obj[idx] = proxy.get() + + +def loadclass(module_and_name, classes=None): + """Loads the module and returns the class. + + >>> cls = loadclass('datetime.datetime') + >>> cls.__name__ + 'datetime' + + >>> loadclass('does.not.exist') + + >>> loadclass('builtins.int')() + 0 + + """ + # Check if the class exists in a caller-provided scope + if classes: + try: + return classes[module_and_name] + except KeyError: + # maybe they didn't provide a fully qualified path + try: + return classes[module_and_name.rsplit('.', 1)[-1]] + except KeyError: + pass + # Otherwise, load classes from globally-accessible imports + names = module_and_name.split('.') + # First assume that everything up to the last dot is the module name, + # then try other splits to handle classes that are defined within + # classes + for up_to in range(len(names) - 1, 0, -1): + module = util.untranslate_module_name('.'.join(names[:up_to])) + try: + __import__(module) + obj = sys.modules[module] + for class_name in names[up_to:]: + obj = getattr(obj, class_name) + return obj + except (AttributeError, ImportError, ValueError): + continue + # NoneType is a special case and can not be imported/created + if module_and_name == "builtins.NoneType": + return type(None) + return None + + +def has_tag(obj, tag): + """Helper class that tests to see if the obj is a dictionary + and contains a particular key/tag. + + >>> obj = {'test': 1} + >>> has_tag(obj, 'test') + True + >>> has_tag(obj, 'fail') + False + + >>> has_tag(42, 'fail') + False + + """ + return type(obj) is dict and tag in obj + + +def getargs(obj, classes=None): + """Return arguments suitable for __new__()""" + # Let saved newargs take precedence over everything + if has_tag(obj, tags.NEWARGSEX): + raise ValueError('__newargs_ex__ returns both args and kwargs') + + if has_tag(obj, tags.NEWARGS): + return obj[tags.NEWARGS] + + if has_tag(obj, tags.INITARGS): + return obj[tags.INITARGS] + + try: + seq_list = obj[tags.SEQ] + obj_dict = obj[tags.OBJECT] + except KeyError: + return [] + typeref = loadclass(obj_dict, classes=classes) + if not typeref: + return [] + if hasattr(typeref, '_fields'): + if len(typeref._fields) == len(seq_list): + return seq_list + return [] + + +class _trivialclassic: + """ + A trivial class that can be instantiated with no args + """ + + +def make_blank_classic(cls): + """ + Implement the mandated strategy for dealing with classic classes + which cannot be instantiated without __getinitargs__ because they + take parameters + """ + instance = _trivialclassic() + instance.__class__ = cls + return instance + + +def loadrepr(reprstr): + """Returns an instance of the object from the object's repr() string. + It involves the dynamic specification of code. + + .. warning:: + + This function is unsafe and uses `eval()`. + + >>> obj = loadrepr('datetime/datetime.datetime.now()') + >>> obj.__class__.__name__ + 'datetime' + + """ + module, evalstr = reprstr.split('/') + mylocals = locals() + localname = module + if '.' in localname: + localname = module.split('.', 1)[0] + mylocals[localname] = __import__(module) + return eval(evalstr, mylocals) + + +def _loadmodule(module_str): + """Returns a reference to a module. + + >>> fn = _loadmodule('datetime/datetime.datetime.fromtimestamp') + >>> fn.__name__ + 'fromtimestamp' + + """ + module, identifier = module_str.split('/') + try: + result = __import__(module) + except ImportError: + return None + identifier_parts = identifier.split('.') + first_identifier = identifier_parts[0] + if first_identifier != module and not module.startswith(f'{first_identifier}.'): + return None + for name in identifier_parts[1:]: + try: + result = getattr(result, name) + except AttributeError: + return None + return result + + +def has_tag_dict(obj, tag): + """Helper class that tests to see if the obj is a dictionary + and contains a particular key/tag. + + >>> obj = {'test': 1} + >>> has_tag(obj, 'test') + True + >>> has_tag(obj, 'fail') + False + + >>> has_tag(42, 'fail') + False + + """ + return tag in obj + + +def _passthrough(value): + """A function that returns its input as-is""" + return value + + +class Unpickler: + def __init__( + self, + backend=None, + keys=False, + safe=True, + v1_decode=False, + on_missing='ignore', + handle_readonly=False, + ): + self.backend = backend or json + self.keys = keys + self.safe = safe + self.v1_decode = v1_decode + self.on_missing = on_missing + self.handle_readonly = handle_readonly + + self.reset() + + def reset(self): + """Resets the object's internal state.""" + # Map reference names to object instances + self._namedict = {} + + # The stack of names traversed for child objects + self._namestack = [] + + # Map of objects to their index in the _objs list + self._obj_to_idx = {} + self._objs = [] + self._proxies = [] + + # Extra local classes not accessible globally + self._classes = {} + + def _swap_proxies(self): + """Replace proxies with their corresponding instances""" + for obj, attr, proxy, method in self._proxies: + method(obj, attr, proxy) + self._proxies = [] + + def _restore(self, obj, _passthrough=_passthrough): + # if obj isn't in these types, neither it nor nothing in it can have a tag + # don't change the tuple of types to a set, it won't work with isinstance + if not isinstance(obj, (str, list, dict, set, tuple)): + restore = _passthrough + else: + restore = self._restore_tags(obj) + return restore(obj) + + def restore(self, obj, reset=True, classes=None): + """Restores a flattened object to its original python state. + + Simply returns any of the basic builtin types + + >>> u = Unpickler() + >>> u.restore('hello world') == 'hello world' + True + >>> u.restore({'key': 'value'}) == {'key': 'value'} + True + + """ + if reset: + self.reset() + if classes: + self.register_classes(classes) + value = self._restore(obj) + if reset: + self._swap_proxies() + return value + + def register_classes(self, classes): + """Register one or more classes + + :param classes: sequence of classes or a single class to register + + """ + if isinstance(classes, (list, tuple, set)): + for cls in classes: + self.register_classes(cls) + elif isinstance(classes, dict): + self._classes.update( + ( + cls if isinstance(cls, str) else util.importable_name(cls), + handler, + ) + for cls, handler in classes.items() + ) + else: + self._classes[util.importable_name(classes)] = classes + + def _restore_base64(self, obj): + try: + return util.b64decode(obj[tags.B64].encode('utf-8')) + except (AttributeError, UnicodeEncodeError): + return b'' + + def _restore_base85(self, obj): + try: + return util.b85decode(obj[tags.B85].encode('utf-8')) + except (AttributeError, UnicodeEncodeError): + return b'' + + def _refname(self): + """Calculates the name of the current location in the JSON stack. + + This is called as jsonpickle traverses the object structure to + create references to previously-traversed objects. This allows + cyclical data structures such as doubly-linked lists. + jsonpickle ensures that duplicate python references to the same + object results in only a single JSON object definition and + special reference tags to represent each reference. + + >>> u = Unpickler() + >>> u._namestack = [] + >>> u._refname() == '/' + True + >>> u._namestack = ['a'] + >>> u._refname() == '/a' + True + >>> u._namestack = ['a', 'b'] + >>> u._refname() == '/a/b' + True + + """ + return '/' + '/'.join(self._namestack) + + def _mkref(self, obj): + obj_id = id(obj) + try: + _ = self._obj_to_idx[obj_id] + except KeyError: + self._obj_to_idx[obj_id] = len(self._objs) + self._objs.append(obj) + # Backwards compatibility: old versions of jsonpickle + # produced "py/ref" references. + self._namedict[self._refname()] = obj + return obj + + def _restore_list(self, obj): + parent = [] + self._mkref(parent) + children = [self._restore(v) for v in obj] + parent.extend(children) + method = _obj_setvalue + proxies = [ + (parent, idx, value, method) + for idx, value in enumerate(parent) + if isinstance(value, _Proxy) + ] + self._proxies.extend(proxies) + return parent + + def _restore_iterator(self, obj): + try: + return iter(self._restore_list(obj[tags.ITERATOR])) + except TypeError: + return iter([]) + + def _swapref(self, proxy, instance): + proxy_id = id(proxy) + instance_id = id(instance) + + instance_index = self._obj_to_idx[proxy_id] + self._obj_to_idx[instance_id] = instance_index + del self._obj_to_idx[proxy_id] + + self._objs[instance_index] = instance + self._namedict[self._refname()] = instance + + def _restore_reduce(self, obj): + """ + Supports restoring with all elements of __reduce__ as per pep 307. + Assumes that iterator items (the last two) are represented as lists + as per pickler implementation. + """ + proxy = _Proxy() + self._mkref(proxy) + try: + reduce_val = list(map(self._restore, obj[tags.REDUCE])) + except TypeError: + result = [] + proxy.reset(result) + self._swapref(proxy, result) + return result + if len(reduce_val) < 5: + reduce_val.extend([None] * (5 - len(reduce_val))) + f, args, state, listitems, dictitems = reduce_val + + if f == tags.NEWOBJ or getattr(f, '__name__', '') == '__newobj__': + # mandated special case + cls = args[0] + if not isinstance(cls, type): + cls = self._restore(cls) + stage1 = cls.__new__(cls, *args[1:]) + else: + if not callable(f): + result = [] + proxy.reset(result) + self._swapref(proxy, result) + return result + stage1 = f(*args) + + if state: + try: + stage1.__setstate__(state) + except AttributeError: + # it's fine - we'll try the prescribed default methods + try: + # we can't do a straight update here because we + # need object identity of the state dict to be + # preserved so that _swap_proxies works out + for k, v in stage1.__dict__.items(): + state.setdefault(k, v) + stage1.__dict__ = state + except AttributeError: + # next prescribed default + try: + for k, v in state.items(): + setattr(stage1, k, v) + except Exception: + dict_state, slots_state = state + if dict_state: + stage1.__dict__.update(dict_state) + if slots_state: + for k, v in slots_state.items(): + setattr(stage1, k, v) + + if listitems: + # should be lists if not None + try: + stage1.extend(listitems) + except AttributeError: + for x in listitems: + stage1.append(x) + + if dictitems: + for k, v in dictitems: + stage1.__setitem__(k, v) + + proxy.reset(stage1) + self._swapref(proxy, stage1) + return stage1 + + def _restore_id(self, obj): + try: + idx = obj[tags.ID] + return self._objs[idx] + except IndexError: + return _IDProxy(self._objs, idx) + except TypeError: + return None + + def _restore_type(self, obj): + typeref = loadclass(obj[tags.TYPE], classes=self._classes) + if typeref is None: + return obj + return typeref + + def _restore_module(self, obj): + obj = _loadmodule(obj[tags.MODULE]) + return self._mkref(obj) + + def _restore_repr_safe(self, obj): + obj = _loadmodule(obj[tags.REPR]) + return self._mkref(obj) + + def _restore_repr(self, obj): + obj = loadrepr(obj[tags.REPR]) + return self._mkref(obj) + + def _loadfactory(self, obj): + try: + default_factory = obj['default_factory'] + except KeyError: + return None + del obj['default_factory'] + return self._restore(default_factory) + + def _process_missing(self, class_name): + # most common case comes first + if self.on_missing == 'ignore': + pass + elif self.on_missing == 'warn': + warnings.warn('Unpickler._restore_object could not find %s!' % class_name) + elif self.on_missing == 'error': + raise errors.ClassNotFoundError( + 'Unpickler.restore_object could not find %s!' % class_name + ) + elif util.is_function(self.on_missing): + self.on_missing(class_name) + + def _restore_pickled_key(self, key): + """Restore a possibly pickled key""" + if _is_json_key(key): + key = decode( + key[len(tags.JSON_KEY) :], + backend=self.backend, + context=self, + keys=True, + reset=False, + ) + return key + + def _restore_key_fn(self, _passthrough=_passthrough): + """Return a callable that restores keys + + This function is responsible for restoring non-string keys + when we are decoding with `keys=True`. + + """ + # This function is called before entering a tight loop + # where the returned function will be called. + # We return a specific function after checking self.keys + # instead of doing so in the body of the function to + # avoid conditional branching inside a tight loop. + if self.keys: + restore_key = self._restore_pickled_key + else: + restore_key = _passthrough + return restore_key + + def _restore_from_dict( + self, obj, instance, ignorereserved=True, restore_dict_items=True + ): + restore_key = self._restore_key_fn() + method = _obj_setattr + deferred = {} + + for k, v in util.items(obj): + # ignore the reserved attribute + if ignorereserved and k in tags.RESERVED: + continue + if isinstance(k, (int, float)): + str_k = k.__str__() + else: + str_k = k + self._namestack.append(str_k) + if restore_dict_items: + k = restore_key(k) + # step into the namespace + value = self._restore(v) + else: + value = v + if util.is_noncomplex(instance) or util.is_dictionary_subclass(instance): + try: + if k == '__dict__': + setattr(instance, k, value) + else: + instance[k] = value + except TypeError: + # Immutable object, must be constructed in one shot + if k != '__dict__': + deferred[k] = value + self._namestack.pop() + continue + else: + if not k.startswith('__'): + try: + setattr(instance, k, value) + except KeyError: + # certain numpy objects require us to prepend a _ to the var + # this should go in the np handler but I think this could be + # useful for other code + setattr(instance, f'_{k}', value) + except dataclasses.FrozenInstanceError: + # issue #240 + # i think this is the only way to set frozen dataclass attrs + object.__setattr__(instance, k, value) + except AttributeError as e: + # some objects raise this for read-only attributes (#422) (#478) + if ( + hasattr(instance, '__slots__') + and not len(instance.__slots__) + # we have to handle this separately because of +483 + and issubclass(instance.__class__, (int, str)) + and self.handle_readonly + ): + continue + raise e + else: + setattr(instance, f'_{instance.__class__.__name__}{k}', value) + + # This instance has an instance variable named `k` that is + # currently a proxy and must be replaced + if isinstance(value, _Proxy): + self._proxies.append((instance, k, value, method)) + + # step out + self._namestack.pop() + + if deferred: + # SQLAlchemy Immutable mappings must be constructed in one shot + instance = instance.__class__(deferred) + + return instance + + def _restore_state(self, obj, instance): + state = self._restore(obj[tags.STATE]) + has_slots = ( + isinstance(state, tuple) and len(state) == 2 and isinstance(state[1], dict) + ) + has_slots_and_dict = has_slots and isinstance(state[0], dict) + if hasattr(instance, '__setstate__'): + instance.__setstate__(state) + elif isinstance(state, dict): + # implements described default handling + # of state for object with instance dict + # and no slots + instance = self._restore_from_dict( + state, instance, ignorereserved=False, restore_dict_items=False + ) + elif has_slots: + instance = self._restore_from_dict( + state[1], instance, ignorereserved=False, restore_dict_items=False + ) + if has_slots_and_dict: + instance = self._restore_from_dict( + state[0], instance, ignorereserved=False, restore_dict_items=False + ) + elif not hasattr(instance, '__getnewargs__') and not hasattr( + instance, '__getnewargs_ex__' + ): + # __setstate__ is not implemented so that means that the best + # we can do is return the result of __getstate__() rather than + # return an empty shell of an object. + # However, if there were newargs, it's not an empty shell + instance = state + return instance + + def _restore_object_instance_variables(self, obj, instance): + instance = self._restore_from_dict(obj, instance) + + # Handle list and set subclasses + if has_tag(obj, tags.SEQ): + if hasattr(instance, 'append'): + for v in obj[tags.SEQ]: + instance.append(self._restore(v)) + elif hasattr(instance, 'add'): + for v in obj[tags.SEQ]: + instance.add(self._restore(v)) + + if has_tag(obj, tags.STATE): + instance = self._restore_state(obj, instance) + + return instance + + def _restore_object_instance(self, obj, cls, class_name=''): + # This is a placeholder proxy object which allows child objects to + # reference the parent object before it has been instantiated. + proxy = _Proxy() + self._mkref(proxy) + + # An object can install itself as its own factory, so load the factory + # after the instance is available for referencing. + factory = self._loadfactory(obj) + + if has_tag(obj, tags.NEWARGSEX): + args, kwargs = obj[tags.NEWARGSEX] + else: + args = getargs(obj, classes=self._classes) + kwargs = {} + if args: + args = self._restore(args) + if kwargs: + kwargs = self._restore(kwargs) + + is_oldstyle = not (isinstance(cls, type) or getattr(cls, '__meta__', None)) + try: + if not is_oldstyle and hasattr(cls, '__new__'): + # new style classes + if factory: + instance = cls.__new__(cls, factory, *args, **kwargs) + instance.default_factory = factory + else: + instance = cls.__new__(cls, *args, **kwargs) + else: + instance = object.__new__(cls) + except TypeError: # old-style classes + is_oldstyle = True + + if is_oldstyle: + try: + instance = cls(*args) + except TypeError: # fail gracefully + try: + instance = make_blank_classic(cls) + except Exception: # fail gracefully + self._process_missing(class_name) + return self._mkref(obj) + + proxy.reset(instance) + self._swapref(proxy, instance) + + if isinstance(instance, tuple): + return instance + + instance = self._restore_object_instance_variables(obj, instance) + + if _safe_hasattr(instance, 'default_factory') and isinstance( + instance.default_factory, _Proxy + ): + instance.default_factory = instance.default_factory.get() + + return instance + + def _restore_object(self, obj): + class_name = obj[tags.OBJECT] + cls = loadclass(class_name, classes=self._classes) + handler = handlers.get(cls, handlers.get(class_name)) + if handler is not None: # custom handler + proxy = _Proxy() + self._mkref(proxy) + instance = handler(self).restore(obj) + proxy.reset(instance) + self._swapref(proxy, instance) + return instance + + if cls is None: + self._process_missing(class_name) + return self._mkref(obj) + + return self._restore_object_instance(obj, cls, class_name) + + def _restore_function(self, obj): + return loadclass(obj[tags.FUNCTION], classes=self._classes) + + def _restore_set(self, obj): + try: + return {self._restore(v) for v in obj[tags.SET]} + except TypeError: + return set() + + def _restore_dict(self, obj): + data = {} + if not self.v1_decode: + self._mkref(data) + + # If we are decoding dicts that can have non-string keys then we + # need to do a two-phase decode where the non-string keys are + # processed last. This ensures a deterministic order when + # assigning object IDs for references. + if self.keys: + # Phase 1: regular non-special keys. + for k, v in util.items(obj): + if _is_json_key(k): + continue + if isinstance(k, (int, float)): + str_k = k.__str__() + else: + str_k = k + self._namestack.append(str_k) + data[k] = self._restore(v) + + self._namestack.pop() + + # Phase 2: object keys only. + for k, v in util.items(obj): + if not _is_json_key(k): + continue + self._namestack.append(k) + + k = self._restore_pickled_key(k) + data[k] = result = self._restore(v) + # k is currently a proxy and must be replaced + if isinstance(result, _Proxy): + self._proxies.append((data, k, result, _obj_setvalue)) + + self._namestack.pop() + else: + # No special keys, thus we don't need to restore the keys either. + for k, v in util.items(obj): + if isinstance(k, (int, float)): + str_k = k.__str__() + else: + str_k = k + self._namestack.append(str_k) + data[k] = result = self._restore(v) + if isinstance(result, _Proxy): + self._proxies.append((data, k, result, _obj_setvalue)) + self._namestack.pop() + return data + + def _restore_tuple(self, obj): + try: + return tuple(self._restore(v) for v in obj[tags.TUPLE]) + except TypeError: + return () + + def _restore_tags(self, obj, _passthrough=_passthrough): + """Return the restoration function for the specified object""" + try: + if not tags.RESERVED <= set(obj) and type(obj) not in (list, dict): + return _passthrough + except TypeError: + pass + if type(obj) is dict: + if tags.TUPLE in obj: + restore = self._restore_tuple + elif tags.SET in obj: + restore = self._restore_set + elif tags.B64 in obj: + restore = self._restore_base64 + elif tags.B85 in obj: + restore = self._restore_base85 + elif tags.ID in obj: + restore = self._restore_id + elif tags.ITERATOR in obj: + restore = self._restore_iterator + elif tags.OBJECT in obj: + restore = self._restore_object + elif tags.TYPE in obj: + restore = self._restore_type + elif tags.REDUCE in obj: + restore = self._restore_reduce + elif tags.FUNCTION in obj: + restore = self._restore_function + elif tags.MODULE in obj: + restore = self._restore_module + elif tags.REPR in obj: + if self.safe: + restore = self._restore_repr_safe + else: + restore = self._restore_repr + else: + restore = self._restore_dict + elif type(obj) is list: + restore = self._restore_list + else: + restore = _passthrough + return restore diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/util.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/util.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ab49e065c7644f9f8bee8b615ec100c1672a35 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/util.py @@ -0,0 +1,629 @@ +# Copyright (C) 2008 John Paulett (john -at- paulett.org) +# Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com) +# All rights reserved. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. + +"""Helper functions for pickling and unpickling. Most functions assist in +determining the type of an object. +""" +import base64 +import binascii +import collections +import inspect +import io +import operator +import sys +import time +import types +import warnings +from collections.abc import Iterator as abc_iterator + +from . import tags + +_ITERATOR_TYPE = type(iter('')) +SEQUENCES = (list, set, tuple) +SEQUENCES_SET = {list, set, tuple} +PRIMITIVES = {str, bool, int, float, type(None)} +FUNCTION_TYPES = { + types.FunctionType, + types.MethodType, + types.LambdaType, + types.BuiltinFunctionType, + types.BuiltinMethodType, +} +NON_REDUCIBLE_TYPES = ( + { + list, + dict, + set, + tuple, + object, + bytes, + } + | PRIMITIVES + | FUNCTION_TYPES +) +NON_CLASS_TYPES = { + list, + dict, + set, + tuple, + bytes, +} | PRIMITIVES + + +def is_type(obj): + """Returns True is obj is a reference to a type. + + >>> is_type(1) + False + + >>> is_type(object) + True + + >>> class Klass: pass + >>> is_type(Klass) + True + """ + # use "isinstance" and not "is" to allow for metaclasses + return isinstance(obj, type) + + +def has_method(obj, name): + # false if attribute doesn't exist + if not hasattr(obj, name): + return False + func = getattr(obj, name) + + # builtin descriptors like __getnewargs__ + if isinstance(func, types.BuiltinMethodType): + return True + + # note that FunctionType has a different meaning in py2/py3 + if not isinstance(func, (types.MethodType, types.FunctionType)): + return False + + # need to go through __dict__'s since in py3 + # methods are essentially descriptors + + # __class__ for old-style classes + base_type = obj if is_type(obj) else obj.__class__ + original = None + # there is no .mro() for old-style classes + for subtype in inspect.getmro(base_type): + original = vars(subtype).get(name) + if original is not None: + break + + # name not found in the mro + if original is None: + return False + + # static methods are always fine + if isinstance(original, staticmethod): + return True + + # at this point, the method has to be an instancemthod or a classmethod + if not hasattr(func, '__self__'): + return False + bound_to = getattr(func, '__self__') + + # class methods + if isinstance(original, classmethod): + return issubclass(base_type, bound_to) + + # bound methods + return isinstance(obj, type(bound_to)) + + +def is_object(obj): + """Returns True is obj is a reference to an object instance. + + >>> is_object(1) + True + + >>> is_object(object()) + True + + >>> is_object(lambda x: 1) + False + """ + return isinstance(obj, object) and not isinstance( + obj, (type, types.FunctionType, types.BuiltinFunctionType) + ) + + +def is_not_class(obj): + """Determines if the object is not a class or a class instance. + Used for serializing properties. + """ + return type(obj) in NON_CLASS_TYPES + + +def is_primitive(obj): + """Helper method to see if the object is a basic data type. Unicode strings, + integers, longs, floats, booleans, and None are considered primitive + and will return True when passed into *is_primitive()* + + >>> is_primitive(3) + True + >>> is_primitive([4,4]) + False + """ + return type(obj) in PRIMITIVES + + +def is_enum(obj): + """Is the object an enum?""" + return 'enum' in sys.modules and isinstance(obj, sys.modules['enum'].Enum) + + +def is_dictionary(obj): + """Helper method for testing if the object is a dictionary. + + >>> is_dictionary({'key':'value'}) + True + + """ + warnings.warn( + "This function will be removed in the next release of jsonpickle, 5.0.0! Please migrate now.", + DeprecationWarning, + ) + return type(obj) is dict + + +def is_sequence(obj): + """Helper method to see if the object is a sequence (list, set, or tuple). + + >>> is_sequence([4]) + True + + """ + return type(obj) in SEQUENCES_SET + + +def is_list(obj): + """Helper method to see if the object is a Python list. + + >>> is_list([4]) + True + """ + warnings.warn( + "This function will be removed in the next release of jsonpickle, 5.0.0! Please migrate now.", + DeprecationWarning, + ) + return type(obj) is list + + +def is_set(obj): + """Helper method to see if the object is a Python set. + + >>> is_set(set()) + True + """ + warnings.warn( + "This function will be removed in the next release of jsonpickle, 5.0.0! Please migrate now.", + DeprecationWarning, + ) + return type(obj) is set + + +def is_bytes(obj): + """Helper method to see if the object is a bytestring. + + >>> is_bytes(b'foo') + True + """ + warnings.warn( + "This function will be removed in the next release of jsonpickle, 5.0.0! Please migrate now.", + DeprecationWarning, + ) + return type(obj) is bytes + + +def is_unicode(obj): + """DEPRECATED: Helper method to see if the object is a unicode string""" + warnings.warn( + "This function will be removed in the next release of jsonpickle, 5.0.0! Please migrate now.", + DeprecationWarning, + ) + return type(obj) is str + + +def is_tuple(obj): + """Helper method to see if the object is a Python tuple. + + >>> is_tuple((1,)) + True + """ + warnings.warn( + "This function will be removed in the next release of jsonpickle, 5.0.0! Please migrate now.", + DeprecationWarning, + ) + return type(obj) is tuple + + +def is_dictionary_subclass(obj): + """Returns True if *obj* is a subclass of the dict type. *obj* must be + a subclass and not the actual builtin dict. + + >>> class Temp(dict): pass + >>> is_dictionary_subclass(Temp()) + True + """ + # TODO: add UserDict + return ( + hasattr(obj, '__class__') + and issubclass(obj.__class__, dict) + and type(obj) is not dict + ) + + +def is_sequence_subclass(obj): + """Returns True if *obj* is a subclass of list, set or tuple. + + *obj* must be a subclass and not the actual builtin, such + as list, set, tuple, etc.. + + >>> class Temp(list): pass + >>> is_sequence_subclass(Temp()) + True + """ + return ( + hasattr(obj, '__class__') + and issubclass(obj.__class__, SEQUENCES) + and not is_sequence(obj) + ) + + +def is_noncomplex(obj): + """Returns True if *obj* is a special (weird) class, that is more complex + than primitive data types, but is not a full object. Including: + + * :class:`~time.struct_time` + """ + if type(obj) is time.struct_time: + return True + return False + + +def is_function(obj): + """Returns true if passed a function + + >>> is_function(lambda x: 1) + True + + >>> is_function(locals) + True + + >>> def method(): pass + >>> is_function(method) + True + + >>> is_function(1) + False + """ + return type(obj) in FUNCTION_TYPES + + +def is_module_function(obj): + """Return True if `obj` is a module-global function + + >>> import os + >>> is_module_function(os.path.exists) + True + + >>> is_module_function(lambda: None) + False + + """ + + return ( + hasattr(obj, '__class__') + and isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)) + and hasattr(obj, '__module__') + and hasattr(obj, '__name__') + and obj.__name__ != '' + ) or is_cython_function(obj) + + +def is_module(obj): + """Returns True if passed a module + + >>> import os + >>> is_module(os) + True + + """ + warnings.warn( + "This function will be removed in the next release of jsonpickle, 5.0.0! Please migrate now.", + DeprecationWarning, + ) + return isinstance(obj, types.ModuleType) + + +def is_picklable(name, value): + """Return True if an object can be pickled + + >>> import os + >>> is_picklable('os', os) + True + + >>> def foo(): pass + >>> is_picklable('foo', foo) + True + + >>> is_picklable('foo', lambda: None) + False + + """ + if name in tags.RESERVED: + return False + return is_module_function(value) or not is_function(value) + + +def is_installed(module): + """Tests to see if ``module`` is available on the sys.path + + >>> is_installed('sys') + True + >>> is_installed('hopefullythisisnotarealmodule') + False + + """ + try: + __import__(module) + return True + except ImportError: + return False + + +def is_list_like(obj): + return hasattr(obj, '__getitem__') and hasattr(obj, 'append') + + +def is_iterator(obj): + return isinstance(obj, abc_iterator) and not isinstance(obj, io.IOBase) + + +def is_collections(obj): + try: + return type(obj).__module__ == 'collections' + except Exception: + return False + + +def is_reducible_sequence_subclass(obj): + return hasattr(obj, '__class__') and issubclass(obj.__class__, SEQUENCES) + + +def is_reducible(obj): + """ + Returns false if of a type which have special casing, + and should not have their __reduce__ methods used + """ + # defaultdicts may contain functions which we cannot serialise + if is_collections(obj) and not isinstance(obj, collections.defaultdict): + return True + if ( + type(obj) in NON_REDUCIBLE_TYPES + or obj is object + or is_dictionary_subclass(obj) + or isinstance(obj, types.ModuleType) + or is_reducible_sequence_subclass(obj) + or is_list_like(obj) + or isinstance(getattr(obj, '__slots__', None), _ITERATOR_TYPE) + or (is_type(obj) and obj.__module__ == 'datetime') + ): + return False + return True + + +def is_cython_function(obj): + """Returns true if the object is a reference to a Cython function""" + return ( + callable(obj) + and hasattr(obj, '__repr__') + and repr(obj).startswith('>> class Example(object): + ... pass + + >>> ex = Example() + >>> importable_name(ex.__class__) == 'jsonpickle.util.Example' + True + >>> importable_name(type(25)) == 'builtins.int' + True + >>> importable_name(None.__class__) == 'builtins.NoneType' + True + >>> importable_name(False.__class__) == 'builtins.bool' + True + >>> importable_name(AttributeError) == 'builtins.AttributeError' + True + + """ + # Use the fully-qualified name if available (Python >= 3.3) + name = getattr(cls, '__qualname__', cls.__name__) + module = translate_module_name(cls.__module__) + if not module: + if hasattr(cls, '__self__'): + if hasattr(cls.__self__, '__module__'): + module = cls.__self__.__module__ + else: + module = cls.__self__.__class__.__module__ + return f'{module}.{name}' + + +def b64encode(data): + """ + Encode binary data to ascii text in base64. Data must be bytes. + """ + return base64.b64encode(data).decode('ascii') + + +def b64decode(payload): + """ + Decode payload - must be ascii text. + """ + try: + return base64.b64decode(payload) + except (TypeError, binascii.Error): + return b'' + + +def b85encode(data): + """ + Encode binary data to ascii text in base85. Data must be bytes. + """ + return base64.b85encode(data).decode('ascii') + + +def b85decode(payload): + """ + Decode payload - must be ascii text. + """ + try: + return base64.b85decode(payload) + except (TypeError, ValueError): + return b'' + + +def itemgetter(obj, getter=operator.itemgetter(0)): + return str(getter(obj)) + + +def items(obj, exclude=()): + """ + This can't be easily replaced by dict.items() because this has the exclude parameter. + Keep it for now. + """ + for k, v in obj.items(): + if k in exclude: + continue + yield k, v diff --git a/.venv_haddock/lib/python3.12/site-packages/jsonpickle/version.py b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/version.py new file mode 100644 index 0000000000000000000000000000000000000000..e1420cf12132a4b7b52e8d740049b7106248456f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/jsonpickle/version.py @@ -0,0 +1,16 @@ +try: + from importlib import metadata +except (ImportError, OSError): + metadata = None + + +def _get_version(): + default_version = '0.0.0-alpha' + try: + version = metadata.version('jsonpickle') + except (AttributeError, ImportError, OSError): + version = default_version + return version + + +__version__ = _get_version() diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/__init__.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c945febe0249a6f15ba2b1d74ffe6558f8c6c7db --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/__init__.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import typing as _t + +from narwhals import dependencies, dtypes, exceptions, selectors +from narwhals._utils import ( + Implementation, + generate_temporary_column_name, + is_ordered_categorical, + maybe_align_index, + maybe_convert_dtypes, + maybe_get_index, + maybe_reset_index, + maybe_set_index, +) +from narwhals.dataframe import DataFrame, LazyFrame +from narwhals.dtypes import ( + Array, + Binary, + Boolean, + Categorical, + Date, + Datetime, + Decimal, + Duration, + Enum, + Field, + Float32, + Float64, + Int8, + Int16, + Int32, + Int64, + Int128, + List, + Object, + String, + Struct, + Time, + UInt8, + UInt16, + UInt32, + UInt64, + UInt128, + Unknown, +) +from narwhals.expr import Expr +from narwhals.functions import ( + all_ as all, + all_horizontal, + any_horizontal, + coalesce, + col, + concat, + concat_str, + corr, + exclude, + format, + from_arrow, + from_dict, + from_dicts, + from_numpy, + len_ as len, + lit, + max, + max_horizontal, + mean, + mean_horizontal, + median, + min, + min_horizontal, + new_series, + nth, + read_csv, + read_parquet, + scan_csv, + scan_parquet, + show_versions, + sum, + sum_horizontal, + when, +) +from narwhals.schema import Schema +from narwhals.series import Series +from narwhals.translate import ( + from_native, + get_native_namespace, + narwhalify, + to_native, + to_py_scalar, +) + +__version__: str + +__all__ = [ + "Array", + "Binary", + "Boolean", + "Categorical", + "DataFrame", + "Date", + "Datetime", + "Decimal", + "Duration", + "Enum", + "Expr", + "Field", + "Float32", + "Float64", + "Implementation", + "Int8", + "Int16", + "Int32", + "Int64", + "Int128", + "LazyFrame", + "List", + "Object", + "Schema", + "Series", + "String", + "Struct", + "Time", + "UInt8", + "UInt16", + "UInt32", + "UInt64", + "UInt128", + "Unknown", + "all", + "all_horizontal", + "any_horizontal", + "coalesce", + "col", + "concat", + "concat_str", + "corr", + "dependencies", + "dtypes", + "exceptions", + "exclude", + "format", + "from_arrow", + "from_dict", + "from_dicts", + "from_native", + "from_numpy", + "generate_temporary_column_name", + "get_native_namespace", + "is_ordered_categorical", + "len", + "lit", + "max", + "max_horizontal", + "maybe_align_index", + "maybe_convert_dtypes", + "maybe_get_index", + "maybe_reset_index", + "maybe_set_index", + "mean", + "mean_horizontal", + "median", + "min", + "min_horizontal", + "narwhalify", + "new_series", + "nth", + "read_csv", + "read_parquet", + "scan_csv", + "scan_parquet", + "selectors", + "show_versions", + "sum", + "sum_horizontal", + "to_native", + "to_py_scalar", + "when", +] + + +if not _t.TYPE_CHECKING: + + def __getattr__(name: str) -> _t.Any: + if name == "__version__": + global __version__ # noqa: PLW0603 + + from importlib import metadata + + __version__ = metadata.version(__name__) + return __version__ + msg = f"module {__name__!r} has no attribute {name!r}" + raise AttributeError(msg) +else: # pragma: no cover + ... diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_constants.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..91032edb26499863001111b0b8582fb749d21762 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_constants.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import datetime as dt + +# Temporal (from `polars._utils.constants`) +SECONDS_PER_DAY = 86_400 +SECONDS_PER_MINUTE = 60 +NS_PER_MINUTE = 60_000_000_000 +"""Nanoseconds (`[ns]`) per minute.""" +US_PER_MINUTE = 60_000_000 +"""Microseconds (`[μs]`) per minute.""" +MS_PER_MINUTE = 60_000 +"""Milliseconds (`[ms]`) per minute.""" +NS_PER_SECOND = 1_000_000_000 +"""Nanoseconds (`[ns]`) per second (`[s]`).""" +US_PER_SECOND = 1_000_000 +"""Microseconds (`[μs]`) per second (`[s]`).""" +MS_PER_SECOND = 1_000 +"""Milliseconds (`[ms]`) per second (`[s]`).""" +NS_PER_MICROSECOND = 1_000 +"""Nanoseconds (`[ns]`) per microsecond (`[μs]`).""" +NS_PER_MILLISECOND = 1_000_000 +"""Nanoseconds (`[ns]`) per millisecond (`[ms]`). + +From [polars](https://github.com/pola-rs/polars/blob/2c7a3e77f0faa37c86a3745db4ef7707ae50c72e/crates/polars-time/src/chunkedarray/duration.rs#L7). +""" +EPOCH_YEAR = 1970 +"""See [Unix time](https://en.wikipedia.org/wiki/Unix_time).""" +EPOCH = dt.datetime(EPOCH_YEAR, 1, 1).replace(tzinfo=None) +"""See [Unix time](https://en.wikipedia.org/wiki/Unix_time).""" diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_duration.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_duration.py new file mode 100644 index 0000000000000000000000000000000000000000..8e678be7ff284e78fe0c65725c7b9e1e16a75dbe --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_duration.py @@ -0,0 +1,94 @@ +"""Tools for working with the Polars duration string language.""" + +from __future__ import annotations + +import datetime as dt +import re +from typing import TYPE_CHECKING, Literal, cast, get_args + +if TYPE_CHECKING: + from collections.abc import Container, Mapping + + from typing_extensions import TypeAlias + +__all__ = ["IntervalUnit"] + +IntervalUnit: TypeAlias = Literal["ns", "us", "ms", "s", "m", "h", "d", "mo", "q", "y"] +"""A Polars duration string interval unit. + +- 'ns': nanosecond. +- 'us': microsecond. +- 'ms': millisecond. +- 's': second. +- 'm': minute. +- 'h': hour. +- 'd': day. +- 'mo': month. +- 'q': quarter. +- 'y': year. +""" +TimedeltaKwd: TypeAlias = Literal[ + "days", "hours", "minutes", "seconds", "milliseconds", "microseconds" +] + +PATTERN_INTERVAL: re.Pattern[str] = re.compile( + r"^(?P-?\d+)(?Pns|us|ms|mo|m|s|h|d|q|y)\Z" +) +MONTH_MULTIPLES = frozenset([1, 2, 3, 4, 6, 12]) +QUARTER_MULTIPLES = frozenset([1, 2, 4]) +UNIT_TO_TIMEDELTA: Mapping[IntervalUnit, TimedeltaKwd] = { + "d": "days", + "h": "hours", + "m": "minutes", + "s": "seconds", + "ms": "milliseconds", + "us": "microseconds", +} + + +class Interval: + def __init__(self, multiple: int, unit: IntervalUnit, /) -> None: + self.multiple: int = multiple + self.unit: IntervalUnit = unit + + def to_timedelta( + self, *, unsupported: Container[IntervalUnit] = frozenset(("ns", "mo", "q", "y")) + ) -> dt.timedelta: + if self.unit in unsupported: # pragma: no cover + msg = f"Creating timedelta with {self.unit} unit is not supported." + raise NotImplementedError(msg) + kwd = UNIT_TO_TIMEDELTA[self.unit] + # error: Keywords must be strings (bad mypy) + return dt.timedelta(**{kwd: self.multiple}) # type: ignore[misc] + + @classmethod + def parse(cls, every: str) -> Interval: + multiple, unit = cls._parse(every) + if unit == "mo" and multiple not in MONTH_MULTIPLES: + msg = f"Only the following multiples are supported for 'mo' unit: {MONTH_MULTIPLES}.\nGot: {multiple}." + raise ValueError(msg) + if unit == "q" and multiple not in QUARTER_MULTIPLES: + msg = f"Only the following multiples are supported for 'q' unit: {QUARTER_MULTIPLES}.\nGot: {multiple}." + raise ValueError(msg) + if unit == "y" and multiple != 1: + msg = ( + f"Only multiple 1 is currently supported for 'y' unit.\nGot: {multiple}." + ) + raise ValueError(msg) + return cls(multiple, unit) + + @classmethod + def parse_no_constraints(cls, every: str) -> Interval: + return cls(*cls._parse(every)) + + @staticmethod + def _parse(every: str) -> tuple[int, IntervalUnit]: + if match := PATTERN_INTERVAL.match(every): + multiple = int(match["multiple"]) + unit = cast("IntervalUnit", match["unit"]) + return multiple, unit + msg = ( + f"Invalid `every` string: {every}. Expected string of kind , " + f"where 'unit' is one of: {get_args(IntervalUnit)}." + ) + raise ValueError(msg) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_enum.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..ed20dd066aabb6edc0c0a7c1d16736a59d2056fc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_enum.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +# ruff: noqa: ARG004 +from enum import Enum +from typing import Any + + +class NoAutoEnum(Enum): + """Enum base class that prohibits the use of enum.auto() for value assignment. + + This behavior is achieved by overriding the value generation mechanism. + + Examples: + >>> from enum import auto + >>> + >>> class Colors(NoAutoEnum): + ... RED = 1 + ... GREEN = 2 + >>> Colors.RED + + + >>> class ColorsWithAuto(NoAutoEnum): + ... RED = 1 + ... GREEN = auto() + Traceback (most recent call last): + ... + ValueError: Creating values with `auto()` is not allowed. Please provide a value manually instead. + + Raises: + ValueError: If `auto()` is attempted to be used for any enum member value. + """ + + @staticmethod + def _generate_next_value_( + name: str, start: int, count: int, last_values: list[Any] + ) -> Any: + msg = "Creating values with `auto()` is not allowed. Please provide a value manually instead." + raise ValueError(msg) + + +__all__ = ["NoAutoEnum"] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_exceptions.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb91c125ef6f47cc00389df8d5ad15f5fadb3fc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_exceptions.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from warnings import warn + + +def find_stacklevel() -> int: + """Find the first place in the stack that is not inside narwhals. + + Taken from: + https://github.com/pandas-dev/pandas/blob/ab89c53f48df67709a533b6a95ce3d911871a0a8/pandas/util/_exceptions.py#L30-L51 + """ + import inspect + from pathlib import Path + + import narwhals as nw + + pkg_dir = str(Path(nw.__file__).parent) + + # https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow + frame = inspect.currentframe() + n = 0 + try: + while frame: + fname = inspect.getfile(frame) + if fname.startswith(pkg_dir) or ( + (qualname := getattr(frame.f_code, "co_qualname", None)) + # ignore @singledispatch wrappers + and qualname.startswith("singledispatch.") + ): + frame = frame.f_back + n += 1 + else: # pragma: no cover + break + else: # pragma: no cover + pass + finally: + # https://docs.python.org/3/library/inspect.html + # > Though the cycle detector will catch these, destruction of the frames + # > (and local variables) can be made deterministic by removing the cycle + # > in a finally clause. + del frame + return n + + +def issue_deprecation_warning(message: str, _version: str) -> None: # pragma: no cover + """Issue a deprecation warning. + + Arguments: + message: The message associated with the warning. + _version: Narwhals version when the warning was introduced. Just used for internal + bookkeeping. + """ + warn(message=message, category=DeprecationWarning, stacklevel=find_stacklevel()) + + +def issue_warning(message: str, category: type[Warning]) -> None: + warn(message=message, category=category, stacklevel=find_stacklevel()) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_expression_parsing.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_expression_parsing.py new file mode 100644 index 0000000000000000000000000000000000000000..9e964dbfdd1d50862bbb0c6e462a092698379b5e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_expression_parsing.py @@ -0,0 +1,919 @@ +# Utilities for expression parsing +# Useful for backends which don't have any concept of expressions, such +# and pandas or PyArrow. +# ! Any change to this module will trigger the pyspark and pyspark-connect tests in CI +from __future__ import annotations + +from enum import Enum, auto +from typing import TYPE_CHECKING, Any, Callable, Literal, cast + +from narwhals._utils import zip_strict +from narwhals.dependencies import is_numpy_array_1d +from narwhals.exceptions import ( + InvalidIntoExprError, + InvalidOperationError, + MultiOutputExpressionError, +) + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + + from typing_extensions import Never, TypeIs + + from narwhals._compliant import CompliantExpr, CompliantFrameT + from narwhals._compliant.typing import ( + AliasNames, + CompliantExprAny, + CompliantFrameAny, + CompliantNamespaceAny, + EvalNames, + ) + from narwhals.expr import Expr + from narwhals.series import Series + from narwhals.typing import IntoExpr, NonNestedLiteral, _1DArray + + +def is_expr(obj: Any) -> TypeIs[Expr]: + """Check whether `obj` is a Narwhals Expr.""" + from narwhals.expr import Expr + + return isinstance(obj, Expr) + + +def is_series(obj: Any) -> TypeIs[Series[Any]]: + """Check whether `obj` is a Narwhals Expr.""" + from narwhals.series import Series + + return isinstance(obj, Series) + + +def combine_evaluate_output_names( + *exprs: CompliantExpr[CompliantFrameT, Any], +) -> EvalNames[CompliantFrameT]: + # Follow left-hand-rule for naming. E.g. `nw.sum_horizontal(expr1, expr2)` takes the + # first name of `expr1`. + def evaluate_output_names(df: CompliantFrameT) -> Sequence[str]: + return exprs[0]._evaluate_output_names(df)[:1] + + return evaluate_output_names + + +def combine_alias_output_names(*exprs: CompliantExprAny) -> AliasNames | None: + # Follow left-hand-rule for naming. E.g. `nw.sum_horizontal(expr1.alias(alias), expr2)` takes the + # aliasing function of `expr1` and apply it to the first output name of `expr1`. + if exprs[0]._alias_output_names is None: + return None + + def alias_output_names(names: Sequence[str]) -> Sequence[str]: + return exprs[0]._alias_output_names(names)[:1] # type: ignore[misc] + + return alias_output_names + + +def evaluate_output_names_and_aliases( + expr: CompliantExprAny, df: CompliantFrameAny, exclude: Sequence[str] +) -> tuple[Sequence[str], Sequence[str]]: + output_names = expr._evaluate_output_names(df) + aliases = ( + output_names + if expr._alias_output_names is None + else expr._alias_output_names(output_names) + ) + if exclude and expr._metadata.expansion_kind.is_multi_unnamed(): + output_names, aliases = zip_strict( + *[ + (x, alias) + for x, alias in zip_strict(output_names, aliases) + if x not in exclude + ] + ) + return output_names, aliases + + +class ExprKind(Enum): + """Describe which kind of expression we are dealing with.""" + + LITERAL = auto() + """e.g. `nw.lit(1)`""" + + AGGREGATION = auto() + """Reduces to a single value, not affected by row order, e.g. `nw.col('a').mean()`""" + + ORDERABLE_AGGREGATION = auto() + """Reduces to a single value, affected by row order, e.g. `nw.col('a').arg_max()`""" + + ELEMENTWISE = auto() + """Preserves length, can operate without context for surrounding rows, e.g. `nw.col('a').abs()`.""" + + ORDERABLE_WINDOW = auto() + """Depends on the rows around it and on their order, e.g. `diff`.""" + + WINDOW = auto() + """Depends on the rows around it and possibly their order, e.g. `rank`.""" + + FILTRATION = auto() + """Changes length, not affected by row order, e.g. `drop_nulls`.""" + + ORDERABLE_FILTRATION = auto() + """Changes length, affected by row order, e.g. `tail`.""" + + OVER = auto() + """Results from calling `.over` on expression.""" + + COL = auto() + """Results from calling `nw.col`.""" + + NTH = auto() + """Results from calling `nw.nth`.""" + + EXCLUDE = auto() + """Results from calling `nw.exclude`.""" + + ALL = auto() + """Results from calling `nw.all`.""" + + SELECTOR = auto() + """Results from creating an expression with a selector.""" + + WHEN_THEN = auto() + """Results from `when/then expression`, possibly followed by `otherwise`.""" + + SERIES = auto() + """Results from converting a Series to Expr.""" + + @property + def is_orderable(self) -> bool: + # Any operation which may be affected by `order_by`, such as `cum_sum`, + # `diff`, `rank`, `arg_max`, ... + return self in { + ExprKind.ORDERABLE_WINDOW, + ExprKind.WINDOW, + ExprKind.ORDERABLE_AGGREGATION, + ExprKind.ORDERABLE_FILTRATION, + } + + @property + def is_elementwise(self) -> bool: + # Any operation which can operate on each row independently + # of the rows around it, e.g. `abs(), __add__, sum_horizontal, ...` + return self in { + ExprKind.ALL, + ExprKind.COL, + ExprKind.ELEMENTWISE, + ExprKind.EXCLUDE, + ExprKind.LITERAL, + ExprKind.NTH, + ExprKind.SELECTOR, + ExprKind.SERIES, + ExprKind.WHEN_THEN, + } + + @property + def preserves_length(self) -> bool: + return self.is_elementwise or self in {ExprKind.WINDOW, ExprKind.ORDERABLE_WINDOW} + + @property + def is_scalar_like(self) -> bool: + return self in { + ExprKind.AGGREGATION, + ExprKind.LITERAL, + ExprKind.ORDERABLE_AGGREGATION, + } + + +def is_scalar_like(obj: CompliantExprAny) -> bool: + return obj._metadata.is_scalar_like + + +class ExpansionKind(Enum): + """Describe what kind of expansion the expression performs.""" + + SINGLE = auto() + """e.g. `nw.col('a'), nw.sum_horizontal(nw.all())`""" + + MULTI_NAMED = auto() + """e.g. `nw.col('a', 'b')`""" + + MULTI_UNNAMED = auto() + """e.g. `nw.all()`, nw.nth(0, 1)""" + + def is_multi_unnamed(self) -> bool: + return self is ExpansionKind.MULTI_UNNAMED + + def is_multi_output(self) -> bool: + return self in {ExpansionKind.MULTI_NAMED, ExpansionKind.MULTI_UNNAMED} + + def __and__(self, other: ExpansionKind) -> Literal[ExpansionKind.MULTI_UNNAMED]: + if self is ExpansionKind.MULTI_UNNAMED and other is ExpansionKind.MULTI_UNNAMED: + # e.g. nw.selectors.all() - nw.selectors.numeric(). + return ExpansionKind.MULTI_UNNAMED + # Don't attempt anything more complex, keep it simple and raise in the face of ambiguity. + msg = f"Unsupported ExpansionKind combination, got {self} and {other}, please report a bug." # pragma: no cover + raise AssertionError(msg) # pragma: no cover + + +class ExprNode: + """An operation to create or modify an expression. + + Parameters: + kind: ExprKind of operation. + name: Name of function, as defined in the compliant protocols. + exprs: Expressifiable arguments to function. + str_as_lit: Whether to interpret strings as literals when they + are present in `exprs`. + allow_multi_output: Whether to allow any of `exprs` to be multi-output. + kwargs: Other (non-expressifiable) arguments to function. + """ + + def __init__( + self, + kind: ExprKind, + name: str, + /, + *, + exprs: Sequence[IntoExpr | NonNestedLiteral] = (), + str_as_lit: bool = False, + allow_multi_output: bool = False, + **kwargs: Any, + ) -> None: + self.kind: ExprKind = kind + self.name: str = name + self.exprs: Sequence[IntoExpr | NonNestedLiteral] = exprs + self.kwargs: dict[str, Any] = kwargs + self.str_as_lit: bool = str_as_lit + self.allow_multi_output: bool = allow_multi_output + + # Cached methods. + self._is_orderable_cached: bool | None = None + self._is_elementwise_cached: bool | None = None + + def __repr__(self) -> str: + if self.name == "col": + names = ", ".join(str(x) for x in self.kwargs["names"]) + return f"col({names})" + arg_str = [] + expr_repr = ", ".join(str(x) for x in self.exprs) + kwargs_repr = ", ".join(f"{key}={value}" for key, value in self.kwargs.items()) + if self.exprs: + arg_str.append(expr_repr) + if self.kwargs: + arg_str.append(kwargs_repr) + return f"{self.name}({', '.join(arg_str)})" + + def as_dict(self) -> dict[str, Any]: # pragma: no cover + # Just for debugging. + return { + "kind": self.kind, + "name": self.name, + "exprs": self.exprs, + "kwargs": self.kwargs, + "str_as_lit": self.str_as_lit, + "allow_multi_output": self.allow_multi_output, + } + + def _with_kwargs(self, **kwargs: Any) -> ExprNode: + return self.__class__( + self.kind, self.name, exprs=self.exprs, str_as_lit=self.str_as_lit, **kwargs + ) + + def _push_down_over_node_in_place( + self, over_node: ExprNode, over_node_without_order_by: ExprNode + ) -> None: + exprs: list[IntoExpr | NonNestedLiteral] = [] + # Note: please keep this as a for-loop (rather than a list-comprehension) + # so that pytest-cov highlights any uncovered branches. + over_node_order_by = over_node.kwargs["order_by"] + over_node_partition_by = over_node.kwargs["partition_by"] + for expr in self.exprs: + if not is_expr(expr): + exprs.append(expr) + elif over_node_order_by and any( + expr_node.is_orderable() for expr_node in expr._nodes + ): + exprs.append(expr._with_over_node(over_node)) + elif over_node_partition_by and not all( + expr_node.is_elementwise() for expr_node in expr._nodes + ): + exprs.append(expr._with_over_node(over_node_without_order_by)) + else: + # If there's no `partition_by`, then `over_node_without_order_by` is a no-op. + exprs.append(expr) + self.exprs = exprs + + def is_orderable(self) -> bool: + if self._is_orderable_cached is None: + # Note: don't combine these if/then statements so that pytest-cov shows if + # anything is uncovered. + if self.kind.is_orderable: # noqa: SIM114 + self._is_orderable_cached = True + elif any( + any(node.is_orderable() for node in expr._nodes) + for expr in self.exprs + if is_expr(expr) + ): + self._is_orderable_cached = True + else: + self._is_orderable_cached = False + return self._is_orderable_cached + + def is_elementwise(self) -> bool: + if self._is_elementwise_cached is None: + # Note: don't combine these if/then statements so that pytest-cov shows if + # anything is uncovered. + if not self.kind.is_elementwise: # noqa: SIM114 + self._is_elementwise_cached = False + elif any( + any(not node.is_elementwise() for node in expr._nodes) + for expr in self.exprs + if is_expr(expr) + ): + self._is_elementwise_cached = False + else: + self._is_elementwise_cached = True + return self._is_elementwise_cached + + +class ExprMetadata: + """Expression metadata. + + Parameters: + expansion_kind: What kind of expansion the expression performs. + has_windows: Whether it already contains window functions. + is_elementwise: Whether it can operate row-by-row without context + of the other rows around it. + is_literal: Whether it is just a literal wrapped in an expression. + is_scalar_like: Whether it is a literal or an aggregation. + n_orderable_ops: The number of order-dependent operations. In the + lazy case, this number must be `0` by the time the expression + is evaluated. + preserves_length: Whether the expression preserves the input length. + current_node: The current ExprNode in the linked list. + prev: Reference to the previous ExprMetadata in the linked list (None for root). + """ + + __slots__ = ( + "current_node", + "expansion_kind", + "has_windows", + "is_elementwise", + "is_literal", + "is_scalar_like", + "n_orderable_ops", + "preserves_length", + "prev", + ) + + def __init__( + self, + expansion_kind: ExpansionKind, + *, + has_windows: bool = False, + n_orderable_ops: int = 0, + preserves_length: bool = True, + is_elementwise: bool = True, + is_scalar_like: bool = False, + is_literal: bool = False, + current_node: ExprNode, + prev: ExprMetadata | None = None, + ) -> None: + if is_literal: + assert is_scalar_like # noqa: S101 # debug assertion + self.expansion_kind: ExpansionKind = expansion_kind + self.has_windows: bool = has_windows + self.n_orderable_ops: int = n_orderable_ops + self.is_elementwise: bool = is_elementwise + self.preserves_length: bool = preserves_length + self.is_scalar_like: bool = is_scalar_like + self.is_literal: bool = is_literal + self.current_node: ExprNode = current_node + self.prev: ExprMetadata | None = prev + + def __init_subclass__(cls, /, *args: Any, **kwds: Any) -> Never: # pragma: no cover + msg = f"Cannot subclass {cls.__name__!r}" + raise TypeError(msg) + + def __repr__(self) -> str: # pragma: no cover + nodes = tuple(reversed(tuple(self.iter_nodes_reversed()))) + return ( + f"ExprMetadata(\n" + f" expansion_kind: {self.expansion_kind},\n" + f" has_windows: {self.has_windows},\n" + f" n_orderable_ops: {self.n_orderable_ops},\n" + f" is_elementwise: {self.is_elementwise},\n" + f" preserves_length: {self.preserves_length},\n" + f" is_scalar_like: {self.is_scalar_like},\n" + f" is_literal: {self.is_literal},\n" + f" nodes: {nodes},\n" + ")" + ) + + def iter_nodes_reversed(self) -> Iterator[ExprNode]: + """Iterate through all nodes from current to root.""" + current: ExprMetadata | None = self + while current is not None: + yield current.current_node + current = current.prev + + @classmethod + def from_node( + cls, node: ExprNode, *compliant_exprs: CompliantExprAny + ) -> ExprMetadata: + return KIND_TO_METADATA_CONSTRUCTOR[node.kind](node, *compliant_exprs) + + def with_node( + self, + node: ExprNode, + compliant_expr: CompliantExprAny, + *compliant_expr_args: CompliantExprAny, + ) -> ExprMetadata: + return KIND_TO_METADATA_UPDATER[node.kind]( + self, node, compliant_expr, *compliant_expr_args + ) + + @classmethod + def from_aggregation( + cls, node: ExprNode, *compliant_exprs: CompliantExprAny + ) -> ExprMetadata: + return combine_metadata( + *compliant_exprs, to_single_output=True, current_node=node, prev=None + ) + + @classmethod + def from_literal(cls, node: ExprNode) -> ExprMetadata: + return cls( + ExpansionKind.SINGLE, + is_elementwise=True, + preserves_length=False, + is_literal=True, + is_scalar_like=True, + current_node=node, + prev=None, + ) + + @classmethod + def from_series(cls, node: ExprNode) -> ExprMetadata: + return cls(ExpansionKind.SINGLE, current_node=node, prev=None) + + @classmethod + def from_col(cls, node: ExprNode) -> ExprMetadata: + # e.g. `nw.col('a')`, `nw.nth(0)` + return ( + cls(ExpansionKind.SINGLE, current_node=node, prev=None) + if len(node.kwargs["names"]) == 1 + else cls.from_selector_multi_named(node) + ) + + @classmethod + def from_nth(cls, node: ExprNode) -> ExprMetadata: + return ( + cls(ExpansionKind.SINGLE, current_node=node, prev=None) + if len(node.kwargs["indices"]) == 1 + else cls.from_selector_multi_named(node) + ) + + @classmethod + def from_selector_multi_named(cls, node: ExprNode) -> ExprMetadata: + # e.g. `nw.col('a', 'b')` + return cls(ExpansionKind.MULTI_NAMED, current_node=node, prev=None) + + @classmethod + def from_selector_multi_unnamed(cls, node: ExprNode) -> ExprMetadata: + # e.g. `nw.all()` + return cls(ExpansionKind.MULTI_UNNAMED, current_node=node, prev=None) + + @classmethod + def from_elementwise( + cls, node: ExprNode, *compliant_exprs: CompliantExprAny + ) -> ExprMetadata: + return combine_metadata( + *compliant_exprs, to_single_output=True, current_node=node, prev=None + ) + + @property + def is_filtration(self) -> bool: + return not self.preserves_length and not self.is_scalar_like + + def with_aggregation(self, node: ExprNode, _ce: CompliantExprAny) -> ExprMetadata: + if self.is_scalar_like: + msg = "Can't apply aggregations to scalar-like expressions." + raise InvalidOperationError(msg) + return ExprMetadata( + self.expansion_kind, + has_windows=self.has_windows, + n_orderable_ops=self.n_orderable_ops, + preserves_length=False, + is_elementwise=False, + is_scalar_like=True, + is_literal=False, + current_node=node, + prev=self, + ) + + def with_orderable_aggregation( + self, node: ExprNode, _ce: CompliantExprAny + ) -> ExprMetadata: + # Deprecated, used only in stable.v1. + if self.is_scalar_like: # pragma: no cover + msg = "Can't apply aggregations to scalar-like expressions." + raise InvalidOperationError(msg) + return ExprMetadata( + self.expansion_kind, + has_windows=self.has_windows, + n_orderable_ops=self.n_orderable_ops + 1, + preserves_length=False, + is_elementwise=False, + is_scalar_like=True, + is_literal=False, + current_node=node, + prev=self, + ) + + def with_elementwise( + self, + node: ExprNode, + compliant_expr: CompliantExprAny, + *compliant_expr_args: CompliantExprAny, + ) -> ExprMetadata: + return combine_metadata( + compliant_expr, + *compliant_expr_args, + to_single_output=False, + current_node=node, + prev=compliant_expr._metadata, + ) + + def with_window(self, node: ExprNode, _ce: CompliantExprAny) -> ExprMetadata: + # Window function which may (but doesn't have to) be used with `over(order_by=...)`. + if self.is_scalar_like: + msg = "Can't apply window (e.g. `rank`) to scalar-like expression." + raise InvalidOperationError(msg) + return ExprMetadata( + self.expansion_kind, + has_windows=self.has_windows, + # The function isn't order-dependent (but, users can still use `order_by` if they wish!), + # so we don't increment `n_orderable_ops`. + n_orderable_ops=self.n_orderable_ops, + preserves_length=self.preserves_length, + is_elementwise=False, + is_scalar_like=False, + is_literal=False, + current_node=node, + prev=self, + ) + + def with_orderable_window( + self, node: ExprNode, _ce: CompliantExprAny + ) -> ExprMetadata: + # Window function which must be used with `over(order_by=...)`. + if self.is_scalar_like: + msg = "Can't apply orderable window (e.g. `diff`, `shift`) to scalar-like expression." + raise InvalidOperationError(msg) + return ExprMetadata( + self.expansion_kind, + has_windows=self.has_windows, + n_orderable_ops=self.n_orderable_ops + 1, + preserves_length=self.preserves_length, + is_elementwise=False, + is_scalar_like=False, + is_literal=False, + current_node=node, + prev=self, + ) + + def with_ordered_over(self, node: ExprNode, _ce: CompliantExprAny) -> ExprMetadata: + if self.has_windows: + msg = "Cannot nest `over` statements." + raise InvalidOperationError(msg) + if self.is_elementwise or self.is_filtration: + msg = ( + "Cannot use `over` on expressions which are elementwise\n" + "(e.g. `abs`) or which change length (e.g. `drop_nulls`)." + ) + raise InvalidOperationError(msg) + n_orderable_ops = self.n_orderable_ops + if ( + not n_orderable_ops + and next(self.op_nodes_reversed()).kind is not ExprKind.WINDOW + ): + msg = ( + "Cannot use `order_by` in `over` on expression which isn't orderable.\n" + "If your expression is orderable, then make sure that `over(order_by=...)`\n" + "comes immediately after the order-dependent expression.\n\n" + "Hint: instead of\n" + " - `(nw.col('price').diff() + 1).over(order_by='date')`\n" + "write:\n" + " + `nw.col('price').diff().over(order_by='date') + 1`\n" + ) + raise InvalidOperationError(msg) + if next(self.op_nodes_reversed()).kind.is_orderable and n_orderable_ops > 0: + n_orderable_ops -= 1 + return ExprMetadata( + self.expansion_kind, + has_windows=True, + n_orderable_ops=n_orderable_ops, + preserves_length=True, + is_elementwise=False, + is_scalar_like=False, + is_literal=False, + current_node=node, + prev=self, + ) + + def with_partitioned_over( + self, node: ExprNode, _ce: CompliantExprAny + ) -> ExprMetadata: + if self.has_windows: + msg = "Cannot nest `over` statements." + raise InvalidOperationError(msg) + if self.is_elementwise or self.is_filtration: + msg = ( + "Cannot use `over` on expressions which are elementwise\n" + "(e.g. `abs`) or which change length (e.g. `drop_nulls`)." + ) + raise InvalidOperationError(msg) + return ExprMetadata( + self.expansion_kind, + has_windows=True, + n_orderable_ops=self.n_orderable_ops, + preserves_length=True, + is_elementwise=False, + is_scalar_like=False, + is_literal=False, + current_node=node, + prev=self, + ) + + def with_over(self, node: ExprNode, _ce: CompliantExprAny) -> ExprMetadata: + if node.kwargs["order_by"]: + return self.with_ordered_over(node, _ce) + if not node.kwargs["partition_by"]: # pragma: no cover + msg = "At least one of `partition_by` or `order_by` must be specified." + raise InvalidOperationError(msg) + return self.with_partitioned_over(node, _ce) + + def with_filtration( + self, node: ExprNode, *compliant_exprs: CompliantExprAny + ) -> ExprMetadata: + if self.is_scalar_like: + msg = "Can't apply filtration (e.g. `drop_nulls`) to scalar-like expression." + raise InvalidOperationError(msg) + result_has_windows = any(x._metadata.has_windows for x in compliant_exprs) + result_n_orderable_ops = sum(x._metadata.n_orderable_ops for x in compliant_exprs) + return ExprMetadata( + self.expansion_kind, + has_windows=result_has_windows, + n_orderable_ops=result_n_orderable_ops, + preserves_length=False, + is_elementwise=False, + is_scalar_like=False, + is_literal=False, + current_node=node, + prev=self, + ) + + def with_orderable_filtration( + self, node: ExprNode, _ce: CompliantExprAny + ) -> ExprMetadata: + if self.is_scalar_like: + msg = "Can't apply filtration (e.g. `drop_nulls`) to scalar-like expression." + raise InvalidOperationError(msg) + return ExprMetadata( + self.expansion_kind, + has_windows=self.has_windows, + n_orderable_ops=self.n_orderable_ops + 1, + preserves_length=False, + is_elementwise=False, + is_scalar_like=False, + is_literal=False, + current_node=node, + prev=self, + ) + + def op_nodes_reversed(self) -> Iterator[ExprNode]: + for node in self.iter_nodes_reversed(): + if node.name.startswith(("name.", "alias")): + # Skip nodes which only do aliasing. + continue + yield node + + +KIND_TO_METADATA_CONSTRUCTOR: dict[ExprKind, Callable[[ExprNode], ExprMetadata]] = { + ExprKind.AGGREGATION: ExprMetadata.from_aggregation, + ExprKind.ALL: ExprMetadata.from_selector_multi_unnamed, + ExprKind.ELEMENTWISE: ExprMetadata.from_elementwise, + ExprKind.EXCLUDE: ExprMetadata.from_selector_multi_unnamed, + ExprKind.SERIES: ExprMetadata.from_series, + ExprKind.COL: ExprMetadata.from_col, + ExprKind.LITERAL: ExprMetadata.from_literal, + ExprKind.NTH: ExprMetadata.from_nth, + ExprKind.SELECTOR: ExprMetadata.from_selector_multi_unnamed, +} + +KIND_TO_METADATA_UPDATER: dict[ExprKind, Callable[..., ExprMetadata]] = { + ExprKind.AGGREGATION: ExprMetadata.with_aggregation, + ExprKind.ELEMENTWISE: ExprMetadata.with_elementwise, + ExprKind.FILTRATION: ExprMetadata.with_filtration, + ExprKind.ORDERABLE_AGGREGATION: ExprMetadata.with_orderable_aggregation, + ExprKind.ORDERABLE_FILTRATION: ExprMetadata.with_orderable_filtration, + ExprKind.OVER: ExprMetadata.with_over, + ExprKind.ORDERABLE_WINDOW: ExprMetadata.with_orderable_window, + ExprKind.WINDOW: ExprMetadata.with_window, +} + + +def combine_metadata( + *compliant_exprs: CompliantExprAny, + to_single_output: bool, + current_node: ExprNode, + prev: ExprMetadata | None, +) -> ExprMetadata: + """Combine metadata from `args`. + + Arguments: + compliant_exprs: Expression arguments. + to_single_output: Whether the result is always single-output, regardless + of the inputs (e.g. `nw.sum_horizontal`). + current_node: The current node being added. + prev: ExprMetadata of previous node. + """ + n_filtrations = 0 + n_scalar_like = 0 + result_expansion_kind = ExpansionKind.SINGLE + result_has_windows = False + result_n_orderable_ops = 0 + # result is elementwise if all inputs are elementwise, and if current operation is elementwise + result_is_elementwise = current_node.kind.is_elementwise + # result is literal if all inputs are literal + result_is_literal = True + + for i, ce in enumerate(compliant_exprs): + metadata = ce._metadata + assert metadata is not None # noqa: S101 + if metadata.expansion_kind.is_multi_output(): + expansion_kind = metadata.expansion_kind + if not to_single_output: + result_expansion_kind = ( + result_expansion_kind & expansion_kind if i > 0 else expansion_kind + ) + + result_has_windows |= metadata.has_windows + result_n_orderable_ops += metadata.n_orderable_ops + result_is_elementwise &= metadata.is_elementwise + result_is_literal &= metadata.is_literal + n_filtrations += int(metadata.is_filtration) + n_scalar_like += int(metadata.is_scalar_like) + + # result is scalar-like if all inputs are scalar-like, or if current operation is an aggregation + result_is_scalar_like = current_node.kind.is_scalar_like or ( + n_scalar_like == len(compliant_exprs) + ) + # result preserves length if: + # - the current operation preserves length + # - there are no filtrations + # - the result is not scalar-like + result_preserves_length = ( + current_node.kind.preserves_length + and n_filtrations == 0 + and not result_is_scalar_like + ) + + if n_filtrations and ( + (n_filtrations > 1) or (n_filtrations + n_scalar_like < len(compliant_exprs)) + ): + msg = "Length-changing expressions can only be used in isolation, or followed by an aggregation" + raise InvalidOperationError(msg) + + return ExprMetadata( + result_expansion_kind, + has_windows=result_has_windows, + n_orderable_ops=result_n_orderable_ops, + preserves_length=result_preserves_length, + is_elementwise=result_is_elementwise, + is_scalar_like=result_is_scalar_like, + is_literal=result_is_literal, + current_node=current_node, + prev=prev, + ) + + +def check_expressions_preserve_length( + *args: CompliantExprAny, function_name: str +) -> None: + # Raise if any argument in `args` isn't length-preserving. + # For Series input, we don't raise (yet), we let such checks happen later, + # as this function works lazily and so can't evaluate lengths. + + if not all(x._metadata.preserves_length for x in args): + msg = f"Expressions which aggregate or change length cannot be passed to '{function_name}'." + raise InvalidOperationError(msg) + + +def _parse_into_expr( + arg: IntoExpr | NonNestedLiteral | _1DArray, + *, + str_as_lit: bool = False, + backend: Any = None, + allow_literal: bool = True, +) -> Expr: + from narwhals.functions import col, lit, new_series + + if isinstance(arg, str) and not str_as_lit: + return col(arg) + if is_numpy_array_1d(arg): + return new_series("", arg, backend=backend)._to_expr() + if is_series(arg): + return arg._to_expr() + if is_expr(arg): + return arg + if not allow_literal: + raise InvalidIntoExprError.from_invalid_type(type(arg)) + return lit(arg) + + +def evaluate_into_exprs( + *exprs: IntoExpr | NonNestedLiteral | _1DArray, + ns: CompliantNamespaceAny, + str_as_lit: bool, + allow_multi_output: bool, +) -> Iterator[CompliantExprAny]: + for expr in exprs: + ret = _parse_into_expr( + expr, str_as_lit=str_as_lit, backend=ns._implementation + )._to_compliant_expr(ns) + if not allow_multi_output and ret._metadata.expansion_kind.is_multi_output(): + msg = "Multi-output expressions are not allowed in this context." + raise MultiOutputExpressionError(msg) + yield ret + + +def maybe_broadcast_ces(*compliant_exprs: CompliantExprAny) -> list[CompliantExprAny]: + broadcast = any(not is_scalar_like(ce) for ce in compliant_exprs) + results: list[CompliantExprAny] = [] + for compliant_expr in compliant_exprs: + if broadcast and is_scalar_like(compliant_expr): + _compliant_expr: CompliantExprAny = compliant_expr.broadcast() + # Make sure to preserve metadata. + _compliant_expr._opt_metadata = compliant_expr._metadata + results.append(_compliant_expr) + else: + results.append(compliant_expr) + return results + + +def evaluate_root_node(node: ExprNode, ns: CompliantNamespaceAny) -> CompliantExprAny: + if node.name in {"col", "exclude"}: + # There's too much potential for Sequence[str] vs str bugs, so we pass down + # `names` positionally rather than as a sequence of strings. + ce = getattr(ns, node.name)(*node.kwargs["names"]) + ces = [] + else: + if "." in node.name: + module, method = node.name.split(".") + func = getattr(getattr(ns, module), method) + else: + func = getattr(ns, node.name) + ces = maybe_broadcast_ces( + *evaluate_into_exprs( + *node.exprs, + ns=ns, + str_as_lit=node.str_as_lit, + allow_multi_output=node.allow_multi_output, + ) + ) + ce = cast("CompliantExprAny", func(*ces, **node.kwargs)) + md = ExprMetadata.from_node(node, *ces) + ce._opt_metadata = md + return ce + + +def evaluate_node( + compliant_expr: CompliantExprAny, node: ExprNode, ns: CompliantNamespaceAny +) -> CompliantExprAny: + md: ExprMetadata = compliant_expr._metadata + compliant_expr, *compliant_expr_args = maybe_broadcast_ces( + compliant_expr, + *evaluate_into_exprs( + *node.exprs, + ns=ns, + str_as_lit=node.str_as_lit, + allow_multi_output=node.allow_multi_output, + ), + ) + md = md.with_node(node, compliant_expr, *compliant_expr_args) + if "." in node.name: + accessor, method = node.name.split(".") + func = getattr(getattr(compliant_expr, accessor), method) + else: + func = getattr(compliant_expr, node.name) + ret = cast("CompliantExprAny", func(*compliant_expr_args, **node.kwargs)) + ret._opt_metadata = md + return ret + + +def evaluate_nodes( + nodes: Sequence[ExprNode], ns: CompliantNamespaceAny +) -> CompliantExprAny: + ce = evaluate_root_node(nodes[0], ns) + for node in nodes[1:]: + ce = evaluate_node(ce, node, ns) + return ce diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_namespace.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..2d4480cc068a4c510fa0b67953fcfe59f30c9296 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_namespace.py @@ -0,0 +1,280 @@ +"""Narwhals-level equivalent of `CompliantNamespace`.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, ClassVar, Generic, overload + +from narwhals._compliant.typing import CompliantNamespaceAny, CompliantNamespaceT_co +from narwhals._native import ( + NativeAny, + NativeArrow, + NativeCuDF, + NativeDask, + NativeDuckDB, + NativeIbis, + NativeModin, + NativePandas, + NativePandasLike, + NativePolars, + NativeSparkLike, + NativeUnknown, + _CuDFDataFrame, + _CuDFSeries, + _ModinDataFrame, + _ModinSeries, + is_native_arrow, + is_native_cudf, + is_native_dask, + is_native_duckdb, + is_native_ibis, + is_native_modin, + is_native_pandas, + is_native_polars, + is_native_pyspark_connect, + is_native_spark_like, + is_native_sqlframe, +) +from narwhals._utils import Implementation, Version + +if TYPE_CHECKING: + import pandas as pd + from typing_extensions import TypeAlias + + from narwhals._arrow.namespace import ArrowNamespace + from narwhals._dask.namespace import DaskNamespace + from narwhals._duckdb.namespace import DuckDBNamespace + from narwhals._ibis.namespace import IbisNamespace + from narwhals._pandas_like.namespace import PandasLikeNamespace + from narwhals._polars.namespace import PolarsNamespace + from narwhals._spark_like.namespace import SparkLikeNamespace + from narwhals._typing import ( + Arrow, + Backend, + Dask, + DuckDB, + EagerAllowed, + Ibis, + IntoBackend, + PandasLike, + Polars, + SparkLike, + ) + + EagerAllowedNamespace: TypeAlias = "Namespace[PandasLikeNamespace] | Namespace[ArrowNamespace] | Namespace[PolarsNamespace]" + +__all__ = ["Namespace"] + + +class Namespace(Generic[CompliantNamespaceT_co]): + _compliant_namespace: CompliantNamespaceT_co + _version: ClassVar[Version] = Version.MAIN + + def __init__(self, namespace: CompliantNamespaceT_co, /) -> None: + self._compliant_namespace = namespace + + def __init_subclass__(cls, *args: Any, version: Version, **kwds: Any) -> None: + super().__init_subclass__(*args, **kwds) + + if isinstance(version, Version): + cls._version = version + else: + msg = f"Expected {Version} but got {type(version).__name__!r}" + raise TypeError(msg) + + def __repr__(self) -> str: + return f"Namespace[{type(self.compliant).__name__}]" + + @property + def compliant(self) -> CompliantNamespaceT_co: + return self._compliant_namespace + + @property + def implementation(self) -> Implementation: + return self.compliant._implementation + + @property + def version(self) -> Version: + return self._version + + @overload + @classmethod + def from_backend(cls, backend: PandasLike, /) -> Namespace[PandasLikeNamespace]: ... + + @overload + @classmethod + def from_backend(cls, backend: Polars, /) -> Namespace[PolarsNamespace]: ... + + @overload + @classmethod + def from_backend(cls, backend: Arrow, /) -> Namespace[ArrowNamespace]: ... + + @overload + @classmethod + def from_backend(cls, backend: SparkLike, /) -> Namespace[SparkLikeNamespace]: ... + + @overload + @classmethod + def from_backend(cls, backend: DuckDB, /) -> Namespace[DuckDBNamespace]: ... + + @overload + @classmethod + def from_backend(cls, backend: Dask, /) -> Namespace[DaskNamespace]: ... + + @overload + @classmethod + def from_backend(cls, backend: Ibis, /) -> Namespace[IbisNamespace]: ... + + @overload + @classmethod + def from_backend(cls, backend: EagerAllowed, /) -> EagerAllowedNamespace: ... + + @overload + @classmethod + def from_backend( + cls, backend: IntoBackend[Backend], / + ) -> Namespace[CompliantNamespaceAny]: ... + + @classmethod + def from_backend( + cls: type[Namespace[Any]], backend: IntoBackend[Backend], / + ) -> Namespace[Any]: + """Instantiate from native namespace module, string, or Implementation. + + Arguments: + backend: native namespace module, string, or Implementation. + + Examples: + >>> Namespace.from_backend("polars") + Namespace[PolarsNamespace] + """ + impl = Implementation.from_backend(backend) + backend_version = impl._backend_version() # noqa: F841 + version = cls._version + ns: CompliantNamespaceAny + if impl.is_pandas_like(): + from narwhals._pandas_like.namespace import PandasLikeNamespace + + ns = PandasLikeNamespace(implementation=impl, version=version) + + elif impl.is_polars(): + from narwhals._polars.namespace import PolarsNamespace + + ns = PolarsNamespace(version=version) + elif impl.is_pyarrow(): + from narwhals._arrow.namespace import ArrowNamespace + + ns = ArrowNamespace(version=version) + elif impl.is_spark_like(): + from narwhals._spark_like.namespace import SparkLikeNamespace + + ns = SparkLikeNamespace(implementation=impl, version=version) + elif impl.is_duckdb(): + from narwhals._duckdb.namespace import DuckDBNamespace + + ns = DuckDBNamespace(version=version) + elif impl.is_dask(): + from narwhals._dask.namespace import DaskNamespace + + ns = DaskNamespace(version=version) + elif impl.is_ibis(): + from narwhals._ibis.namespace import IbisNamespace + + ns = IbisNamespace(version=version) + else: + msg = "Not supported Implementation" # pragma: no cover + raise AssertionError(msg) + return cls(ns) + + @overload + @classmethod + def from_native_object( + cls, native: NativePolars, / + ) -> Namespace[PolarsNamespace]: ... + + @overload + @classmethod + def from_native_object( + cls, native: NativePandas, / + ) -> Namespace[PandasLikeNamespace[pd.DataFrame, pd.Series[Any]]]: ... + + @overload + @classmethod + def from_native_object(cls, native: NativeArrow, /) -> Namespace[ArrowNamespace]: ... + + @overload + @classmethod + def from_native_object( + cls, native: NativeSparkLike, / + ) -> Namespace[SparkLikeNamespace]: ... + + @overload + @classmethod + def from_native_object( + cls, native: NativeDuckDB, / + ) -> Namespace[DuckDBNamespace]: ... + + @overload + @classmethod + def from_native_object(cls, native: NativeDask, /) -> Namespace[DaskNamespace]: ... + + @overload + @classmethod + def from_native_object(cls, native: NativeIbis, /) -> Namespace[IbisNamespace]: ... + + @overload + @classmethod + def from_native_object( + cls, native: NativeModin, / + ) -> Namespace[PandasLikeNamespace[_ModinDataFrame, _ModinSeries]]: ... + + @overload + @classmethod + def from_native_object( + cls, native: NativeCuDF, / + ) -> Namespace[PandasLikeNamespace[_CuDFDataFrame, _CuDFSeries]]: ... + + @overload + @classmethod + def from_native_object( + cls, native: NativePandasLike, / + ) -> Namespace[PandasLikeNamespace[Any, Any]]: ... + + @overload + @classmethod + def from_native_object( + cls, native: NativeUnknown, / + ) -> Namespace[CompliantNamespaceAny]: ... + + @classmethod + def from_native_object( + cls: type[Namespace[Any]], native: NativeAny, / + ) -> Namespace[Any]: + impl: Backend + if is_native_polars(native): + impl = Implementation.POLARS + elif is_native_pandas(native): + impl = Implementation.PANDAS + elif is_native_arrow(native): + impl = Implementation.PYARROW + elif is_native_spark_like(native): + impl = ( + Implementation.SQLFRAME + if is_native_sqlframe(native) + else Implementation.PYSPARK_CONNECT + if is_native_pyspark_connect(native) + else Implementation.PYSPARK + ) + elif is_native_dask(native): # pragma: no cover + impl = Implementation.DASK + elif is_native_duckdb(native): + impl = Implementation.DUCKDB + elif is_native_cudf(native): # pragma: no cover + impl = Implementation.CUDF + elif is_native_modin(native): # pragma: no cover + impl = Implementation.MODIN + elif is_native_ibis(native): # pragma: no cover + impl = Implementation.IBIS + else: + msg = f"Unsupported type: {type(native).__qualname__!r}" + raise TypeError(msg) + return cls.from_backend(impl) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_native.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_native.py new file mode 100644 index 0000000000000000000000000000000000000000..2e06ac70418b74807fb748e65a8c795025d55d60 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_native.py @@ -0,0 +1,427 @@ +"""The home for *mostly* [structural] counterparts to [nominal] native types. + +If you find yourself being yelled at by a typechecker and ended up here - **do not fear!** + +We have 5 funky flavors, which tackle two different problem spaces. + +How do we describe [Native types] when ... +- ... **wrapping in** a [Narwhals type]? +- ... **matching to** an [`Implementation`]? + +## Wrapping in a Narwhals type +[//]: # (TODO @dangotbanned: Replace `Thing` with a better name) + +The following examples use the placeholder type `Thing` which represents one of: +- `DataFrame`: (Eager) 2D data structure representing data as a table with rows and columns. +- `LazyFrame`: (Lazy) Computation graph/query against a DataFrame/database. +- `Series`: 1D data structure representing a single column. + +Our goal is to **wrap** a *partially-unknown* native object **in** a [generic class]: + + def wrapping_in_df(native: IntoDataFrameT) -> DataFrame[IntoDataFrameT]: ... + def wrapping_in_lf(native: IntoLazyFrameT) -> LazyFrame[IntoLazyFrameT]: ... + def wrapping_in_ser(native: IntoSeriesT) -> Series[IntoSeriesT]: ... + +### (1) `Native` +Minimal [`Protocol`]s that are [assignable to] *almost any* supported native type of that group: + + class NativeThing(Protocol): + def something_common(self, *args: Any, **kwargs: Any) -> Any: ... + +Note: + This group is primarily a building block for more useful types. + +### (2) `Into` +*Publicly* exported [`TypeAlias`]s of **(1)**: + + IntoThing: TypeAlias = NativeThing + +**But**, occasionally, there'll be an edge-case which we can spell like: + + IntoThing: TypeAlias = Union[, NativeThing] + +Tip: + Reach for these when there **isn't a need to preserve** the original native type. + +### (3) `IntoT` +*Publicly* exported [`TypeVar`]s, bound to **(2)**: + + IntoThingT = TypeVar("IntoThingT", bound=IntoThing) + +Important: + In most situations, you'll want to use these as they **do preserve** the original native type. + +Putting it all together, we can now add a *narwhals-level* wrapper: + + class Thing(Generic[IntoThingT]): + def to_native(self) -> IntoThingT: ... + +## Matching to an `Implementation` +This problem differs as we need to *create* a relationship between *otherwise-unrelated* types. + +Comparing the problems side-by-side, we can more clearly see this difference: + + def wrapping_in_df(native: IntoDataFrameT) -> DataFrame[IntoDataFrameT]: ... + def matching_to_polars(native: pl.DataFrame) -> Literal[Implementation.POLARS]: ... + +### (4) `Native` +If we want to describe a set of specific types and **match** them in [`@overload`s], then these the tools we need. + +For common and easily-installed backends, [`TypeAlias`]s are composed of the native type(s): + + NativePolars: TypeAlias = pl.DataFrame | pl.LazyFrame | pl.Series + +Otherwise, we need to define a [`Protocol`] which the native type(s) can **match** against *when* installed: + + class NativeDask(NativeLazyFrame, Protocol): + _partition_type: type[pd.DataFrame] + +Tip: + The goal is to be as minimal as possible, while still being *specific-enough* to **not match** something else. + +Important: + See [ibis#9276 comment] for a more *in-depth* example that doesn't fit here 😄 + +### (5) `is_native_` +[Type guards] for **(4)**, *similar* to those found in `nw.dependencies`. + +They differ by checking **all** native types/protocols in a single-call and using ``Native`` aliases. + +[structural]: https://typing.python.org/en/latest/spec/glossary.html#term-structural +[nominal]: https://typing.python.org/en/latest/spec/glossary.html#term-nominal +[Native types]: https://narwhals-dev.github.io/narwhals/how_it_works/#polars-and-other-implementations +[Narwhals type]: https://narwhals-dev.github.io/narwhals/api-reference/dataframe/ +[`Implementation`]: https://narwhals-dev.github.io/narwhals/api-reference/implementation/ +[`Protocol`]: https://typing.python.org/en/latest/spec/protocol.html +[assignable to]: https://typing.python.org/en/latest/spec/glossary.html#term-assignable +[`TypeAlias`]: https://mypy.readthedocs.io/en/stable/kinds_of_types.html#type-aliases +[`TypeVar`]: https://mypy.readthedocs.io/en/stable/generics.html#type-variables-with-upper-bounds +[generic class]: https://docs.python.org/3/library/typing.html#user-defined-generic-types +[`@overload`s]: https://typing.python.org/en/latest/spec/overload.html +[ibis#9276 comment]: https://github.com/ibis-project/ibis/issues/9276#issuecomment-3292016818 +[Type guards]: https://typing.python.org/en/latest/spec/narrowing.html +""" + +from __future__ import annotations + +from collections.abc import Callable, Collection, Iterable, Sized +from typing import TYPE_CHECKING, Any, Protocol, TypeVar, Union, cast + +from narwhals.dependencies import ( + get_cudf, + get_modin, + get_pandas, + get_polars, + get_pyarrow, + is_dask_dataframe, + is_duckdb_relation, + is_ibis_table, + is_pyspark_connect_dataframe, + is_pyspark_dataframe, + is_sqlframe_dataframe, +) + +if TYPE_CHECKING: + import duckdb + import pandas as pd + import polars as pl + import pyarrow as pa + from sqlframe.base.dataframe import BaseDataFrame as _BaseDataFrame + from typing_extensions import Self, TypeAlias, TypeIs + + SQLFrameDataFrame = _BaseDataFrame[Any, Any, Any, Any, Any] + T = TypeVar("T") + _Guard: TypeAlias = "Callable[[Any], TypeIs[T]]" + Incomplete: TypeAlias = Any + +__all__ = [ + "IntoDataFrame", + "IntoDataFrameT", + "IntoFrame", + "IntoFrameT", + "IntoLazyFrame", + "IntoLazyFrameT", + "IntoSeries", + "IntoSeriesT", + "NativeAny", + "NativeArrow", + "NativeCuDF", + "NativeDask", + "NativeDataFrame", + "NativeDuckDB", + "NativeFrame", + "NativeIbis", + "NativeKnown", + "NativeLazyFrame", + "NativeModin", + "NativePandas", + "NativePandasLike", + "NativePandasLikeDataFrame", + "NativePandasLikeSeries", + "NativePolars", + "NativePySpark", + "NativePySparkConnect", + "NativeSQLFrame", + "NativeSeries", + "NativeSparkLike", + "NativeUnknown", + "is_native_arrow", + "is_native_cudf", + "is_native_dask", + "is_native_duckdb", + "is_native_ibis", + "is_native_modin", + "is_native_pandas", + "is_native_pandas_like", + "is_native_polars", + "is_native_pyspark", + "is_native_pyspark_connect", + "is_native_spark_like", + "is_native_sqlframe", +] + + +# All dataframes supported by Narwhals have a +# `columns` property. Their similarities don't extend +# _that_ much further unfortunately... +class NativeFrame(Protocol): + @property + def columns(self) -> Any: ... + def join(self, *args: Any, **kwargs: Any) -> Any: ... + + +class NativeDataFrame(Sized, NativeFrame, Protocol): + def drop(self, *args: Any, **kwargs: Any) -> Any: ... + + +class NativeLazyFrame(NativeFrame, Protocol): + def explain(self, *args: Any, **kwargs: Any) -> Any: ... + + +class NativeSeries(Sized, Iterable[Any], Protocol): + def filter(self, *args: Any, **kwargs: Any) -> Any: ... + def value_counts(self, *args: Any, **kwargs: Any) -> Any: ... + def unique(self, *args: Any, **kwargs: Any) -> Any: ... + + +class _BasePandasLike(Sized, Protocol): + index: Any + """`mypy` doesn't like the asymmetric `property` setter in `pandas`.""" + + def __getitem__(self, key: Any, /) -> Any: ... + def __mul__(self, other: float | Collection[float] | Self, /) -> Self: ... + def __floordiv__(self, other: float | Collection[float] | Self, /) -> Self: ... + @property + def loc(self) -> Any: ... + @property + def shape(self) -> tuple[int, ...]: ... + def set_axis(self, labels: Any, *, axis: Any = ..., copy: bool = ...) -> Self: ... + def copy(self, deep: bool = ...) -> Self: ... # noqa: FBT001 + def rename(self, *args: Any, **kwds: Any) -> Self | Incomplete: + """`mypy` & `pyright` disagree on overloads. + + `Incomplete` used to fix [more important issue](https://github.com/narwhals-dev/narwhals/pull/3016#discussion_r2296139744). + """ + + +class _BasePandasLikeFrame(NativeDataFrame, _BasePandasLike, Protocol): ... + + +class _BasePandasLikeSeries(NativeSeries, _BasePandasLike, Protocol): + name: Any | None + + def __init__( + self, + data: Iterable[Any] | None = None, + index: Iterable[Any] | None = None, + dtype: Any | None = None, + name: Any | None = None, + *args: Any, + **kwargs: Any, + ) -> None: ... + def where(self, cond: Any, other: Any = ..., /) -> Self | Incomplete: ... + + +class NativeDask(NativeLazyFrame, Protocol): + _partition_type: type[pd.DataFrame] + + +class _CuDFDataFrame(_BasePandasLikeFrame, Protocol): + def to_pylibcudf(self, *args: Any, **kwds: Any) -> Any: ... + + +class _CuDFSeries(_BasePandasLikeSeries, Protocol): + def to_pylibcudf(self, *args: Any, **kwds: Any) -> Any: ... + + +class NativeIbis(NativeFrame, Protocol): + def sql(self, *args: Any, **kwds: Any) -> Any: ... + def __pyarrow_result__(self, *args: Any, **kwds: Any) -> Any: ... + def __pandas_result__(self, *args: Any, **kwds: Any) -> Any: ... + def __polars_result__(self, *args: Any, **kwds: Any) -> Any: ... + + +class _ModinDataFrame(_BasePandasLikeFrame, Protocol): + _pandas_class: type[pd.DataFrame] + + +class _ModinSeries(_BasePandasLikeSeries, Protocol): + _pandas_class: type[pd.Series[Any]] + + +class _PySparkDataFrame(NativeLazyFrame, Protocol): + def dropDuplicatesWithinWatermark(self, *arg: Any, **kwargs: Any) -> Any: ... # noqa: N802 + + +NativePolars: TypeAlias = "pl.DataFrame | pl.LazyFrame | pl.Series" +NativeArrow: TypeAlias = "pa.Table | pa.ChunkedArray[Any]" +NativeDuckDB: TypeAlias = "duckdb.DuckDBPyRelation" +NativePandas: TypeAlias = "pd.DataFrame | pd.Series[Any]" +NativeModin: TypeAlias = "_ModinDataFrame | _ModinSeries" +NativeCuDF: TypeAlias = "_CuDFDataFrame | _CuDFSeries" +NativePandasLikeSeries: TypeAlias = "pd.Series[Any] | _CuDFSeries | _ModinSeries" +NativePandasLikeDataFrame: TypeAlias = "pd.DataFrame | _CuDFDataFrame | _ModinDataFrame" +NativePandasLike: TypeAlias = "NativePandasLikeDataFrame | NativePandasLikeSeries" +NativeSQLFrame: TypeAlias = "_BaseDataFrame[Any, Any, Any, Any, Any]" +NativePySpark: TypeAlias = _PySparkDataFrame +NativePySparkConnect: TypeAlias = _PySparkDataFrame +NativeSparkLike: TypeAlias = "NativeSQLFrame | NativePySpark | NativePySparkConnect" +NativeKnown: TypeAlias = "NativePolars | NativeArrow | NativePandasLike | NativeSparkLike | NativeDuckDB | NativeDask | NativeIbis" +NativeUnknown: TypeAlias = "NativeDataFrame | NativeSeries | NativeLazyFrame" +NativeAny: TypeAlias = "NativeKnown | NativeUnknown" + +IntoDataFrame: TypeAlias = NativeDataFrame +"""Anything which can be converted to a Narwhals DataFrame. + +Use this if your function accepts a narwhalifiable object but doesn't care about its backend. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import IntoDataFrame + >>> def agnostic_shape(df_native: IntoDataFrame) -> tuple[int, int]: + ... df = nw.from_native(df_native, eager_only=True) + ... return df.shape +""" + +IntoLazyFrame: TypeAlias = Union[NativeLazyFrame, NativeIbis] +IntoFrame: TypeAlias = Union[IntoDataFrame, IntoLazyFrame] +"""Anything which can be converted to a Narwhals DataFrame or LazyFrame. + +Use this if your function can accept an object which can be converted to either +`nw.DataFrame` or `nw.LazyFrame` and it doesn't care about its backend. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import IntoFrame + >>> def agnostic_columns(df_native: IntoFrame) -> list[str]: + ... df = nw.from_native(df_native) + ... return df.collect_schema().names() +""" + +IntoSeries: TypeAlias = NativeSeries +"""Anything which can be converted to a Narwhals Series. + +Use this if your function can accept an object which can be converted to `nw.Series` +and it doesn't care about its backend. + +Examples: + >>> from typing import Any + >>> import narwhals as nw + >>> from narwhals.typing import IntoSeries + >>> def agnostic_to_list(s_native: IntoSeries) -> list[Any]: + ... s = nw.from_native(s_native) + ... return s.to_list() +""" + +IntoFrameT = TypeVar("IntoFrameT", bound=IntoFrame) +"""TypeVar bound to object convertible to Narwhals DataFrame or Narwhals LazyFrame. + +Use this if your function accepts an object which is convertible to `nw.DataFrame` +or `nw.LazyFrame` and returns an object of the same type. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import IntoFrameT + >>> def agnostic_func(df_native: IntoFrameT) -> IntoFrameT: + ... df = nw.from_native(df_native) + ... return df.with_columns(c=nw.col("a") + 1).to_native() +""" + +IntoDataFrameT = TypeVar("IntoDataFrameT", bound=IntoDataFrame) +"""TypeVar bound to object convertible to Narwhals DataFrame. + +Use this if your function accepts an object which can be converted to `nw.DataFrame` +and returns an object of the same class. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import IntoDataFrameT + >>> def agnostic_func(df_native: IntoDataFrameT) -> IntoDataFrameT: + ... df = nw.from_native(df_native, eager_only=True) + ... return df.with_columns(c=df["a"] + 1).to_native() +""" + +IntoLazyFrameT = TypeVar("IntoLazyFrameT", bound=IntoLazyFrame) +IntoSeriesT = TypeVar("IntoSeriesT", bound=IntoSeries) +"""TypeVar bound to object convertible to Narwhals Series. + +Use this if your function accepts an object which can be converted to `nw.Series` +and returns an object of the same class. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import IntoSeriesT + >>> def agnostic_abs(s_native: IntoSeriesT) -> IntoSeriesT: + ... s = nw.from_native(s_native, series_only=True) + ... return s.abs().to_native() +""" + + +def is_native_polars(obj: Any) -> TypeIs[NativePolars]: + return (pl := get_polars()) is not None and isinstance( + obj, (pl.DataFrame, pl.Series, pl.LazyFrame) + ) + + +def is_native_arrow(obj: Any) -> TypeIs[NativeArrow]: + return (pa := get_pyarrow()) is not None and isinstance( + obj, (pa.Table, pa.ChunkedArray) + ) + + +is_native_dask = cast("_Guard[NativeDask]", is_dask_dataframe) +is_native_duckdb: _Guard[NativeDuckDB] = is_duckdb_relation +is_native_sqlframe: _Guard[NativeSQLFrame] = is_sqlframe_dataframe +is_native_pyspark = cast("_Guard[NativePySpark]", is_pyspark_dataframe) +is_native_pyspark_connect = cast( + "_Guard[NativePySparkConnect]", is_pyspark_connect_dataframe +) +is_native_ibis = cast("_Guard[NativeIbis]", is_ibis_table) + + +def is_native_pandas(obj: Any) -> TypeIs[NativePandas]: + return (pd := get_pandas()) is not None and isinstance(obj, (pd.DataFrame, pd.Series)) + + +def is_native_modin(obj: Any) -> TypeIs[NativeModin]: + return (mpd := get_modin()) is not None and isinstance( + obj, (mpd.DataFrame, mpd.Series) + ) + + +def is_native_cudf(obj: Any) -> TypeIs[NativeCuDF]: + return (cudf := get_cudf()) is not None and isinstance( + obj, (cudf.DataFrame, cudf.Series) + ) # pragma: no cover + + +def is_native_pandas_like(obj: Any) -> TypeIs[NativePandasLike]: + return is_native_pandas(obj) or is_native_cudf(obj) or is_native_modin(obj) + + +def is_native_spark_like(obj: Any) -> TypeIs[NativeSparkLike]: + return ( + is_native_sqlframe(obj) + or is_native_pyspark(obj) + or is_native_pyspark_connect(obj) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_translate.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_translate.py new file mode 100644 index 0000000000000000000000000000000000000000..48531e144c693f2b61d6f66104f2485924d13523 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_translate.py @@ -0,0 +1,321 @@ +"""[Protocols] defining conversion methods between representations, and related [structural] typing. + +The protocols come in 3 flavors and are [generic] to promote reuse. + +These examples use the placeholder types `Narwhal` and `Other`: +- `Narwhal`: some class written in `narwhals`. +- `Other`: any other class, could be native, compliant, or a builtin. + +## `To` +When we want to convert or unwrap a `Narwhal` into an `Other`, +we provide an **instance** method: + + ToOtherT_co = TypeVar("ToOtherT_co", covariant=True) + + class ToOther(Protocol[ToOtherT_co]): + def to_other(self, *args: Any, **kwds: Any) -> ToOtherT_co: ... + +- `*args`, `**kwds` are defined to be *permissive* and allow a wider set of signatures when implementing. + - In most cases, they are unused. + - But come in handy when adapting an [upstream signature]. +- We use a **covariant** `TypeVar`. + +## `From` +But what if we have `Other` and want to do the reverse? + +Our `Narwhal` will need to provide a `@classmethod`: + + FromOtherT_contra = TypeVar("FromOtherT_contra", contravariant=True) + + class FromOther(Protocol[FromOtherT_contra]): + @classmethod + def from_other(cls, data: FromOtherT_contra, *args: Any, **kwds: Any) -> Self: ... + +- `*args`, `**kwds` serve a similar purpose as before, but are much more frequently used. +- We've added a **required** [positional-only] parameter `data` which will always be passed `Other`. + - This removes the name from the contract of the protocol. + - Implementations are free to use something more descriptive for documentation purposes. +- We use a **contravariant** `TypeVar`. + +## `Convertible` +Combining our `to_` and `from_` methods allows us to convert in both directions `Narwhal` <-> `Other`: + + class OtherConvertible( + ToOther[ToOtherT_co], + FromOther[FromOtherT_contra], + Protocol[ToOtherT_co, FromOtherT_contra], + ): ... + +## See Also +Variance of `TypeVar`(s) can be tricky to wrap your head around. + +To learn more see [moist], [dry], or [even drier] - depending on how deep you wanna go. + +[Protocols]: https://typing.python.org/en/latest/spec/protocol.html +[generic]: https://typing.python.org/en/latest/spec/generics.html +[structural]: https://typing.python.org/en/latest/spec/glossary.html#term-structural +[upstream signature]: https://numpy.org/doc/stable/user/basics.interoperability.html#the-array-method +[positional-only]: https://peps.python.org/pep-0570/ +[moist]: https://mypy.readthedocs.io/en/stable/generics.html#variance-of-generic-types +[dry]: https://typing.python.org/en/latest/spec/generics.html#variance +[even drier]: https://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29 +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import TYPE_CHECKING, Any, Literal, Protocol, TypedDict + +from narwhals._typing_compat import TypeVar + +if TYPE_CHECKING: + import pyarrow as pa + from typing_extensions import Required, Self, TypeAlias, TypeIs + + +class ArrowStreamExportable(Protocol): + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: ... + + +ToNumpyT_co = TypeVar("ToNumpyT_co", covariant=True) +FromNumpyDT_contra = TypeVar( + "FromNumpyDT_contra", contravariant=True, default=ToNumpyT_co +) +FromNumpyT_contra = TypeVar("FromNumpyT_contra", contravariant=True) + + +class ToNumpy(Protocol[ToNumpyT_co]): + def to_numpy(self, *args: Any, **kwds: Any) -> ToNumpyT_co: ... + + +class FromNumpy(Protocol[FromNumpyT_contra]): + @classmethod + def from_numpy(cls, data: FromNumpyT_contra, *args: Any, **kwds: Any) -> Self: ... + + +class NumpyConvertible( + ToNumpy[ToNumpyT_co], + FromNumpy[FromNumpyDT_contra], + Protocol[ToNumpyT_co, FromNumpyDT_contra], +): + def to_numpy(self, dtype: Any, *, copy: bool | None) -> ToNumpyT_co: ... + + +FromIterableT_contra = TypeVar("FromIterableT_contra", contravariant=True, default=Any) + + +class FromIterable(Protocol[FromIterableT_contra]): + @classmethod + def from_iterable( + cls, data: Iterable[FromIterableT_contra], *args: Any, **kwds: Any + ) -> Self: ... + + +ToDictDT_co = TypeVar( + "ToDictDT_co", bound=Mapping[str, Any], covariant=True, default="dict[str, Any]" +) +FromDictDT_contra = TypeVar( + "FromDictDT_contra", + bound=Mapping[str, Any], + contravariant=True, + default=Mapping[str, Any], +) + + +class ToDict(Protocol[ToDictDT_co]): + def to_dict(self, *args: Any, **kwds: Any) -> ToDictDT_co: ... + + +class FromDict(Protocol[FromDictDT_contra]): + @classmethod + def from_dict(cls, data: FromDictDT_contra, *args: Any, **kwds: Any) -> Self: ... + + +class DictConvertible( + ToDict[ToDictDT_co], + FromDict[FromDictDT_contra], + Protocol[ToDictDT_co, FromDictDT_contra], +): ... + + +IntoArrowTable: TypeAlias = "ArrowStreamExportable | pa.Table" +"""An object supporting the [Arrow PyCapsule Interface], or a native [`pyarrow.Table`]. + +[Arrow PyCapsule Interface]: https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html#arrowstream-export +[`pyarrow.Table`]: https://arrow.apache.org/docs/python/generated/pyarrow.Table.html +""" +ToArrowT_co = TypeVar("ToArrowT_co", covariant=True) +FromArrowDT_contra = TypeVar( + "FromArrowDT_contra", contravariant=True, default=IntoArrowTable +) + + +class ToArrow(Protocol[ToArrowT_co]): + def to_arrow(self, *args: Any, **kwds: Any) -> ToArrowT_co: ... + + +class FromArrow(Protocol[FromArrowDT_contra]): + @classmethod + def from_arrow(cls, data: FromArrowDT_contra, *args: Any, **kwds: Any) -> Self: ... + + +class ArrowConvertible( + ToArrow[ToArrowT_co], + FromArrow[FromArrowDT_contra], + Protocol[ToArrowT_co, FromArrowDT_contra], +): ... + + +FromNativeT = TypeVar("FromNativeT") + + +class FromNative(Protocol[FromNativeT]): + @classmethod + def from_native(cls, data: FromNativeT, *args: Any, **kwds: Any) -> Self: ... + @staticmethod + def _is_native(obj: FromNativeT | Any, /) -> TypeIs[FromNativeT]: + """Return `True` if `obj` can be passed to `from_native`.""" + ... + + +ToNarwhalsT_co = TypeVar("ToNarwhalsT_co", covariant=True) + + +class ToNarwhals(Protocol[ToNarwhalsT_co]): + def to_narwhals(self) -> ToNarwhalsT_co: + """Convert into public representation.""" + ... + + +class _ExcludeSeries(TypedDict, total=False): + eager_only: bool + series_only: Literal[False] + allow_series: Literal[False] | None + + +class ExcludeSeries(_ExcludeSeries, total=False): + pass_through: bool + + +class ExcludeSeriesV1(_ExcludeSeries, total=False): + pass_through: bool | None + eager_or_interchange_only: Literal[False] + + +class ExcludeSeriesStrictV1(_ExcludeSeries, total=False): + strict: bool | None + eager_or_interchange_only: Literal[False] + + +class _AllowSeries(TypedDict, total=False): + eager_only: bool + series_only: Literal[False] + allow_series: Required[Literal[True]] + + +class AllowSeries(_AllowSeries, total=False): + pass_through: bool + + +class AllowSeriesV1(_AllowSeries, total=False): + pass_through: bool | None + eager_or_interchange_only: Literal[False] + + +class AllowSeriesStrictV1(_AllowSeries, total=False): + strict: bool | None + eager_or_interchange_only: Literal[False] + + +class _OnlySeries(TypedDict, total=False): + eager_only: bool + series_only: Required[Literal[True]] + allow_series: bool | None + + +class OnlySeries(_OnlySeries, total=False): + pass_through: bool + + +class OnlySeriesV1(_OnlySeries, total=False): + pass_through: bool | None + eager_or_interchange_only: Literal[False] + + +class OnlySeriesStrictV1(_OnlySeries, total=False): + strict: bool | None + eager_or_interchange_only: Literal[False] + + +class _OnlyEagerOrInterchange(TypedDict, total=False): + eager_or_interchange_only: Required[Literal[True]] + series_only: Literal[False] + allow_series: bool | None + + +class OnlyEagerOrInterchange(_OnlyEagerOrInterchange, total=False): + pass_through: bool | None + + +class OnlyEagerOrInterchangeStrict(_OnlyEagerOrInterchange, total=False): + strict: bool | None + + +class _AllowLazy(TypedDict, total=False): + eager_only: Literal[False] + series_only: Literal[False] + allow_series: bool | None + + +class AllowLazy(_AllowLazy, total=False): + pass_through: bool + + +class AllowLazyV1(_AllowLazy, total=False): + pass_through: bool | None + eager_or_interchange_only: Literal[False] + + +class AllowLazyStrictV1(_AllowLazy, total=False): + strict: bool | None + eager_or_interchange_only: Literal[False] + + +class _AllowAny(TypedDict, total=False): + eager_only: Literal[False] + series_only: Literal[False] + allow_series: Required[Literal[True]] + + +class AllowAny(_AllowAny, total=False): + pass_through: bool + + +class AllowAnyV1(_AllowAny, total=False): + pass_through: bool | None + eager_or_interchange_only: Literal[False] + + +class AllowAnyStrictV1(_AllowAny, total=False): + strict: bool | None + eager_or_interchange_only: Literal[False] + + +class _Unknown(TypedDict, total=False): + eager_only: bool + series_only: bool + allow_series: bool | None + + +class PassThroughUnknown(_Unknown, total=False): + pass_through: Required[Literal[True]] + + +class PassThroughUnknownV1(_Unknown, total=False): + pass_through: Required[Literal[True]] + eager_or_interchange_only: bool + + +class StrictUnknownV1(_Unknown, total=False): + strict: Required[Literal[False]] + eager_or_interchange_only: bool diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_typing.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..c4307c2680beb8caacc1ef6ec9d869ec2f7ce9e1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_typing.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +from types import ModuleType +from typing import TYPE_CHECKING, Literal, Union + +from narwhals._typing_compat import TypeVar +from narwhals._utils import Implementation, _NoDefault + +if TYPE_CHECKING: + from typing_extensions import TypeAlias + +# `str` aliases +_Polars: TypeAlias = Literal["polars"] +_Arrow: TypeAlias = Literal["pyarrow"] +_Dask: TypeAlias = Literal["dask"] +_DuckDB: TypeAlias = Literal["duckdb"] +_Pandas: TypeAlias = Literal["pandas"] +_Modin: TypeAlias = Literal["modin"] +_CuDF: TypeAlias = Literal["cudf"] +_PySpark: TypeAlias = Literal["pyspark"] +_SQLFrame: TypeAlias = Literal["sqlframe"] +_PySparkConnect: TypeAlias = Literal["pyspark[connect]"] +_Ibis: TypeAlias = Literal["ibis"] +_PandasLike: TypeAlias = Literal[_Pandas, _CuDF, _Modin] +_SparkLike: TypeAlias = Literal[_PySpark, _SQLFrame, _PySparkConnect] +_EagerOnly: TypeAlias = Literal[_PandasLike, _Arrow] +_EagerAllowed: TypeAlias = Literal[_Polars, _EagerOnly] +_LazyOnly: TypeAlias = Literal[_SparkLike, _Dask, _DuckDB, _Ibis] +_LazyAllowed: TypeAlias = Literal[_Polars, _LazyOnly] + +# `Implementation` aliases +_PandasImpl: TypeAlias = Literal[Implementation.PANDAS] +_ModinImpl: TypeAlias = Literal[Implementation.MODIN] +_CuDFImpl: TypeAlias = Literal[Implementation.CUDF] +_PySparkImpl: TypeAlias = Literal[Implementation.PYSPARK] +_SQLFrameImpl: TypeAlias = Literal[Implementation.SQLFRAME] +_PySparkConnectImpl: TypeAlias = Literal[Implementation.PYSPARK_CONNECT] +_PolarsImpl: TypeAlias = Literal[Implementation.POLARS] +_ArrowImpl: TypeAlias = Literal[Implementation.PYARROW] +_DaskImpl: TypeAlias = Literal[Implementation.DASK] +_DuckDBImpl: TypeAlias = Literal[Implementation.DUCKDB] +_IbisImpl: TypeAlias = Literal[Implementation.IBIS] +_PandasLikeImpl: TypeAlias = Literal[_PandasImpl, _CuDFImpl, _ModinImpl] +_SparkLikeImpl: TypeAlias = Literal[_PySparkImpl, _SQLFrameImpl, _PySparkConnectImpl] +_EagerOnlyImpl: TypeAlias = Literal[_PandasLikeImpl, _ArrowImpl] +_EagerAllowedImpl: TypeAlias = Literal[_EagerOnlyImpl, _PolarsImpl] # noqa: PYI047 +_LazyOnlyImpl: TypeAlias = Literal[_SparkLikeImpl, _DaskImpl, _DuckDBImpl, _IbisImpl] +_LazyAllowedImpl: TypeAlias = Literal[_LazyOnlyImpl, _PolarsImpl] # noqa: PYI047 + +# NOTE: Temporary aliases for gaps in `LazyFrame.collect`, `DataFrame.lazy`, see: +# - https://github.com/narwhals-dev/narwhals/pull/2971#discussion_r2277137003 +# - https://github.com/narwhals-dev/narwhals/pull/3002#issuecomment-3194267667 +_LazyFrameCollectImpl: TypeAlias = Literal[_PandasImpl, _PolarsImpl, _ArrowImpl] # noqa: PYI047 + +# `str | Implementation` aliases +Pandas: TypeAlias = Literal[_Pandas, _PandasImpl] +CuDF: TypeAlias = Literal[_CuDF, _CuDFImpl] +Modin: TypeAlias = Literal[_Modin, _ModinImpl] +PySpark: TypeAlias = Literal[_PySpark, _PySparkImpl] +SQLFrame: TypeAlias = Literal[_SQLFrame, _SQLFrameImpl] +PySparkConnect: TypeAlias = Literal[_PySparkConnect, _PySparkConnectImpl] +Polars: TypeAlias = Literal[_Polars, _PolarsImpl] +Arrow: TypeAlias = Literal[_Arrow, _ArrowImpl] +Dask: TypeAlias = Literal[_Dask, _DaskImpl] +DuckDB: TypeAlias = Literal[_DuckDB, _DuckDBImpl] +Ibis: TypeAlias = Literal[_Ibis, _IbisImpl] +PandasLike: TypeAlias = Literal[_PandasLike, _PandasLikeImpl] +SparkLike: TypeAlias = Literal[_SparkLike, _SparkLikeImpl] +EagerOnly: TypeAlias = Literal[PandasLike, Arrow] +LazyOnly: TypeAlias = Literal[SparkLike, Dask, DuckDB, Ibis] +EagerAllowed: TypeAlias = Literal[EagerOnly, Polars] +"""A string name or [`narwhals.Implementation`][] of an eager backend. + +- A string name, one of: `"cudf"`, `"modin"`, `"pandas"`, `"pyarrow"`, `"polars"`. +- An Implementation, such as: `Implementation.CUDF`, `Implementation.MODIN`, ... +""" + +LazyAllowed: TypeAlias = Literal[LazyOnly, Polars] +"""A string name or [`narwhals.Implementation`][] of a lazy backend. + +- A string name, such as: `"duckdb"`, `"ibis"`, `"dask"`, `"sqlframe"`, ... +- An Implementation, such as: `Implementation.POLARS`, `Implementation.PYSPARK`, ... +""" + +BackendName: TypeAlias = Literal[_EagerAllowed, _LazyAllowed] +Backend: TypeAlias = Literal[EagerAllowed, LazyAllowed] +"""A string name or [`narwhals.Implementation`][] of a supported +backend (either eager or lazy). + +- A string name, such as: `"duckdb"`, `"ibis"`, `"pandas"`, `"pyarrow"`, `"polars"`, ... +- An Implementation, such as: `Implementation.DASK`, `Implementation.PYSPARK`, ... +""" + +BackendT = TypeVar("BackendT", bound=Backend) +IntoBackend: TypeAlias = Union[BackendT, ModuleType] +"""Anything that can be converted into a [`narwhals.Implementation`][]. + +`backend` can be specified in three ways. + +Examples: + A string backend name, such as: `"pandas"`, `"pyarrow"`, `"modin"`, `"cudf"` + + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> data = {"c": [5, 2], "d": [1, 4]} + >>> nw.DataFrame.from_dict(data, backend="pandas") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | c d | + | 0 5 1 | + | 1 2 4 | + └──────────────────┘ + + An Implementation, such as: `Implementation.POLARS`, `Implementation.DUCKDB`, `Implementation.PYSPARK` + + >>> import narwhals as nw + >>> nw.read_parquet("file.parquet", backend=nw.Implementation.PYARROW) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int64 | + | b: int64 | + | ---- | + | a: [[1,2]] | + | b: [[4,5]] | + └──────────────────┘ + + A python module, such as `dask`, `ibis`, `sqlframe` + + >>> import numpy as np + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> arr = np.arange(5, 10) + >>> nw.Series.from_numpy("arr", arr, dtype=nw.Int8, backend=pl) + ┌──────────────────┐ + | Narwhals Series | + |------------------| + |shape: (5,) | + |Series: 'arr' [i8]| + |[ | + | 5 | + | 6 | + | 7 | + | 8 | + | 9 | + |] | + └──────────────────┘ +""" + +IntoBackendAny: TypeAlias = IntoBackend[Backend] +IntoBackendEager: TypeAlias = IntoBackend[EagerAllowed] +IntoBackendLazy: TypeAlias = IntoBackend[LazyAllowed] + +NoDefault: TypeAlias = Literal[_NoDefault.no_default] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_typing_compat.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_typing_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..47cbf3464a13d49cd54a15fdf303dba33d6b6f4e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_typing_compat.py @@ -0,0 +1,86 @@ +"""Backward compatibility for newer/less buggy typing features. + +## Important +Import from here to avoid introducing a runtime dependency on [`typing_extensions`] + +## Notes +- `TypeVar` defaults + - https://typing.python.org/en/latest/spec/generics.html#type-parameter-defaults + - https://peps.python.org/pep-0696/ +- `@deprecated` + - https://docs.python.org/3/library/warnings.html#warnings.deprecated + - https://typing.python.org/en/latest/spec/directives.html#deprecated + - https://peps.python.org/pep-0702/ + +[`typing_extensions`]: https://github.com/python/typing_extensions +""" + +from __future__ import annotations + +# ruff: noqa: ARG001, ANN202, N802 +import sys +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from typing import Callable + + if sys.version_info >= (3, 13): + from typing import TypeVar + from warnings import deprecated + else: + from typing_extensions import TypeVar, deprecated + + if sys.version_info >= (3, 11): + from typing import Never, assert_never + else: + from typing_extensions import Never, assert_never + + _Fn = TypeVar("_Fn", bound=Callable[..., Any]) + + +else: # pragma: no cover + if sys.version_info >= (3, 13): + from typing import TypeVar + from warnings import deprecated + else: + from typing import TypeVar as _TypeVar + + def TypeVar( + name: str, + *constraints: Any, + bound: Any | None = None, + covariant: bool = False, + contravariant: bool = False, + **kwds: Any, + ): + return _TypeVar( + name, + *constraints, + bound=bound, + covariant=covariant, + contravariant=contravariant, + ) + + def deprecated(message: str, /) -> Callable[[_Fn], _Fn]: + def wrapper(func: _Fn, /) -> _Fn: + return func + + return wrapper + + _ASSERT_NEVER_REPR_MAX_LENGTH = 100 + _BUG_URL = ( + "https://github.com/narwhals-dev/narwhals/issues/new?template=bug_report.yml" + ) + + def assert_never(arg: Never, /) -> Never: + value = repr(arg) + if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: + value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + "..." + msg = ( + f"Expected code to be unreachable, but got: {value}.\n" + f"Please report an issue at {_BUG_URL}" + ) + raise AssertionError(msg) + + +__all__ = ["TypeVar", "assert_never", "deprecated"] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/_utils.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..70b6f5d342b69ce0b1855a81871bc86b2c8a75fc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/_utils.py @@ -0,0 +1,2165 @@ +from __future__ import annotations + +import os +import re +import sys +from collections.abc import Collection, Container, Iterable, Iterator, Mapping, Sequence +from datetime import timezone +from enum import Enum, auto +from functools import cache, lru_cache, partial, wraps +from importlib.util import find_spec +from inspect import getattr_static, getdoc +from itertools import chain +from operator import attrgetter +from pathlib import Path +from secrets import token_hex +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Final, + Generic, + Literal, + Protocol, + TypeVar, + Union, + cast, + overload, +) + +from narwhals._enum import NoAutoEnum +from narwhals._exceptions import issue_deprecation_warning +from narwhals._typing_compat import assert_never, deprecated +from narwhals.dependencies import ( + get_cudf, + get_dask_dataframe, + get_duckdb, + get_ibis, + get_modin, + get_pandas, + get_polars, + get_pyarrow, + get_pyspark_connect, + get_pyspark_sql, + get_sqlframe, + is_narwhals_series, + is_narwhals_series_bool, + is_narwhals_series_int, + is_numpy_array_1d, + is_numpy_array_1d_bool, + is_numpy_array_1d_int, + is_pandas_like_dataframe, + is_pandas_like_series, +) +from narwhals.exceptions import ColumnNotFoundError, DuplicateError, InvalidOperationError + +if TYPE_CHECKING: + from collections.abc import Set # noqa: PYI025 + from types import ModuleType + + import pandas as pd + import polars as pl + import pyarrow as pa + from typing_extensions import ( + Concatenate, + LiteralString, + ParamSpec, + Self, + TypeAlias, + TypeIs, + ) + + from narwhals._compliant import CompliantExprT, CompliantSeriesT, NativeSeriesT_co + from narwhals._compliant.any_namespace import NamespaceAccessor + from narwhals._compliant.typing import ( + Accessor, + EvalNames, + NativeDataFrameT, + NativeLazyFrameT, + ) + from narwhals._namespace import Namespace + from narwhals._native import ( + NativeArrow, + NativeCuDF, + NativeDask, + NativeDuckDB, + NativeIbis, + NativeModin, + NativePandas, + NativePandasLike, + NativePolars, + NativePySpark, + NativePySparkConnect, + NativeSQLFrame, + ) + from narwhals._translate import ArrowStreamExportable, IntoArrowTable, ToNarwhalsT_co + from narwhals._typing import ( + Backend, + IntoBackend, + _ArrowImpl, + _CuDFImpl, + _DaskImpl, + _DuckDBImpl, + _EagerAllowedImpl, + _IbisImpl, + _LazyAllowedImpl, + _LazyFrameCollectImpl, + _ModinImpl, + _PandasImpl, + _PandasLikeImpl, + _PolarsImpl, + _PySparkConnectImpl, + _PySparkImpl, + _SQLFrameImpl, + ) + from narwhals.dataframe import DataFrame, LazyFrame + from narwhals.dtypes import DType + from narwhals.series import Series + from narwhals.typing import ( + CompliantDataFrame, + CompliantLazyFrame, + CompliantSeries, + DTypes, + FileSource, + IntoSeriesT, + MultiIndexSelector, + NestedLiteral, + SingleIndexSelector, + SizedMultiBoolSelector, + SizedMultiIndexSelector, + SizeUnit, + SupportsNativeNamespace, + TimeUnit, + _1DArray, + _SliceIndex, + _SliceName, + _SliceNone, + ) + + UnknownBackendName: TypeAlias = str + + FrameOrSeriesT = TypeVar( + "FrameOrSeriesT", bound=Union[LazyFrame[Any], DataFrame[Any], Series[Any]] + ) + + _T1 = TypeVar("_T1") + _T2 = TypeVar("_T2") + _T3 = TypeVar("_T3") + _Fn = TypeVar("_Fn", bound="Callable[..., Any]") + P = ParamSpec("P") + R = TypeVar("R") + R1 = TypeVar("R1") + R2 = TypeVar("R2") + + class _SupportsVersion(Protocol): + __version__: str + + class _SupportsGet(Protocol): # noqa: PYI046 + def __get__(self, instance: Any, owner: Any | None = None, /) -> Any: ... + + class _StoresColumns(Protocol): + @property + def columns(self) -> Sequence[str]: ... + + +_T = TypeVar("_T") +NativeT_co = TypeVar("NativeT_co", covariant=True) +CompliantT_co = TypeVar("CompliantT_co", covariant=True) +_IntoContext: TypeAlias = "_FullContext | NamespaceAccessor[_FullContext]" +_IntoContextT = TypeVar("_IntoContextT", bound=_IntoContext) +_Method: TypeAlias = "Callable[Concatenate[_IntoContextT, P], R]" +_Constructor: TypeAlias = "Callable[Concatenate[_T, P], R2]" + + +class _StoresNative(Protocol[NativeT_co]): + """Provides access to a native object. + + Native objects have types like: + + >>> from pandas import Series + >>> from pyarrow import Table + """ + + @property + def native(self) -> NativeT_co: + """Return the native object.""" + ... + + +class _StoresCompliant(Protocol[CompliantT_co]): # noqa: PYI046 + """Provides access to a compliant object. + + Compliant objects have types like: + + >>> from narwhals._pandas_like.series import PandasLikeSeries + >>> from narwhals._arrow.dataframe import ArrowDataFrame + """ + + @property + def compliant(self) -> CompliantT_co: + """Return the compliant object.""" + ... + + +class _StoresBackendVersion(Protocol): + @property + def _backend_version(self) -> tuple[int, ...]: + """Version tuple for a native package.""" + ... + + +class _StoresVersion(Protocol): + _version: Version + """Narwhals API version (V1 or MAIN).""" + + +class _StoresImplementation(Protocol): + _implementation: Implementation + """Implementation of native object (pandas, Polars, PyArrow, ...).""" + + +class _LimitedContext(_StoresImplementation, _StoresVersion, Protocol): + """Provides 2 attributes. + + - `_implementation` + - `_version` + """ + + +class _FullContext(_StoresImplementation, _StoresBackendVersion, Protocol): + """Provides 2 attributes. + + - `_implementation` + - `_backend_version` + """ + + +class ValidateBackendVersion(_StoresImplementation, Protocol): + """Ensure the target `Implementation` is on a supported version.""" + + def _validate_backend_version(self) -> None: + """Raise if installed version below `nw._utils.MIN_VERSIONS`. + + **Only use this when moving between backends.** + Otherwise, the validation will have taken place already. + """ + _ = self._implementation._backend_version() + + +class Version(Enum): + V1 = auto() + V2 = auto() + MAIN = auto() + + @property + def namespace(self) -> type[Namespace[Any]]: + if self is Version.V1: + from narwhals.stable.v1._namespace import Namespace as NamespaceV1 + + return NamespaceV1 + if self is Version.V2: + from narwhals.stable.v2._namespace import Namespace as NamespaceV2 + + return NamespaceV2 + from narwhals._namespace import Namespace + + return Namespace + + @property + def dtypes(self) -> DTypes: + if self is Version.V1: + from narwhals.stable.v1 import dtypes as dtypes_v1 + + return dtypes_v1 + if self is Version.V2: + from narwhals.stable.v2 import dtypes as dtypes_v2 + + return dtypes_v2 + from narwhals import dtypes + + return dtypes + + @property + def dataframe(self) -> type[DataFrame[Any]]: + if self is Version.V1: + from narwhals.stable.v1 import DataFrame as DataFrameV1 + + return DataFrameV1 + if self is Version.V2: + from narwhals.stable.v2 import DataFrame as DataFrameV2 + + return DataFrameV2 + from narwhals.dataframe import DataFrame + + return DataFrame + + @property + def lazyframe(self) -> type[LazyFrame[Any]]: + if self is Version.V1: + from narwhals.stable.v1 import LazyFrame as LazyFrameV1 + + return LazyFrameV1 + if self is Version.V2: + from narwhals.stable.v2 import LazyFrame as LazyFrameV2 + + return LazyFrameV2 + from narwhals.dataframe import LazyFrame + + return LazyFrame + + @property + def series(self) -> type[Series[Any]]: + if self is Version.V1: + from narwhals.stable.v1 import Series as SeriesV1 + + return SeriesV1 + if self is Version.V2: + from narwhals.stable.v2 import Series as SeriesV2 + + return SeriesV2 + from narwhals.series import Series + + return Series + + +class Implementation(NoAutoEnum): + """Implementation of native object (pandas, Polars, PyArrow, ...).""" + + PANDAS = "pandas" + """pandas implementation.""" + MODIN = "modin" + """Modin implementation.""" + CUDF = "cudf" + """cuDF implementation.""" + PYARROW = "pyarrow" + """PyArrow implementation.""" + PYSPARK = "pyspark" + """PySpark implementation.""" + POLARS = "polars" + """Polars implementation.""" + DASK = "dask" + """Dask implementation.""" + DUCKDB = "duckdb" + """DuckDB implementation.""" + IBIS = "ibis" + """Ibis implementation.""" + SQLFRAME = "sqlframe" + """SQLFrame implementation.""" + PYSPARK_CONNECT = "pyspark[connect]" + """PySpark Connect implementation.""" + UNKNOWN = "unknown" + """Unknown implementation.""" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def from_native_namespace( + cls: type[Self], native_namespace: ModuleType + ) -> Implementation: # pragma: no cover + """Instantiate Implementation object from a native namespace module. + + Arguments: + native_namespace: Native namespace. + """ + mapping = { + get_pandas(): Implementation.PANDAS, + get_modin(): Implementation.MODIN, + get_cudf(): Implementation.CUDF, + get_pyarrow(): Implementation.PYARROW, + get_pyspark_sql(): Implementation.PYSPARK, + get_polars(): Implementation.POLARS, + get_dask_dataframe(): Implementation.DASK, + get_duckdb(): Implementation.DUCKDB, + get_ibis(): Implementation.IBIS, + get_sqlframe(): Implementation.SQLFRAME, + get_pyspark_connect(): Implementation.PYSPARK_CONNECT, + } + return mapping.get(native_namespace, Implementation.UNKNOWN) + + @classmethod + def from_string(cls: type[Self], backend_name: str) -> Implementation: + """Instantiate Implementation object from a native namespace module. + + Arguments: + backend_name: Name of backend, expressed as string. + """ + try: + return cls(backend_name) + except ValueError: + return Implementation.UNKNOWN + + @classmethod + def from_backend( + cls: type[Self], backend: IntoBackend[Backend] | UnknownBackendName + ) -> Implementation: + """Instantiate from native namespace module, string, or Implementation. + + Arguments: + backend: Backend to instantiate Implementation from. + """ + return ( + cls.from_string(backend) + if isinstance(backend, str) + else backend + if isinstance(backend, Implementation) + else cls.from_native_namespace(backend) + ) + + def to_native_namespace(self) -> ModuleType: + """Return the native namespace module corresponding to Implementation.""" + if self is Implementation.UNKNOWN: + msg = "Cannot return native namespace from UNKNOWN Implementation" + raise AssertionError(msg) + + self._backend_version() + module_name = _IMPLEMENTATION_TO_MODULE_NAME.get(self, self.value) + return _import_native_namespace(module_name) + + def is_pandas(self) -> bool: + """Return whether implementation is pandas. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_pandas() + True + """ + return self is Implementation.PANDAS + + def is_pandas_like(self) -> bool: + """Return whether implementation is pandas, Modin, or cuDF. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_pandas_like() + True + """ + return self in {Implementation.PANDAS, Implementation.MODIN, Implementation.CUDF} + + def is_spark_like(self) -> bool: + """Return whether implementation is pyspark or sqlframe. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_spark_like() + False + """ + return self in { + Implementation.PYSPARK, + Implementation.SQLFRAME, + Implementation.PYSPARK_CONNECT, + } + + def is_polars(self) -> bool: + """Return whether implementation is Polars. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_polars() + True + """ + return self is Implementation.POLARS + + def is_cudf(self) -> bool: + """Return whether implementation is cuDF. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_cudf() + False + """ + return self is Implementation.CUDF # pragma: no cover + + def is_modin(self) -> bool: + """Return whether implementation is Modin. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_modin() + False + """ + return self is Implementation.MODIN # pragma: no cover + + def is_pyspark(self) -> bool: + """Return whether implementation is PySpark. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_pyspark() + False + """ + return self is Implementation.PYSPARK # pragma: no cover + + def is_pyspark_connect(self) -> bool: + """Return whether implementation is PySpark. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_pyspark_connect() + False + """ + return self is Implementation.PYSPARK_CONNECT # pragma: no cover + + def is_pyarrow(self) -> bool: + """Return whether implementation is PyArrow. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_pyarrow() + False + """ + return self is Implementation.PYARROW # pragma: no cover + + def is_dask(self) -> bool: + """Return whether implementation is Dask. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_dask() + False + """ + return self is Implementation.DASK # pragma: no cover + + def is_duckdb(self) -> bool: + """Return whether implementation is DuckDB. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_duckdb() + False + """ + return self is Implementation.DUCKDB # pragma: no cover + + def is_ibis(self) -> bool: + """Return whether implementation is Ibis. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_ibis() + False + """ + return self is Implementation.IBIS # pragma: no cover + + def is_sqlframe(self) -> bool: + """Return whether implementation is SQLFrame. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation.is_sqlframe() + False + """ + return self is Implementation.SQLFRAME # pragma: no cover + + def _backend_version(self) -> tuple[int, ...]: + """Returns backend version.""" + return backend_version(self) + + +def is_pyspark_pre_4(implementation: Implementation) -> bool: + """Whether implementation is PySpark (or PySpark Connect) with version < 4.0.""" + return ( + implementation.is_pyspark() or implementation.is_pyspark_connect() + ) and implementation._backend_version() < (4, 0) + + +MIN_VERSIONS: Mapping[Implementation, tuple[int, ...]] = { + Implementation.PANDAS: (1, 1, 3), + Implementation.MODIN: (0, 8, 2), + Implementation.CUDF: (24, 10), + Implementation.PYARROW: (13,), + Implementation.PYSPARK: (3, 5), + Implementation.PYSPARK_CONNECT: (3, 5), + Implementation.POLARS: (0, 20, 4), + Implementation.DASK: (2024, 8), + Implementation.DUCKDB: (1, 1), + Implementation.IBIS: (6,), + Implementation.SQLFRAME: (3, 22, 0), +} + +_IMPLEMENTATION_TO_MODULE_NAME: Mapping[Implementation, str] = { + Implementation.DASK: "dask.dataframe", + Implementation.MODIN: "modin.pandas", + Implementation.PYSPARK: "pyspark.sql", + Implementation.PYSPARK_CONNECT: "pyspark.sql.connect", +} +"""Stores non default mapping from Implementation to module name""" + + +@lru_cache(maxsize=16) +def _import_native_namespace(module_name: str) -> ModuleType: + from importlib import import_module + + return import_module(module_name) + + +# NOTE: We can safely use an unbounded cache, the size is constrained by `len(Implementation._member_names_)` +# Faster than `lru_cache` +# https://docs.python.org/3/library/functools.html#functools.cache +@cache +def backend_version(implementation: Implementation, /) -> tuple[int, ...]: + if not isinstance(implementation, Implementation): + assert_never(implementation) + if implementation is Implementation.UNKNOWN: + return (0, 0, 0) + into_version: ModuleType | str + impl = implementation + module_name = _IMPLEMENTATION_TO_MODULE_NAME.get(impl, impl.value) + native_namespace = _import_native_namespace(module_name) + if impl.is_sqlframe(): + import sqlframe._version + + into_version = sqlframe._version + elif impl.is_pyspark() or impl.is_pyspark_connect(): # pragma: no cover + import pyspark # ignore-banned-import + + into_version = pyspark + elif impl.is_dask(): + import dask # ignore-banned-import + + into_version = dask + else: + into_version = native_namespace + version = parse_version(into_version) + if version < (min_version := MIN_VERSIONS[impl]): + msg = f"Minimum version of {impl} supported by Narwhals is {min_version}, found: {version}" + raise ValueError(msg) + return version + + +def flatten(args: Any) -> list[Any]: + return list(args[0] if (len(args) == 1 and _is_iterable(args[0])) else args) + + +def tupleify(arg: Any) -> Any: + if not isinstance(arg, (list, tuple)): # pragma: no cover + return (arg,) + return arg + + +def _is_iterable(arg: Any | Iterable[Any]) -> bool: + from narwhals.series import Series + + if ( + (pd := get_pandas()) is not None and isinstance(arg, (pd.Series, pd.DataFrame)) + ) or ( + (pl := get_polars()) is not None + and isinstance(arg, (pl.Series, pl.Expr, pl.DataFrame, pl.LazyFrame)) + ): + # Non-exhaustive check for common potential mistakes. + msg = ( + f"Expected Narwhals class or scalar, got: {qualified_type_name(arg)!r}.\n\n" + "Hint: Perhaps you\n" + "- forgot a `nw.from_native` somewhere?\n" + "- used `pl.col` instead of `nw.col`?" + ) + raise TypeError(msg) + + return isinstance(arg, Iterable) and not isinstance(arg, (str, bytes, Series)) + + +def is_iterator(val: Iterable[_T] | Any) -> TypeIs[Iterator[_T]]: + return isinstance(val, Iterator) + + +def parse_version(version: str | ModuleType | _SupportsVersion) -> tuple[int, ...]: + """Simple version parser; split into a tuple of ints for comparison. + + Arguments: + version: Version string, or object with one, to parse. + """ + # lifted from Polars + # [marco]: Take care of DuckDB pre-releases which end with e.g. `-dev4108` + # and pandas pre-releases which end with e.g. .dev0+618.gb552dc95c9 + version_str = version if isinstance(version, str) else version.__version__ + version_str = re.sub(r"(\D?dev.*$)", "", version_str) + return tuple(int(re.sub(r"\D", "", v)) for v in version_str.split(".")) + + +@overload +def isinstance_or_issubclass( + obj_or_cls: type, cls_or_tuple: type[_T] +) -> TypeIs[type[_T]]: ... + + +@overload +def isinstance_or_issubclass( + obj_or_cls: object | type, cls_or_tuple: type[_T] +) -> TypeIs[_T | type[_T]]: ... + + +@overload +def isinstance_or_issubclass( + obj_or_cls: type, cls_or_tuple: tuple[type[_T1], type[_T2]] +) -> TypeIs[type[_T1 | _T2]]: ... + + +@overload +def isinstance_or_issubclass( + obj_or_cls: object | type, cls_or_tuple: tuple[type[_T1], type[_T2]] +) -> TypeIs[_T1 | _T2 | type[_T1 | _T2]]: ... + + +@overload +def isinstance_or_issubclass( + obj_or_cls: type, cls_or_tuple: tuple[type[_T1], type[_T2], type[_T3]] +) -> TypeIs[type[_T1 | _T2 | _T3]]: ... + + +@overload +def isinstance_or_issubclass( + obj_or_cls: object | type, cls_or_tuple: tuple[type[_T1], type[_T2], type[_T3]] +) -> TypeIs[_T1 | _T2 | _T3 | type[_T1 | _T2 | _T3]]: ... + + +@overload +def isinstance_or_issubclass( + obj_or_cls: Any, cls_or_tuple: tuple[type, ...] +) -> TypeIs[Any]: ... + + +def isinstance_or_issubclass(obj_or_cls: Any, cls_or_tuple: Any) -> bool: + from narwhals.dtypes import DType + + if isinstance(obj_or_cls, DType): + return isinstance(obj_or_cls, cls_or_tuple) + return isinstance(obj_or_cls, cls_or_tuple) or ( + isinstance(obj_or_cls, type) and issubclass(obj_or_cls, cls_or_tuple) + ) + + +def validate_laziness(items: Iterable[Any]) -> None: + from narwhals.dataframe import DataFrame, LazyFrame + + if all(isinstance(item, DataFrame) for item in items) or ( + all(isinstance(item, LazyFrame) for item in items) + ): + return + msg = f"The items to concatenate should either all be eager, or all lazy, got: {[type(item) for item in items]}" + raise TypeError(msg) + + +def maybe_align_index( + lhs: FrameOrSeriesT, rhs: Series[Any] | DataFrame[Any] | LazyFrame[Any] +) -> FrameOrSeriesT: + """Align `lhs` to the Index of `rhs`, if they're both pandas-like. + + Arguments: + lhs: Dataframe or Series. + rhs: Dataframe or Series to align with. + + Notes: + This is only really intended for backwards-compatibility purposes, + for example if your library already aligns indices for users. + If you're designing a new library, we highly encourage you to not + rely on the Index. + For non-pandas-like inputs, this only checks that `lhs` and `rhs` + are the same length. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> df_pd = pd.DataFrame({"a": [1, 2]}, index=[3, 4]) + >>> s_pd = pd.Series([6, 7], index=[4, 3]) + >>> df = nw.from_native(df_pd) + >>> s = nw.from_native(s_pd, series_only=True) + >>> nw.to_native(nw.maybe_align_index(df, s)) + a + 4 2 + 3 1 + """ + from narwhals._pandas_like.dataframe import PandasLikeDataFrame + from narwhals._pandas_like.series import PandasLikeSeries + + def _validate_index(index: Any) -> None: + if not index.is_unique: + msg = "given index doesn't have a unique index" + raise ValueError(msg) + + lhs_any = cast("Any", lhs) + rhs_any = cast("Any", rhs) + if isinstance( + getattr(lhs_any, "_compliant_frame", None), PandasLikeDataFrame + ) and isinstance(getattr(rhs_any, "_compliant_frame", None), PandasLikeDataFrame): + _validate_index(lhs_any._compliant_frame.native.index) + _validate_index(rhs_any._compliant_frame.native.index) + return lhs_any._with_compliant( + lhs_any._compliant_frame._with_native( + lhs_any._compliant_frame.native.loc[rhs_any._compliant_frame.native.index] + ) + ) + if isinstance( + getattr(lhs_any, "_compliant_frame", None), PandasLikeDataFrame + ) and isinstance(getattr(rhs_any, "_compliant_series", None), PandasLikeSeries): + _validate_index(lhs_any._compliant_frame.native.index) + _validate_index(rhs_any._compliant_series.native.index) + return lhs_any._with_compliant( + lhs_any._compliant_frame._with_native( + lhs_any._compliant_frame.native.loc[ + rhs_any._compliant_series.native.index + ] + ) + ) + if isinstance( + getattr(lhs_any, "_compliant_series", None), PandasLikeSeries + ) and isinstance(getattr(rhs_any, "_compliant_frame", None), PandasLikeDataFrame): + _validate_index(lhs_any._compliant_series.native.index) + _validate_index(rhs_any._compliant_frame.native.index) + return lhs_any._with_compliant( + lhs_any._compliant_series._with_native( + lhs_any._compliant_series.native.loc[ + rhs_any._compliant_frame.native.index + ] + ) + ) + if isinstance( + getattr(lhs_any, "_compliant_series", None), PandasLikeSeries + ) and isinstance(getattr(rhs_any, "_compliant_series", None), PandasLikeSeries): + _validate_index(lhs_any._compliant_series.native.index) + _validate_index(rhs_any._compliant_series.native.index) + return lhs_any._with_compliant( + lhs_any._compliant_series._with_native( + lhs_any._compliant_series.native.loc[ + rhs_any._compliant_series.native.index + ] + ) + ) + if len(lhs_any) != len(rhs_any): + msg = f"Expected `lhs` and `rhs` to have the same length, got {len(lhs_any)} and {len(rhs_any)}" + raise ValueError(msg) + return lhs + + +def maybe_get_index(obj: DataFrame[Any] | LazyFrame[Any] | Series[Any]) -> Any | None: + """Get the index of a DataFrame or a Series, if it's pandas-like. + + Arguments: + obj: Dataframe or Series. + + Notes: + This is only really intended for backwards-compatibility purposes, + for example if your library already aligns indices for users. + If you're designing a new library, we highly encourage you to not + rely on the Index. + For non-pandas-like inputs, this returns `None`. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> df_pd = pd.DataFrame({"a": [1, 2], "b": [4, 5]}) + >>> df = nw.from_native(df_pd) + >>> nw.maybe_get_index(df) + RangeIndex(start=0, stop=2, step=1) + >>> series_pd = pd.Series([1, 2]) + >>> series = nw.from_native(series_pd, series_only=True) + >>> nw.maybe_get_index(series) + RangeIndex(start=0, stop=2, step=1) + """ + obj_any = cast("Any", obj) + native_obj = obj_any.to_native() + if is_pandas_like_dataframe(native_obj) or is_pandas_like_series(native_obj): + return native_obj.index + return None + + +def maybe_set_index( + obj: FrameOrSeriesT, + column_names: str | list[str] | None = None, + *, + index: Series[IntoSeriesT] | list[Series[IntoSeriesT]] | None = None, +) -> FrameOrSeriesT: + """Set the index of a DataFrame or a Series, if it's pandas-like. + + Arguments: + obj: object for which maybe set the index (can be either a Narwhals `DataFrame` + or `Series`). + column_names: name or list of names of the columns to set as index. + For dataframes, only one of `column_names` and `index` can be specified but + not both. If `column_names` is passed and `df` is a Series, then a + `ValueError` is raised. + index: series or list of series to set as index. + + Raises: + ValueError: If one of the following conditions happens + + - none of `column_names` and `index` are provided + - both `column_names` and `index` are provided + - `column_names` is provided and `df` is a Series + + Notes: + This is only really intended for backwards-compatibility purposes, for example if + your library already aligns indices for users. + If you're designing a new library, we highly encourage you to not + rely on the Index. + + For non-pandas-like inputs, this is a no-op. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> df_pd = pd.DataFrame({"a": [1, 2], "b": [4, 5]}) + >>> df = nw.from_native(df_pd) + >>> nw.to_native(nw.maybe_set_index(df, "b")) # doctest: +NORMALIZE_WHITESPACE + a + b + 4 1 + 5 2 + """ + from narwhals.translate import to_native + + df_any = cast("Any", obj) + native_obj = df_any.to_native() + + if column_names is not None and index is not None: + msg = "Only one of `column_names` or `index` should be provided" + raise ValueError(msg) + + if not column_names and index is None: + msg = "Either `column_names` or `index` should be provided" + raise ValueError(msg) + + if index is not None: + keys = ( + [to_native(idx, pass_through=True) for idx in index] + if _is_iterable(index) + else to_native(index, pass_through=True) + ) + else: + keys = column_names + + if is_pandas_like_dataframe(native_obj): + return df_any._with_compliant( + df_any._compliant_frame._with_native(native_obj.set_index(keys)) + ) + if is_pandas_like_series(native_obj): + from narwhals._pandas_like.utils import set_index + + if column_names: + msg = "Cannot set index using column names on a Series" + raise ValueError(msg) + + native_obj = set_index( + native_obj, + keys, + implementation=obj._compliant_series._implementation, # type: ignore[union-attr] + ) + return df_any._with_compliant(df_any._compliant_series._with_native(native_obj)) + return df_any + + +def maybe_reset_index(obj: FrameOrSeriesT) -> FrameOrSeriesT: + """Reset the index to the default integer index of a DataFrame or a Series, if it's pandas-like. + + Arguments: + obj: Dataframe or Series. + + Notes: + This is only really intended for backwards-compatibility purposes, + for example if your library already resets the index for users. + If you're designing a new library, we highly encourage you to not + rely on the Index. + For non-pandas-like inputs, this is a no-op. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> df_pd = pd.DataFrame({"a": [1, 2], "b": [4, 5]}, index=([6, 7])) + >>> df = nw.from_native(df_pd) + >>> nw.to_native(nw.maybe_reset_index(df)) + a b + 0 1 4 + 1 2 5 + >>> series_pd = pd.Series([1, 2]) + >>> series = nw.from_native(series_pd, series_only=True) + >>> nw.maybe_get_index(series) + RangeIndex(start=0, stop=2, step=1) + """ + obj_any = cast("Any", obj) + native_obj = obj_any.to_native() + if is_pandas_like_dataframe(native_obj): + native_namespace = obj_any.__native_namespace__() + if _has_default_index(native_obj, native_namespace): + return obj_any + return obj_any._with_compliant( + obj_any._compliant_frame._with_native(native_obj.reset_index(drop=True)) + ) + if is_pandas_like_series(native_obj): + native_namespace = obj_any.__native_namespace__() + if _has_default_index(native_obj, native_namespace): + return obj_any + return obj_any._with_compliant( + obj_any._compliant_series._with_native(native_obj.reset_index(drop=True)) + ) + return obj_any + + +if TYPE_CHECKING: + zip_strict = partial(zip, strict=True) +else: + import sys + + if sys.version_info >= (3, 10): + zip_strict = partial(zip, strict=True) + else: # pragma: no cover + # https://stackoverflow.com/questions/32954486/zip-iterators-asserting-for-equal-length-in-python/69485272#69485272 + + def zip_strict(*iterables: Iterable[Any]) -> Iterable[tuple[Any, ...]]: + # For trivial cases, use pure zip. + if len(iterables) < 2: + return zip(*iterables) + # Tail for the first iterable + first_stopped = False + + def first_tail() -> Any: + nonlocal first_stopped + first_stopped = True + return + yield + + # Tail for the zip + def zip_tail() -> Any: + if not first_stopped: # pragma: no cover + msg = "zip_strict: first iterable is longer" + raise ValueError(msg) + for _ in chain.from_iterable(rest): # pragma: no cover + msg = "zip_strict: first iterable is shorter" + raise ValueError(msg) + yield + + # Put the pieces together + iterables_it = iter(iterables) + first = chain(next(iterables_it), first_tail()) + rest = list(map(iter, iterables_it)) + return chain(zip(first, *rest), zip_tail()) + + +def _is_range_index(obj: Any, native_namespace: Any) -> TypeIs[pd.RangeIndex]: + return isinstance(obj, native_namespace.RangeIndex) + + +def _has_default_index( + native_frame_or_series: pd.Series[Any] | pd.DataFrame, native_namespace: Any +) -> bool: + index = native_frame_or_series.index + return ( + _is_range_index(index, native_namespace) + and index.start == 0 + and index.stop == len(index) + and index.step == 1 + ) + + +def maybe_convert_dtypes( + obj: FrameOrSeriesT, *args: bool, **kwargs: bool | str +) -> FrameOrSeriesT: + """Convert columns or series to the best possible dtypes using dtypes supporting ``pd.NA``, if df is pandas-like. + + Arguments: + obj: DataFrame or Series. + *args: Additional arguments which gets passed through. + **kwargs: Additional arguments which gets passed through. + + Notes: + For non-pandas-like inputs, this is a no-op. + Also, `args` and `kwargs` just get passed down to the underlying library as-is. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> import numpy as np + >>> df_pd = pd.DataFrame( + ... { + ... "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")), + ... "b": pd.Series([True, False, np.nan], dtype=np.dtype("O")), + ... } + ... ) + >>> df = nw.from_native(df_pd) + >>> nw.to_native( + ... nw.maybe_convert_dtypes(df) + ... ).dtypes # doctest: +NORMALIZE_WHITESPACE + a Int32 + b boolean + dtype: object + """ + if not obj.implementation.is_pandas_like(): + return obj + result = obj._with_compliant( + obj._compliant._with_native(obj.to_native().convert_dtypes(*args, **kwargs)) + ) + return cast("FrameOrSeriesT", result) + + +def scale_bytes(sz: int, unit: SizeUnit) -> int | float: + """Scale size in bytes to other size units (eg: "kb", "mb", "gb", "tb"). + + Arguments: + sz: original size in bytes + unit: size unit to convert into + """ + if unit in {"b", "bytes"}: + return sz + if unit in {"kb", "kilobytes"}: + return sz / 1024 + if unit in {"mb", "megabytes"}: + return sz / 1024**2 + if unit in {"gb", "gigabytes"}: + return sz / 1024**3 + if unit in {"tb", "terabytes"}: + return sz / 1024**4 + msg = f"`unit` must be one of {{'b', 'kb', 'mb', 'gb', 'tb'}}, got {unit!r}" + raise ValueError(msg) + + +def is_ordered_categorical(series: Series[Any]) -> bool: + """Return whether indices of categories are semantically meaningful. + + This is a convenience function to accessing what would otherwise be + the `is_ordered` property from the DataFrame Interchange Protocol, + see https://data-apis.org/dataframe-protocol/latest/API.html. + + - For Polars: + - Enums are always ordered. + - Categoricals are ordered if `dtype.ordering == "physical"`. + - For pandas-like APIs: + - Categoricals are ordered if `dtype.cat.ordered == True`. + - For PyArrow table: + - Categoricals are ordered if `dtype.type.ordered == True`. + + Arguments: + series: Input Series. + + Examples: + >>> import narwhals as nw + >>> import pandas as pd + >>> import polars as pl + >>> data = ["x", "y"] + >>> + >>> s_pd = nw.from_native( + ... pd.Series(data, dtype=pd.CategoricalDtype(ordered=True)), series_only=True + ... ) + >>> nw.is_ordered_categorical(s_pd) + True + >>> s_pl = nw.from_native( + ... pl.Series(data, dtype=pl.Categorical()), series_only=True + ... ) + >>> nw.is_ordered_categorical(s_pl) + False + """ + from narwhals._interchange.series import InterchangeSeries + + dtypes = series._compliant_series._version.dtypes + compliant = series._compliant_series + # If it doesn't match any branches, let's just play it safe and return False. + result: bool = False + if isinstance(compliant, InterchangeSeries) and isinstance( + series.dtype, dtypes.Categorical + ): + result = compliant.native.describe_categorical["is_ordered"] + elif series.dtype == dtypes.Enum: + result = True + elif series.dtype != dtypes.Categorical: + result = False + else: + native = series.to_native() + impl = series.implementation + if impl.is_polars() and impl._backend_version() < (1, 32): + # NOTE: Deprecated https://github.com/pola-rs/polars/pull/23779 + # Since version 1.32.0, ordering parameter is ignored and + # it always behaves as if 'lexical' was passed. + result = cast("pl.Categorical", native.dtype).ordering == "physical" + elif impl.is_pandas_like(): + result = bool(native.cat.ordered) + elif impl.is_pyarrow(): + from narwhals._arrow.utils import is_dictionary + + result = is_dictionary(native.type) and native.type.ordered + return result + + +def generate_unique_token( + n_bytes: int, columns: Container[str], prefix: str = "nw" +) -> str: # pragma: no cover + msg = ( + "Use `generate_temporary_column_name` instead. `generate_unique_token` is " + "deprecated and it will be removed in future versions" + ) + issue_deprecation_warning(msg, _version="1.13.0") + return generate_temporary_column_name(n_bytes=n_bytes, columns=columns, prefix=prefix) + + +def generate_temporary_column_name( + n_bytes: int, columns: Container[str], prefix: str = "nw" +) -> str: + """Generates a unique column name that is not present in the given list of columns. + + It relies on [python secrets token_hex](https://docs.python.org/3/library/secrets.html#secrets.token_hex) + function to return a string nbytes random bytes. + + Arguments: + n_bytes: The number of bytes to generate for the token. + columns: The list of columns to check for uniqueness. + prefix: prefix with which the temporary column name should start with. + + Returns: + A unique token that is not present in the given list of columns. + + Raises: + AssertionError: If a unique token cannot be generated after 100 attempts. + + Examples: + >>> import narwhals as nw + >>> columns = ["abc", "xyz"] + >>> nw.generate_temporary_column_name(n_bytes=8, columns=columns) not in columns + True + >>> temp_name = nw.generate_temporary_column_name( + ... n_bytes=8, columns=columns, prefix="foo" + ... ) + >>> temp_name not in columns and temp_name.startswith("foo") + True + """ + counter = 0 + while True: + if (token := f"{prefix}{token_hex(n_bytes - 1)}") not in columns: + return token + + counter += 1 + if counter > 100: + msg = ( + "Internal Error: Narwhals was not able to generate a column name with " + f"{n_bytes=} and not in {columns}" + ) + raise AssertionError(msg) + + +def parse_columns_to_drop( + frame: _StoresColumns, subset: Iterable[str], /, *, strict: bool +) -> list[str]: + if not strict: + return list(set(frame.columns).intersection(subset)) + to_drop = list(subset) + if error := check_columns_exist(to_drop, available=frame.columns): + raise error + return to_drop + + +def is_sequence_but_not_str(sequence: Sequence[_T] | Any) -> TypeIs[Sequence[_T]]: + return isinstance(sequence, Sequence) and not isinstance(sequence, str) + + +def is_slice_none(obj: Any) -> TypeIs[_SliceNone]: + return isinstance(obj, slice) and obj == slice(None) + + +def is_sized_multi_index_selector( + obj: Any, +) -> TypeIs[SizedMultiIndexSelector[Series[Any] | CompliantSeries[Any]]]: + return ( + ( + is_sequence_but_not_str(obj) + and ((len(obj) > 0 and is_single_index_selector(obj[0])) or (len(obj) == 0)) + ) + or is_numpy_array_1d_int(obj) + or is_narwhals_series_int(obj) + or is_compliant_series_int(obj) + ) + + +def is_sequence_like( + obj: Sequence[_T] | Any, +) -> TypeIs[Sequence[_T] | Series[Any] | _1DArray]: + return ( + is_sequence_but_not_str(obj) + or is_numpy_array_1d(obj) + or is_narwhals_series(obj) + or is_compliant_series(obj) + ) + + +def is_slice_index(obj: Any) -> TypeIs[_SliceIndex]: + return isinstance(obj, slice) and ( + isinstance(obj.start, int) + or isinstance(obj.stop, int) + or ( + isinstance(obj.step, (int, NoneType)) + and obj.start is None + and obj.stop is None + ) + ) + + +def is_range(obj: Any) -> TypeIs[range]: + return isinstance(obj, range) + + +def is_single_index_selector(obj: Any) -> TypeIs[SingleIndexSelector]: + return bool(isinstance(obj, int) and not isinstance(obj, bool)) + + +def is_index_selector( + obj: Any, +) -> TypeIs[SingleIndexSelector | MultiIndexSelector[Series[Any] | CompliantSeries[Any]]]: + return ( + is_single_index_selector(obj) + or is_sized_multi_index_selector(obj) + or is_slice_index(obj) + ) + + +def is_boolean_selector( + obj: Any, +) -> TypeIs[SizedMultiBoolSelector[Series[Any] | CompliantSeries[Any]]]: + return ( + (is_sequence_but_not_str(obj) and (len(obj) > 0 and isinstance(obj[0], bool))) + or is_numpy_array_1d_bool(obj) + or is_narwhals_series_bool(obj) + or is_compliant_series_bool(obj) + ) + + +def is_list_of(obj: Any, tp: type[_T]) -> TypeIs[list[_T]]: + # Check if an object is a list of `tp`, only sniffing the first element. + return bool(isinstance(obj, list) and obj and isinstance(obj[0], tp)) + + +def predicates_contains_list_of_bool( + predicates: Collection[Any], +) -> TypeIs[Collection[list[bool]]]: + return any(is_list_of(pred, bool) for pred in predicates) + + +def is_sequence_of(obj: Any, tp: type[_T]) -> TypeIs[Sequence[_T]]: + # Check if an object is a sequence of `tp`, only sniffing the first element. + return bool( + is_sequence_but_not_str(obj) + and (first := next(iter(obj), None)) + and isinstance(first, tp) + ) + + +def is_nested_literal(obj: Any) -> TypeIs[NestedLiteral]: + return isinstance(obj, (list, tuple, dict)) + + +def validate_strict_and_pass_though( + strict: bool | None, # noqa: FBT001 + pass_through: bool | None, # noqa: FBT001 + *, + pass_through_default: bool, +) -> bool: + if strict is None and pass_through is None: + pass_through = pass_through_default + elif strict is not None and pass_through is None: + pass_through = not strict + elif strict is None and pass_through is not None: + pass + else: + msg = "Cannot pass both `strict` and `pass_through`" + raise ValueError(msg) + return pass_through + + +def deprecate_native_namespace( + *, warn_version: str = "", required: bool = False +) -> Callable[[Callable[P, R]], Callable[P, R]]: + """Decorator to transition from `native_namespace` to `backend` argument. + + Arguments: + warn_version: Emit a deprecation warning from this version. + required: Raise when both `native_namespace`, `backend` are `None`. + + Returns: + Wrapped function, with `native_namespace` **removed**. + """ + + def decorate(fn: Callable[P, R], /) -> Callable[P, R]: + @wraps(fn) + def wrapper(*args: P.args, **kwds: P.kwargs) -> R: + backend = kwds.pop("backend", None) + native_namespace = kwds.pop("native_namespace", None) + if native_namespace is not None and backend is None: + if warn_version: + msg = ( + "`native_namespace` is deprecated, please use `backend` instead.\n\n" + "Note: `native_namespace` will remain available in `narwhals.stable.v1`.\n" + "See https://narwhals-dev.github.io/narwhals/backcompat/ for more information.\n" + ) + issue_deprecation_warning(msg, _version=warn_version) + backend = native_namespace + elif native_namespace is not None and backend is not None: + msg = "Can't pass both `native_namespace` and `backend`" + raise ValueError(msg) + elif native_namespace is None and backend is None and required: + msg = f"`backend` must be specified in `{fn.__name__}`." + raise ValueError(msg) + kwds["backend"] = backend + return fn(*args, **kwds) + + return wrapper + + return decorate + + +def _validate_rolling_arguments( + window_size: int, min_samples: int | None +) -> tuple[int, int]: + ensure_type(window_size, int, param_name="window_size") + ensure_type(min_samples, int, type(None), param_name="min_samples") + + if window_size < 1: + msg = "window_size must be greater or equal than 1" + raise ValueError(msg) + + if min_samples is not None: + if min_samples < 1: + msg = "min_samples must be greater or equal than 1" + raise ValueError(msg) + + if min_samples > window_size: + msg = "`min_samples` must be less or equal than `window_size`" + raise InvalidOperationError(msg) + else: + min_samples = window_size + + return window_size, min_samples + + +def generate_repr(header: str, native_repr: str) -> str: + try: + terminal_width = os.get_terminal_size().columns + except OSError: + terminal_width = int(os.getenv("COLUMNS", 80)) # noqa: PLW1508 + native_lines = native_repr.expandtabs().splitlines() + max_native_width = max(len(line) for line in native_lines) + + if max_native_width + 2 <= terminal_width: + length = max(max_native_width, len(header)) + output = f"┌{'─' * length}┐\n" + header_extra = length - len(header) + output += f"|{' ' * (header_extra // 2)}{header}{' ' * (header_extra // 2 + header_extra % 2)}|\n" + output += f"|{'-' * (length)}|\n" + start_extra = (length - max_native_width) // 2 + end_extra = (length - max_native_width) // 2 + (length - max_native_width) % 2 + for line in native_lines: + output += f"|{' ' * (start_extra)}{line}{' ' * (end_extra + max_native_width - len(line))}|\n" + output += f"└{'─' * length}┘" + return output + + diff = 39 - len(header) + return ( + f"┌{'─' * (39)}┐\n" + f"|{' ' * (diff // 2)}{header}{' ' * (diff // 2 + diff % 2)}|\n" + "| Use `.to_native` to see native output |\n└" + f"{'─' * 39}┘" + ) + + +def check_columns_exist( + subset: Collection[str], /, *, available: Collection[str] +) -> ColumnNotFoundError | None: + if missing := set(subset).difference(available): + return ColumnNotFoundError.from_missing_and_available_column_names( + missing, available + ) + return None + + +def check_column_names_are_unique(columns: Collection[str]) -> None: + if len(columns) != len(set(columns)): + from collections import Counter + + counter = Counter(columns) + duplicates = {k: v for k, v in counter.items() if v > 1} + msg = "".join(f"\n- '{k}' {v} times" for k, v in duplicates.items()) + msg = f"Expected unique column names, got:{msg}" + raise DuplicateError(msg) + + +def _parse_time_unit_and_time_zone( + time_unit: TimeUnit | Iterable[TimeUnit] | None, + time_zone: str | timezone | Iterable[str | timezone | None] | None, +) -> tuple[Set[TimeUnit], Set[str | None]]: + time_units: Set[TimeUnit] = ( + {"ms", "us", "ns", "s"} + if time_unit is None + else {time_unit} + if isinstance(time_unit, str) + else set(time_unit) + ) + time_zones: Set[str | None] = ( + {None} + if time_zone is None + else {str(time_zone)} + if isinstance(time_zone, (str, timezone)) + else {str(tz) if tz is not None else None for tz in time_zone} + ) + return time_units, time_zones + + +def dtype_matches_time_unit_and_time_zone( + dtype: DType, dtypes: DTypes, time_units: Set[TimeUnit], time_zones: Set[str | None] +) -> bool: + return ( + isinstance(dtype, dtypes.Datetime) + and (dtype.time_unit in time_units) + and ( + dtype.time_zone in time_zones + or ("*" in time_zones and dtype.time_zone is not None) + ) + ) + + +def get_column_names(frame: _StoresColumns, /) -> Sequence[str]: + return frame.columns + + +def exclude_column_names(frame: _StoresColumns, names: Container[str]) -> Sequence[str]: + return [col_name for col_name in frame.columns if col_name not in names] + + +def passthrough_column_names(names: Sequence[str], /) -> EvalNames[Any]: + def fn(_frame: Any, /) -> Sequence[str]: + return names + + return fn + + +_SENTINEL: Final = object() + + +def _hasattr_static(obj: Any, attr: str) -> bool: + return getattr_static(obj, attr, _SENTINEL) is not _SENTINEL + + +def is_compliant_dataframe( + obj: CompliantDataFrame[ + CompliantSeriesT, CompliantExprT, NativeDataFrameT, ToNarwhalsT_co + ] + | Any, +) -> TypeIs[ + CompliantDataFrame[CompliantSeriesT, CompliantExprT, NativeDataFrameT, ToNarwhalsT_co] +]: + return _hasattr_static(obj, "__narwhals_dataframe__") + + +def is_compliant_lazyframe( + obj: CompliantLazyFrame[CompliantExprT, NativeLazyFrameT, ToNarwhalsT_co] | Any, +) -> TypeIs[CompliantLazyFrame[CompliantExprT, NativeLazyFrameT, ToNarwhalsT_co]]: + return _hasattr_static(obj, "__narwhals_lazyframe__") + + +def is_compliant_series( + obj: CompliantSeries[NativeSeriesT_co] | Any, +) -> TypeIs[CompliantSeries[NativeSeriesT_co]]: + return _hasattr_static(obj, "__narwhals_series__") + + +def is_compliant_series_int( + obj: CompliantSeries[NativeSeriesT_co] | Any, +) -> TypeIs[CompliantSeries[NativeSeriesT_co]]: + return is_compliant_series(obj) and obj.dtype.is_integer() + + +def is_compliant_series_bool( + obj: CompliantSeries[NativeSeriesT_co] | Any, +) -> TypeIs[CompliantSeries[NativeSeriesT_co]]: + return is_compliant_series(obj) and obj.dtype.is_boolean() + + +def _is_namespace_accessor(obj: _IntoContext) -> TypeIs[NamespaceAccessor[_FullContext]]: + # NOTE: Only `compliant` has false positives **internally** + # - https://github.com/narwhals-dev/narwhals/blob/cc69bac35eb8c81a1106969c49bfba9fd569b856/narwhals/_compliant/group_by.py#L44-L49 + # - https://github.com/narwhals-dev/narwhals/blob/cc69bac35eb8c81a1106969c49bfba9fd569b856/narwhals/_namespace.py#L166-L168 + # NOTE: Only `_accessor` has false positives **upstream** + # - https://github.com/pandas-dev/pandas/blob/e209a35403f8835bbcff97636b83d2fc39b51e68/pandas/core/accessor.py#L200-L233 + # - https://github.com/pola-rs/polars/blob/a60c5019f7b694c97009ef9208d25aaa4cc1d8a6/py-polars/polars/api.py#L29-L42 + return _hasattr_static(obj, "compliant") and _hasattr_static(obj, "_accessor") + + +def is_eager_allowed(impl: Implementation, /) -> TypeIs[_EagerAllowedImpl]: + """Return True if `impl` allows eager operations.""" + return impl in { + Implementation.CUDF, + Implementation.MODIN, + Implementation.PANDAS, + Implementation.POLARS, + Implementation.PYARROW, + } + + +def can_lazyframe_collect(impl: Implementation, /) -> TypeIs[_LazyFrameCollectImpl]: + """Return True if `LazyFrame.collect(impl)` is allowed.""" + return impl in {Implementation.PANDAS, Implementation.POLARS, Implementation.PYARROW} + + +def is_lazy_allowed(impl: Implementation, /) -> TypeIs[_LazyAllowedImpl]: + """Return True if `DataFrame.lazy(impl)` is allowed.""" + return impl in { + Implementation.DASK, + Implementation.DUCKDB, + Implementation.IBIS, + Implementation.POLARS, + Implementation.PYSPARK, + Implementation.PYSPARK_CONNECT, + Implementation.SQLFRAME, + } + + +def has_native_namespace(obj: Any) -> TypeIs[SupportsNativeNamespace]: + return _hasattr_static(obj, "__native_namespace__") + + +def supports_arrow_c_stream(obj: Any) -> TypeIs[ArrowStreamExportable]: + return _hasattr_static(obj, "__arrow_c_stream__") + + +def _remap_full_join_keys( + left_on: Collection[str], right_on: Collection[str], suffix: str +) -> dict[str, str]: + """Remap join keys to avoid collisions. + + If left keys collide with the right keys, append the suffix. + If there's no collision, let the right keys be. + + Arguments: + left_on: Left keys. + right_on: Right keys. + suffix: Suffix to append to right keys. + + Returns: + A map of old to new right keys. + """ + right_keys_suffixed = ( + f"{key}{suffix}" if key in left_on else key for key in right_on + ) + return dict(zip(right_on, right_keys_suffixed)) + + +def _into_arrow_table(data: IntoArrowTable, context: _LimitedContext, /) -> pa.Table: + """Guards `ArrowDataFrame.from_arrow` w/ safer imports. + + Arguments: + data: Object which implements `__arrow_c_stream__`. + context: Initialized compliant object. + """ + if find_spec("pyarrow"): + ns = context._version.namespace.from_backend("pyarrow").compliant + return ns._dataframe.from_arrow(data, context=ns).native + msg = f"'pyarrow>=14.0.0' is required for `from_arrow` for object of type {qualified_type_name(data)!r}." # pragma: no cover + raise ModuleNotFoundError(msg) # pragma: no cover + + +# TODO @dangotbanned: Extend with runtime behavior for `v1.*` +# See `narwhals.exceptions.NarwhalsUnstableWarning` +def unstable(fn: _Fn, /) -> _Fn: + """Visual-only marker for unstable functionality. + + Arguments: + fn: Function to decorate. + + Returns: + Decorated function (unchanged). + + Examples: + >>> @unstable + ... def a_work_in_progress_feature(*args): + ... return args + >>> + >>> a_work_in_progress_feature.__name__ + 'a_work_in_progress_feature' + >>> a_work_in_progress_feature(1, 2, 3) + (1, 2, 3) + """ + return fn + + +def _is_naive_format(format: str) -> bool: + """Determines if a datetime format string is 'naive', i.e., does not include timezone information. + + A format is considered naive if it does not contain any of the following + + - '%s': Unix timestamp + - '%z': UTC offset + - 'Z' : UTC timezone designator + + Arguments: + format: The datetime format string to check. + + Returns: + bool: True if the format is naive (does not include timezone info), False otherwise. + """ + return not any(x in format for x in ("%s", "%z", "Z")) + + +class not_implemented: # noqa: N801 + """Mark some functionality as unsupported. + + Arguments: + alias: optional name used instead of the data model hook [`__set_name__`]. + + Returns: + An exception-raising [descriptor]. + + Notes: + - Attribute/method name *doesn't* need to be declared twice + - Allows different behavior when looked up on the class vs instance + - Allows us to use `isinstance(...)` instead of monkeypatching an attribute to the function + + Examples: + >>> class Thing: + ... def totally_ready(self) -> str: + ... return "I'm ready!" + ... + ... not_ready_yet = not_implemented() + >>> + >>> thing = Thing() + >>> thing.totally_ready() + "I'm ready!" + >>> thing.not_ready_yet() + Traceback (most recent call last): + ... + NotImplementedError: 'not_ready_yet' is not implemented for: 'Thing'. + ... + >>> isinstance(Thing.not_ready_yet, not_implemented) + True + + [`__set_name__`]: https://docs.python.org/3/reference/datamodel.html#object.__set_name__ + [descriptor]: https://docs.python.org/3/howto/descriptor.html + """ + + def __init__(self, alias: str | None = None, /) -> None: + # NOTE: Don't like this + # Trying to workaround `mypy` requiring `@property` everywhere + self._alias: str | None = alias + + def __repr__(self) -> str: + return f"<{type(self).__name__}>: {self._name_owner}.{self._name}" + + def __set_name__(self, owner: type[_T], name: str) -> None: + # https://docs.python.org/3/howto/descriptor.html#customized-names + self._name_owner: str = owner.__name__ + self._name: str = self._alias or name + + def __get__( + self, instance: _T | Literal["raise"] | None, owner: type[_T] | None = None, / + ) -> Any: + if instance is None: + # NOTE: Branch for `cls._name` + # We can check that to see if an instance of `type(self)` for + # https://narwhals-dev.github.io/narwhals/api-completeness/expr/ + return self + # NOTE: Prefer not exposing the actual class we're defining in + # `_implementation` may not be available everywhere + implementation = getattr(instance, "_implementation", Implementation.UNKNOWN) + if implementation is not Implementation.UNKNOWN: + who = repr(implementation) + else: + who = self._name_owner + _raise_not_implemented_error(self._name, who) + return None # pragma: no cover + + def __call__(self, *args: Any, **kwds: Any) -> Any: + # NOTE: Purely to duck-type as assignable to **any** instance method + # Wouldn't be reachable through *regular* attribute access + return self.__get__("raise") + + @classmethod + def deprecated(cls, message: LiteralString, /) -> Self: # pragma: no cover + """Alt constructor, wraps with `@deprecated`. + + Arguments: + message: **Static-only** deprecation message, emitted in an IDE. + + [descriptor]: https://docs.python.org/3/howto/descriptor.html + """ + obj = cls() + return deprecated(message)(obj) + + +def _raise_not_implemented_error(what: str, who: str, /) -> NotImplementedError: + msg = ( + f"{what!r} is not implemented for: {who!r}.\n\n" + "If you would like to see this functionality in `narwhals`, " + "please open an issue at: https://github.com/narwhals-dev/narwhals/issues" + ) + raise NotImplementedError(msg) + + +class requires: # noqa: N801 + """Method decorator for raising under certain constraints. + + Attributes: + _min_version: Minimum backend version. + _hint: Optional suggested alternative. + + Examples: + >>> class SomeBackend: + ... _implementation = Implementation.PYARROW + ... _backend_version = 20, 0, 0 + ... + ... @requires.backend_version((9000, 0, 0)) + ... def really_complex_feature(self) -> str: + ... return "hello" + >>> backend = SomeBackend() + >>> backend.really_complex_feature() + Traceback (most recent call last): + ... + NotImplementedError: `really_complex_feature` is only available in 'pyarrow>=9000.0.0', found version '20.0.0'. + """ + + _min_version: tuple[int, ...] + _hint: str + _wrapped_name: str + """(Unqualified) decorated method name. + + When used in a namespace accessor, it will be prefixed by the property name. + """ + + @classmethod + def backend_version(cls, minimum: tuple[int, ...], /, hint: str = "") -> Self: + """Method decorator for raising below a minimum `_backend_version`. + + Arguments: + minimum: Minimum backend version. + hint: Optional suggested alternative. + """ + obj = cls.__new__(cls) + obj._min_version = minimum + obj._hint = hint + return obj + + @staticmethod + def _unparse_version(backend_version: tuple[int, ...], /) -> str: + return ".".join(f"{d}" for d in backend_version) + + def _qualify_accessor_name(self, prefix: Accessor, /) -> None: + # NOTE: Should only need to do this once per class (the first time the method is called) + if "." not in self._wrapped_name: + self._wrapped_name = f"{prefix}.{self._wrapped_name}" + + def _unwrap_context(self, instance: _IntoContext, /) -> tuple[tuple[int, ...], str]: + if _is_namespace_accessor(instance): + self._qualify_accessor_name(instance._accessor) + compliant = instance.compliant + else: + compliant = instance + return compliant._backend_version, str(compliant._implementation) + + def _ensure_version(self, instance: _IntoContext, /) -> None: + version, backend = self._unwrap_context(instance) + if version >= self._min_version: + return + minimum = self._unparse_version(self._min_version) + found = self._unparse_version(version) + msg = f"`{self._wrapped_name}` is only available in '{backend}>={minimum}', found version {found!r}." + if self._hint: + msg = f"{msg}\n{self._hint}" + raise NotImplementedError(msg) + + def __call__( + self, fn: _Method[_IntoContextT, P, R], / + ) -> _Method[_IntoContextT, P, R]: + self._wrapped_name = fn.__name__ + + @wraps(fn) + def wrapper(instance: _IntoContextT, *args: P.args, **kwds: P.kwargs) -> R: + self._ensure_version(instance) + return fn(instance, *args, **kwds) + + # NOTE: Only getting a complaint from `mypy` + return wrapper # type: ignore[return-value] + + +def convert_str_slice_to_int_slice( + str_slice: _SliceName, columns: Sequence[str] +) -> tuple[int | None, int | None, Any]: + start = columns.index(str_slice.start) if str_slice.start is not None else None + stop = columns.index(str_slice.stop) + 1 if str_slice.stop is not None else None + step = str_slice.step + return (start, stop, step) + + +def inherit_doc( + tp_parent: Callable[P, R1], / +) -> Callable[[_Constructor[_T, P, R2]], _Constructor[_T, P, R2]]: + """Steal the class-level docstring from parent and attach to child `__init__`. + + Returns: + Decorated constructor. + + Notes: + - Passes static typing (mostly) + - Passes at runtime + """ + + def decorate(init_child: _Constructor[_T, P, R2], /) -> _Constructor[_T, P, R2]: + if init_child.__name__ == "__init__" and issubclass(type(tp_parent), type): + init_child.__doc__ = getdoc(tp_parent) + return init_child + msg = ( # pragma: no cover + f"`@{inherit_doc.__name__}` is only allowed to decorate an `__init__` with a class-level doc.\n" + f"Method: {init_child.__qualname__!r}\n" + f"Parent: {tp_parent!r}" + ) + raise TypeError(msg) # pragma: no cover + + return decorate + + +def qualified_type_name(obj: object | type[Any], /) -> str: + tp = obj if isinstance(obj, type) else type(obj) + module = tp.__module__ if tp.__module__ != "builtins" else "" + return f"{module}.{tp.__name__}".lstrip(".") + + +def ensure_type(obj: Any, /, *valid_types: type[Any], param_name: str = "") -> None: + """Validate that an object is an instance of one or more specified types. + + Parameters: + obj: The object to validate. + *valid_types: One or more valid types that `obj` is expected to match. + param_name: The name of the parameter being validated. + Used to improve error message clarity. + + Raises: + TypeError: If `obj` is not an instance of any of the provided `valid_types`. + + Examples: + >>> ensure_type(42, int, float) + >>> ensure_type("hello", str) + + >>> ensure_type("hello", int, param_name="test") + Traceback (most recent call last): + ... + TypeError: Expected 'int', got: 'str' + test='hello' + ^^^^^^^ + >>> import polars as pl + >>> import pandas as pd + >>> df = pl.DataFrame([[1], [2], [3], [4], [5]], schema=[*"abcde"]) + >>> ensure_type(df, pd.DataFrame, param_name="df") + Traceback (most recent call last): + ... + TypeError: Expected 'pandas.DataFrame', got: 'polars.dataframe.frame.DataFrame' + df=polars.dataframe.frame.DataFrame(...) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + """ + if not isinstance(obj, valid_types): # pragma: no cover + tp_names = " | ".join(qualified_type_name(tp) for tp in valid_types) + msg = f"Expected {tp_names!r}, got: {qualified_type_name(obj)!r}" + if param_name: + left_pad = " " * 4 + val = repr(obj) + if len(val) > 40: # truncate long reprs + val = f"{qualified_type_name(obj)}(...)" + assign = f"{left_pad}{param_name}=" + underline = (" " * len(assign)) + ("^" * len(val)) + msg = f"{msg}\n{assign}{val}\n{underline}" + raise TypeError(msg) + + +class _DeferredIterable(Generic[_T]): + """Store a callable producing an iterable to defer collection until we need it.""" + + def __init__(self, into_iter: Callable[[], Iterable[_T]], /) -> None: + self._into_iter: Callable[[], Iterable[_T]] = into_iter + + def __iter__(self) -> Iterator[_T]: + yield from self._into_iter() + + def to_tuple(self) -> tuple[_T, ...]: + # Collect and return as a `tuple`. + it = self._into_iter() + return it if isinstance(it, tuple) else tuple(it) + + +@lru_cache(maxsize=64) +def deep_attrgetter(attr: str, *nested: str) -> attrgetter[Any]: + name = ".".join((attr, *nested)) if nested else attr + return attrgetter(name) + + +def deep_getattr(obj: Any, name_1: str, *nested: str) -> Any: + """Perform a nested attribute lookup on `obj`.""" + return deep_attrgetter(name_1, *nested)(obj) + + +class Compliant( + _StoresNative[NativeT_co], _StoresImplementation, Protocol[NativeT_co] +): ... + + +class Narwhals(Protocol[NativeT_co]): + """Minimal *Narwhals-level* protocol. + + Provides access to a compliant object: + + obj: Narwhals[NativeT_co]] + compliant: Compliant[NativeT_co] = obj._compliant + + Which itself exposes: + + implementation: Implementation = compliant.implementation + native: NativeT_co = compliant.native + + This interface is used for revealing which `Implementation` member is associated with **either**: + - One or more [nominal] native type(s) + - One or more [structural] type(s) + - where the true native type(s) are [assignable to] *at least* one of them + + These relationships are defined in the `@overload`s of `_Implementation.__get__(...)`. + + [nominal]: https://typing.python.org/en/latest/spec/glossary.html#term-nominal + [structural]: https://typing.python.org/en/latest/spec/glossary.html#term-structural + [assignable to]: https://typing.python.org/en/latest/spec/glossary.html#term-assignable + """ + + @property + def _compliant(self) -> Compliant[NativeT_co]: ... + + +class _Implementation: + """Descriptor for matching an opaque `Implementation` on a generic class. + + Based on [pyright comment](https://github.com/microsoft/pyright/issues/3071#issuecomment-1043978070) + """ + + def __set_name__(self, owner: type[Any], name: str) -> None: + self.__name__: str = name + + @overload + def __get__(self, instance: Narwhals[NativePolars], owner: Any) -> _PolarsImpl: ... + @overload + def __get__(self, instance: Narwhals[NativePandas], owner: Any) -> _PandasImpl: ... + @overload + def __get__(self, instance: Narwhals[NativeModin], owner: Any) -> _ModinImpl: ... + @overload + def __get__(self, instance: Narwhals[NativeCuDF], owner: Any) -> _CuDFImpl: ... + @overload + def __get__( + self, instance: Narwhals[NativePandasLike], owner: Any + ) -> _PandasLikeImpl: ... + @overload + def __get__(self, instance: Narwhals[NativeArrow], owner: Any) -> _ArrowImpl: ... + @overload + def __get__( + self, instance: Narwhals[NativePolars | NativeArrow | NativePandas], owner: Any + ) -> _PolarsImpl | _PandasImpl | _ArrowImpl: ... + @overload + def __get__(self, instance: Narwhals[NativeDuckDB], owner: Any) -> _DuckDBImpl: ... + @overload + def __get__( + self, instance: Narwhals[NativeSQLFrame], owner: Any + ) -> _SQLFrameImpl: ... + @overload + def __get__(self, instance: Narwhals[NativeDask], owner: Any) -> _DaskImpl: ... + @overload + def __get__(self, instance: Narwhals[NativeIbis], owner: Any) -> _IbisImpl: ... + @overload + def __get__( + self, instance: Narwhals[NativePySpark | NativePySparkConnect], owner: Any + ) -> _PySparkImpl | _PySparkConnectImpl: ... + # NOTE: https://docs.python.org/3/howto/descriptor.html#invocation-from-a-class + @overload + def __get__(self, instance: None, owner: type[Narwhals[Any]]) -> Self: ... + @overload + def __get__( + self, instance: DataFrame[Any] | Series[Any], owner: Any + ) -> _EagerAllowedImpl: ... + @overload + def __get__(self, instance: LazyFrame[Any], owner: Any) -> _LazyAllowedImpl: ... + def __get__(self, instance: Narwhals[Any] | None, owner: Any) -> Any: + return self if instance is None else instance._compliant._implementation + + +def to_pyarrow_table(tbl: pa.Table | pa.RecordBatchReader) -> pa.Table: + import pyarrow as pa # ignore-banned-import + + if isinstance(tbl, pa.RecordBatchReader): # pragma: no cover + return pa.Table.from_batches(tbl) + return tbl + + +if sys.platform != "win32": + + def normalize_path(source: FileSource, /) -> str: + return source if isinstance(source, str) else str(Path(source)) +else: # pragma: no cover + # NOTE: On Windows, we need to ensure strings paths do not produce escape sequences. + # This module is an example of the issue: + # `WindowsPath('/narwhals/narwhals/_utils.py')` + # If we stringify that, we get: + # `'\\narwhals\\narwhals\\_utils.py'` + # Which contains 2x `"\n"` characters + def normalize_path(source: FileSource, /) -> str: + return Path(source).as_posix() + + +def extend_bool( + value: bool | Iterable[bool], # noqa: FBT001 + n_match: int, +) -> Sequence[bool]: + """Ensure the given bool or sequence of bools is the correct length. + + Stolen from https://github.com/pola-rs/polars/blob/b8bfb07a4a37a8d449d6d1841e345817431142df/py-polars/polars/_utils/various.py#L580-L594 + """ + return (value,) * n_match if isinstance(value, bool) else tuple(value) + + +class _NoDefault(Enum): + # "borrowed" from + # https://github.com/pandas-dev/pandas/blob/e7859983a814b1823cf26e3b491ae2fa3be47c53/pandas/_libs/lib.pyx#L2736-L2748 + no_default = "NO_DEFAULT" + + def __repr__(self) -> str: # pragma: no cover + return "" + + +# the "no_default" sentinel should typically be used when one of the valid parameter +# values is None, as otherwise we cannot determine if the caller has set that value. +no_default = _NoDefault.no_default + +# Can be imported from types in Python 3.10 +NoneType = type(None) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/compliant.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/compliant.py new file mode 100644 index 0000000000000000000000000000000000000000..a97ce01c2dcce2108fb2d92736a8d509bcab44b0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/compliant.py @@ -0,0 +1,38 @@ +"""Public protocols for plugin authors.""" + +from __future__ import annotations + +from narwhals._compliant import ( + CompliantDataFrame, + CompliantExpr, + CompliantGroupBy, + CompliantLazyFrame, + CompliantNamespace, + CompliantSeries, +) +from narwhals._compliant.any_namespace import ( + CatNamespace, + DateTimeNamespace, + ListNamespace, + StringNamespace, + StructNamespace, +) +from narwhals._compliant.expr import CompliantExprNameNamespace +from narwhals._compliant.selectors import CompliantSelector, CompliantSelectorNamespace + +__all__ = [ + "CatNamespace", + "CompliantDataFrame", + "CompliantExpr", + "CompliantExprNameNamespace", + "CompliantGroupBy", + "CompliantLazyFrame", + "CompliantNamespace", + "CompliantSelector", + "CompliantSelectorNamespace", + "CompliantSeries", + "DateTimeNamespace", + "ListNamespace", + "StringNamespace", + "StructNamespace", +] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/dataframe.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..bd602efd5243396e8ef088da2572bde33c39dd2a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/dataframe.py @@ -0,0 +1,3352 @@ +from __future__ import annotations + +from abc import abstractmethod +from functools import partial +from itertools import chain +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Generic, + Literal, + NoReturn, + TypeVar, + get_args, + overload, +) + +from narwhals._exceptions import issue_warning +from narwhals._expression_parsing import ( + _parse_into_expr, + check_expressions_preserve_length, + is_scalar_like, +) +from narwhals._typing import Arrow, Pandas, _LazyAllowedImpl, _LazyFrameCollectImpl +from narwhals._utils import ( + Implementation, + Version, + _Implementation, + can_lazyframe_collect, + check_columns_exist, + flatten, + generate_repr, + is_compliant_dataframe, + is_compliant_lazyframe, + is_eager_allowed, + is_index_selector, + is_iterator, + is_lazy_allowed, + is_list_of, + is_sequence_like, + is_slice_none, + predicates_contains_list_of_bool, + qualified_type_name, + supports_arrow_c_stream, + zip_strict, +) +from narwhals.dependencies import is_numpy_array_2d, is_pyarrow_table +from narwhals.exceptions import ( + ColumnNotFoundError, + InvalidOperationError, + PerformanceWarning, +) +from narwhals.functions import _from_dict_no_backend, _is_into_schema +from narwhals.schema import Schema +from narwhals.series import Series +from narwhals.translate import to_native + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Mapping, Sequence + from io import BytesIO + from pathlib import Path + from types import ModuleType + + import pandas as pd + import polars as pl + import pyarrow as pa + from typing_extensions import Concatenate, ParamSpec, Self, TypeAlias + + from narwhals._compliant import CompliantDataFrame, CompliantLazyFrame + from narwhals._compliant.typing import CompliantExprAny + from narwhals._expression_parsing import ExprMetadata + from narwhals._translate import IntoArrowTable + from narwhals._typing import EagerAllowed, IntoBackend, LazyAllowed, Polars + from narwhals.dtypes import DType + from narwhals.group_by import GroupBy, LazyGroupBy + from narwhals.typing import ( + AsofJoinStrategy, + IntoDataFrame, + IntoExpr, + IntoFrame, + IntoLazyFrame, + IntoSchema, + JoinStrategy, + MultiColSelector as _MultiColSelector, + MultiIndexSelector as _MultiIndexSelector, + PivotAgg, + SingleColSelector, + SingleIndexSelector, + SizeUnit, + UniqueKeepStrategy, + _2DArray, + ) + + PS = ParamSpec("PS") + Incomplete: TypeAlias = Any + +_FrameT = TypeVar("_FrameT", bound="IntoFrame") +LazyFrameT = TypeVar("LazyFrameT", bound="IntoLazyFrame") +DataFrameT = TypeVar("DataFrameT", bound="IntoDataFrame") +R = TypeVar("R") + +MultiColSelector: TypeAlias = "_MultiColSelector[Series[Any]]" +MultiIndexSelector: TypeAlias = "_MultiIndexSelector[Series[Any]]" + + +class BaseFrame(Generic[_FrameT]): + _compliant_frame: Any + _level: Literal["full", "lazy", "interchange"] + + implementation: _Implementation = _Implementation() + """Return [`narwhals.Implementation`][] of native frame. + + This can be useful when you need to use special-casing for features outside of + Narwhals' scope - for example, when dealing with pandas' Period Dtype. + + Examples: + >>> import narwhals as nw + >>> import pandas as pd + >>> df_native = pd.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.implementation + + >>> df.implementation.is_pandas() + True + >>> df.implementation.is_pandas_like() + True + >>> df.implementation.is_polars() + False + """ + + @property + @abstractmethod + def _compliant(self) -> Any: ... + + def __native_namespace__(self) -> ModuleType: + return self._compliant_frame.__native_namespace__() # type: ignore[no-any-return] + + def __narwhals_namespace__(self) -> Any: + return self._compliant_frame.__narwhals_namespace__() + + def _with_compliant(self, df: Any) -> Self: + # construct, preserving properties + return self.__class__(df, level=self._level) # type: ignore[call-arg] + + def _flatten_and_extract( + self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr + ) -> list[CompliantExprAny]: + # Process `args` and `kwargs`, extracting underlying objects as we go. + # NOTE: Strings are interpreted as column names. + out_exprs = [] + ns = self.__narwhals_namespace__() + parse = partial( + _parse_into_expr, backend=self._compliant._implementation, allow_literal=False + ) + all_exprs = chain( + (parse(x) for x in flatten(exprs)), + (parse(expr).alias(alias) for alias, expr in named_exprs.items()), + ) + for expr in all_exprs: + ce = expr._to_compliant_expr(ns) + out_exprs.append(ce) + self._validate_metadata(ce._metadata) + return out_exprs + + def _extract_compliant_frame(self, other: Self | Any, /) -> Any: + if isinstance(other, type(self)): + return other._compliant_frame + msg = f"Expected `other` to be a {qualified_type_name(self)!r}, got: {qualified_type_name(other)!r}" + raise TypeError(msg) + + def _check_columns_exist(self, subset: Sequence[str]) -> ColumnNotFoundError | None: + return check_columns_exist(subset, available=self.columns) + + @abstractmethod + def _validate_metadata(self, metadata: ExprMetadata) -> None: # pragma: no cover + pass + + @property + def schema(self) -> Schema: + return Schema(self._compliant_frame.schema.items()) + + def collect_schema(self) -> Schema: + native_schema = dict(self._compliant_frame.collect_schema()) + + return Schema(native_schema) + + def pipe( + self, + function: Callable[Concatenate[Self, PS], R], + *args: PS.args, + **kwargs: PS.kwargs, + ) -> R: + return function(self, *args, **kwargs) + + def drop_nulls(self, subset: str | list[str] | None) -> Self: + subset = [subset] if isinstance(subset, str) else subset + return self._with_compliant(self._compliant_frame.drop_nulls(subset=subset)) + + @property + def columns(self) -> list[str]: + return self._compliant_frame.columns # type: ignore[no-any-return] + + def with_columns( + self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr + ) -> Self: + compliant_exprs = self._flatten_and_extract(*exprs, **named_exprs) + compliant_exprs = [ + compliant_expr.broadcast() + if is_scalar_like(compliant_expr) + else compliant_expr + for compliant_expr in compliant_exprs + ] + return self._with_compliant(self._compliant_frame.with_columns(*compliant_exprs)) + + def select( + self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr + ) -> Self: + flat_exprs = tuple(flatten(exprs)) + if flat_exprs and all(isinstance(x, str) for x in flat_exprs) and not named_exprs: + # fast path! + try: + return self._with_compliant( + self._compliant_frame.simple_select(*flat_exprs) + ) + except Exception as e: + # Column not found is the only thing that can realistically be raised here. + if error := self._check_columns_exist(flat_exprs): + raise error from e + raise + compliant_exprs = self._flatten_and_extract(*flat_exprs, **named_exprs) + if compliant_exprs and all(is_scalar_like(x) for x in compliant_exprs): + return self._with_compliant(self._compliant_frame.aggregate(*compliant_exprs)) + compliant_exprs = [ + compliant_expr.broadcast() + if is_scalar_like(compliant_expr) + else compliant_expr + for compliant_expr in compliant_exprs + ] + return self._with_compliant(self._compliant_frame.select(*compliant_exprs)) + + def rename(self, mapping: dict[str, str]) -> Self: + return self._with_compliant(self._compliant_frame.rename(mapping)) + + def head(self, n: int) -> Self: + return self._with_compliant(self._compliant_frame.head(n)) + + def tail(self, n: int) -> Self: + return self._with_compliant(self._compliant_frame.tail(n)) + + def drop(self, *columns: Iterable[str], strict: bool) -> Self: + return self._with_compliant(self._compliant_frame.drop(columns, strict=strict)) + + def filter( + self, *predicates: IntoExpr | Iterable[IntoExpr], **constraints: Any + ) -> Self: + from narwhals.functions import all_horizontal, col + + flat_predicates = flatten(predicates) + predicate = all_horizontal( + *chain(flat_predicates, (col(name) == v for name, v in constraints.items())), + ignore_nulls=False, + ) + (compliant_predicate,) = self._flatten_and_extract(predicate) + check_expressions_preserve_length(compliant_predicate, function_name="filter") + return self._with_compliant(self._compliant_frame.filter(compliant_predicate)) + + def sort( + self, + by: str | Iterable[str], + *more_by: str, + descending: bool | Sequence[bool] = False, + nulls_last: bool = False, + ) -> Self: + by = flatten([*flatten([by]), *more_by]) + return self._with_compliant( + self._compliant_frame.sort(*by, descending=descending, nulls_last=nulls_last) + ) + + def top_k( + self, k: int, *, by: str | Iterable[str], reverse: bool | Sequence[bool] = False + ) -> Self: + flatten_by = flatten([by]) + return self._with_compliant( + self._compliant_frame.top_k(k, by=flatten_by, reverse=reverse) + ) + + def join( + self, + other: Incomplete, + on: str | list[str] | None, + how: JoinStrategy, + *, + left_on: str | list[str] | None, + right_on: str | list[str] | None, + suffix: str, + ) -> Self: + _supported_joins = ("inner", "left", "full", "cross", "anti", "semi") + on = [on] if isinstance(on, str) else on + left_on = [left_on] if isinstance(left_on, str) else left_on + right_on = [right_on] if isinstance(right_on, str) else right_on + compliant = self._compliant_frame + other = self._extract_compliant_frame(other) + + if how not in _supported_joins: + msg = f"Only the following join strategies are supported: {_supported_joins}; found '{how}'." + raise NotImplementedError(msg) + if how == "cross": + if left_on is not None or right_on is not None or on is not None: + msg = "Can not pass `left_on`, `right_on` or `on` keys for cross join" + raise ValueError(msg) + result = compliant.join( + other, how=how, left_on=None, right_on=None, suffix=suffix + ) + elif on is None: + if left_on is None or right_on is None: + msg = f"Either (`left_on` and `right_on`) or `on` keys should be specified for {how}." + raise ValueError(msg) + if len(left_on) != len(right_on): + msg = "`left_on` and `right_on` must have the same length." + raise ValueError(msg) + result = compliant.join( + other, how=how, left_on=left_on, right_on=right_on, suffix=suffix + ) + else: + if left_on is not None or right_on is not None: + msg = f"If `on` is specified, `left_on` and `right_on` should be None for {how}." + raise ValueError(msg) + result = compliant.join( + other, how=how, left_on=on, right_on=on, suffix=suffix + ) + return self._with_compliant(result) + + def gather_every(self, n: int, offset: int = 0) -> Self: + return self._with_compliant( + self._compliant_frame.gather_every(n=n, offset=offset) + ) + + def join_asof( + self, + other: Incomplete, + *, + left_on: str | None, + right_on: str | None, + on: str | None, + by_left: str | list[str] | None, + by_right: str | list[str] | None, + by: str | list[str] | None, + strategy: AsofJoinStrategy, + suffix: str, + ) -> Self: + _supported_strategies = ("backward", "forward", "nearest") + + if strategy not in _supported_strategies: + msg = f"Only the following strategies are supported: {_supported_strategies}; found '{strategy}'." + raise NotImplementedError(msg) + + if (on is None) and (left_on is None or right_on is None): + msg = "Either (`left_on` and `right_on`) or `on` keys should be specified." + raise ValueError(msg) + if (on is not None) and (left_on is not None or right_on is not None): + msg = "If `on` is specified, `left_on` and `right_on` should be None." + raise ValueError(msg) + if (by is None) and ( + (by_left is None and by_right is not None) + or (by_left is not None and by_right is None) + ): + msg = ( + "Can not specify only `by_left` or `by_right`, you need to specify both." + ) + raise ValueError(msg) + if (by is not None) and (by_left is not None or by_right is not None): + msg = "If `by` is specified, `by_left` and `by_right` should be None." + raise ValueError(msg) + if on is not None: + left_on = right_on = on + if by is not None: + by_left = by_right = by + + by_left = [by_left] if isinstance(by_left, str) else by_left + by_right = [by_right] if isinstance(by_right, str) else by_right + + if (isinstance(by_left, list) and isinstance(by_right, list)) and ( + len(by_left) != len(by_right) + ): + msg = "`by_left` and `by_right` must have the same length." + raise ValueError(msg) + + return self._with_compliant( + self._compliant_frame.join_asof( + self._extract_compliant_frame(other), + left_on=left_on, + right_on=right_on, + by_left=by_left, + by_right=by_right, + strategy=strategy, + suffix=suffix, + ) + ) + + def unpivot( + self, + on: str | list[str] | None, + *, + index: str | list[str] | None, + variable_name: str, + value_name: str, + ) -> Self: + on = [on] if isinstance(on, str) else on + index = [index] if isinstance(index, str) else index + + return self._with_compliant( + self._compliant_frame.unpivot( + on=on, index=index, variable_name=variable_name, value_name=value_name + ) + ) + + def __neq__(self, other: object) -> NoReturn: + msg = ( + "DataFrame.__neq__ and LazyFrame.__neq__ are not implemented, please " + "use expressions instead.\n\n" + "Hint: instead of\n" + " df != 0\n" + "you may want to use\n" + " df.select(nw.all() != 0)" + ) + raise NotImplementedError(msg) + + def __eq__(self, other: object) -> NoReturn: + msg = ( + "DataFrame.__eq__ and LazyFrame.__eq__ are not implemented, please " + "use expressions instead.\n\n" + "Hint: instead of\n" + " df == 0\n" + "you may want to use\n" + " df.select(nw.all() == 0)" + ) + raise NotImplementedError(msg) + + def explode(self, columns: str | Sequence[str], *more_columns: str) -> Self: + to_explode = ( + [columns, *more_columns] + if isinstance(columns, str) + else [*columns, *more_columns] + ) + + return self._with_compliant(self._compliant_frame.explode(columns=to_explode)) + + +class DataFrame(BaseFrame[DataFrameT]): + """Narwhals DataFrame, backed by a native eager dataframe. + + Warning: + This class is not meant to be instantiated directly - instead: + + - If the native object is a eager dataframe from one of the supported + backend (e.g. pandas.DataFrame, polars.DataFrame, pyarrow.Table), + you can use [`narwhals.from_native`][]: + ```py + narwhals.from_native(native_dataframe) + narwhals.from_native(native_dataframe, eager_only=True) + ``` + + - If the object is a dictionary of column names and generic sequences mapping + (e.g. `dict[str, list]`), you can create a DataFrame via + [`narwhals.from_dict`][]: + ```py + narwhals.from_dict( + data={"a": [1, 2, 3]}, + backend=narwhals.get_native_namespace(another_object), + ) + ``` + """ + + _version: ClassVar[Version] = Version.MAIN + + @property + def _compliant(self) -> CompliantDataFrame[Any, Any, DataFrameT, Self]: + return self._compliant_frame + + @property + def _series(self) -> type[Series[Any]]: + return Series + + @property + def _lazyframe(self) -> type[LazyFrame[Any]]: + return LazyFrame + + def _validate_metadata(self, metadata: ExprMetadata) -> None: + # all is valid in eager case. + pass + + def __init__(self, df: Any, *, level: Literal["full", "lazy", "interchange"]) -> None: + self._level: Literal["full", "lazy", "interchange"] = level + self._compliant_frame: CompliantDataFrame[Any, Any, DataFrameT, Self] + if is_compliant_dataframe(df): + self._compliant_frame = df.__narwhals_dataframe__() + else: # pragma: no cover + msg = f"Expected an object which implements `__narwhals_dataframe__`, got: {type(df)}" + raise AssertionError(msg) + + @classmethod + def from_arrow( + cls, native_frame: IntoArrowTable, *, backend: IntoBackend[EagerAllowed] + ) -> DataFrame[Any]: + """Construct a DataFrame from an object which supports the PyCapsule Interface. + + Arguments: + native_frame: Object which implements `__arrow_c_stream__`. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [4.2, 5.1]}) + >>> nw.DataFrame.from_arrow(df_native, backend="polars") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (2, 2) | + | ┌─────┬─────┐ | + | │ a ┆ b │ | + | │ --- ┆ --- │ | + | │ i64 ┆ f64 │ | + | ╞═════╪═════╡ | + | │ 1 ┆ 4.2 │ | + | │ 2 ┆ 5.1 │ | + | └─────┴─────┘ | + └──────────────────┘ + """ + if not (supports_arrow_c_stream(native_frame) or is_pyarrow_table(native_frame)): + msg = f"Given object of type {type(native_frame)} does not support PyCapsule interface" + raise TypeError(msg) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + compliant = ns._dataframe.from_arrow(native_frame, context=ns) + return cls(compliant, level="full") + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `DataFrame.from_arrow` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.DataFrame.from_arrow(df, backend='pyarrow').lazy('{implementation}')" + ) + raise ValueError(msg) + + @classmethod + def from_dict( + cls, + data: Mapping[str, Any], + schema: IntoSchema | Mapping[str, DType | None] | None = None, + *, + backend: IntoBackend[EagerAllowed] | None = None, + ) -> DataFrame[Any]: + """Instantiate DataFrame from dictionary. + + Indexes (if present, for pandas-like backends) are aligned following + the [left-hand-rule](../concepts/pandas_index.md/). + + Notes: + For pandas-like dataframes, conversion to schema is applied after dataframe + creation. + + Arguments: + data: Dictionary to create DataFrame from. + schema: The DataFrame schema as Schema or dict of {name: type}. If not + specified, the schema will be inferred by the native library. If + any `dtype` is `None`, the data type for that column will be inferred + by the native library. + backend: specifies which eager backend instantiate to. Only + necessary if inputs are not Narwhals Series. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> data = {"c": [5, 2], "d": [1, 4]} + >>> nw.DataFrame.from_dict(data, backend="pandas") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | c d | + | 0 5 1 | + | 1 2 4 | + └──────────────────┘ + """ + if backend is None: + data, backend = _from_dict_no_backend(data) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + compliant = ns._dataframe.from_dict(data, schema=schema, context=ns) + return cls(compliant, level="full") + # NOTE: (#2786) needs resolving for extensions + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `DataFrame.from_dict` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.DataFrame.from_dict({{'a': [1, 2]}}, backend='pyarrow').lazy('{implementation}')" + ) + raise ValueError(msg) + + @classmethod + def from_dicts( + cls, + data: Sequence[Mapping[str, Any]], + schema: IntoSchema | Mapping[str, DType | None] | None = None, + *, + backend: IntoBackend[EagerAllowed], + ) -> DataFrame[Any]: + """Instantiate DataFrame from a sequence of dictionaries representing rows. + + Notes: + For pandas-like dataframes, conversion to schema is applied after dataframe + creation. + + Arguments: + data: Sequence with dictionaries mapping column name to value. + schema: The DataFrame schema as Schema or dict of {name: type}. If not + specified, the schema will be inferred by the native library. If + any `dtype` is `None`, the data type for that column will be inferred + by the native library. + backend: Specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Tip: + If you expect non-uniform keys in `data`, consider passing `schema` for + more consistent results, as **inference varies between backends**: + + - pandas uses all rows + - polars uses the first 100 rows + - pyarrow uses only the first row + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> data = [ + ... {"item": "apple", "weight": 80, "price": 0.60}, + ... {"item": "egg", "weight": 55, "price": 0.40}, + ... ] + >>> nw.DataFrame.from_dicts(data, backend="polars") + ┌──────────────────────────┐ + | Narwhals DataFrame | + |--------------------------| + |shape: (2, 3) | + |┌───────┬────────┬───────┐| + |│ item ┆ weight ┆ price │| + |│ --- ┆ --- ┆ --- │| + |│ str ┆ i64 ┆ f64 │| + |╞═══════╪════════╪═══════╡| + |│ apple ┆ 80 ┆ 0.6 │| + |│ egg ┆ 55 ┆ 0.4 │| + |└───────┴────────┴───────┘| + └──────────────────────────┘ + """ + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + compliant = ns._dataframe.from_dicts(data, schema=schema, context=ns) + return cls(compliant, level="full") + # NOTE: (#2786) needs resolving for extensions + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `DataFrame.from_dicts` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.DataFrame.from_dicts([{{'a': 1}}, {{'a': 2}}], backend='pyarrow').lazy('{implementation}')" + ) + raise ValueError(msg) + + @classmethod + def from_numpy( + cls, + data: _2DArray, + schema: IntoSchema | Sequence[str] | None = None, + *, + backend: IntoBackend[EagerAllowed], + ) -> DataFrame[Any]: + """Construct a DataFrame from a NumPy ndarray. + + Notes: + Only row orientation is currently supported. + + For pandas-like dataframes, conversion to schema is applied after dataframe + creation. + + Arguments: + data: Two-dimensional data represented as a NumPy ndarray. + schema: The DataFrame schema as Schema, dict of {name: type}, or a sequence of str. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import numpy as np + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> arr = np.array([[5, 2, 1], [1, 4, 3]]) + >>> schema = {"c": nw.Int16(), "d": nw.Float32(), "e": nw.Int8()} + >>> nw.DataFrame.from_numpy(arr, schema=schema, backend="polars") + ┌───────────────────┐ + |Narwhals DataFrame | + |-------------------| + |shape: (2, 3) | + |┌─────┬─────┬─────┐| + |│ c ┆ d ┆ e │| + |│ --- ┆ --- ┆ --- │| + |│ i16 ┆ f32 ┆ i8 │| + |╞═════╪═════╪═════╡| + |│ 5 ┆ 2.0 ┆ 1 │| + |│ 1 ┆ 4.0 ┆ 3 │| + |└─────┴─────┴─────┘| + └───────────────────┘ + """ + if not is_numpy_array_2d(data): + msg = "`from_numpy` only accepts 2D numpy arrays" + raise ValueError(msg) + if not _is_into_schema(schema): + msg = ( + "`schema` is expected to be one of the following types: " + "Mapping[str, DType] | Schema | Sequence[str]. " + f"Got {type(schema)}." + ) + raise TypeError(msg) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + return cls(ns.from_numpy(data, schema), level="full") + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `DataFrame.from_numpy` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.DataFrame.from_numpy(arr, backend='pyarrow').lazy('{implementation}')" + ) + raise ValueError(msg) + + def __len__(self) -> int: + return self._compliant_frame.__len__() + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> _2DArray: # noqa: FBT001 + return self._compliant_frame.__array__(dtype, copy=copy) + + def __repr__(self) -> str: # pragma: no cover + return generate_repr("Narwhals DataFrame", self.to_native().__repr__()) + + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export a DataFrame via the Arrow PyCapsule Interface. + + - if the underlying dataframe implements the interface, it'll return that + - else, it'll call `to_arrow` and then defer to PyArrow's implementation + + See [PyCapsule Interface](https://arrow.apache.org/docs/dev/format/CDataInterface/PyCapsuleInterface.html) + for more. + """ + native_frame = self._compliant_frame._native_frame + if supports_arrow_c_stream(native_frame): + return native_frame.__arrow_c_stream__(requested_schema=requested_schema) + try: + pa_version = Implementation.PYARROW._backend_version() + except ModuleNotFoundError as exc: + msg = f"'pyarrow>=14.0.0' is required for `DataFrame.__arrow_c_stream__` for object of type {type(native_frame)}" + raise ModuleNotFoundError(msg) from exc + if pa_version < (14, 0): # pragma: no cover + msg = f"'pyarrow>=14.0.0' is required for `DataFrame.__arrow_c_stream__` for object of type {type(native_frame)}" + raise ModuleNotFoundError(msg) from None + pa_table = self.to_arrow() + return pa_table.__arrow_c_stream__(requested_schema=requested_schema) # type: ignore[no-untyped-call] + + def lazy( + self, + backend: IntoBackend[LazyAllowed] | None = None, + *, + session: Any | None = None, + ) -> LazyFrame[Any]: + """Restrict available API methods to lazy-only ones. + + If `backend` is specified, then a conversion between different backends + might be triggered. + + If a library does not support lazy execution and `backend` is not specified, + then this is will only restrict the API to lazy-only operations. This is useful + if you want to ensure that you write dataframe-agnostic code which all has + the possibility of running entirely lazily. + + Note: + If `backend` is spark-like, then a valid `session` is required. + + For instance: + + ```py + import narwhals as nw + from sqlframe.duckdb import DuckDBSession + + df.lazy(backend=nw.Implementation.SQLFRAME, session=DuckDBSession()) + ``` + + Arguments: + backend: Which lazy backend collect to. This will be the underlying + backend for the resulting Narwhals LazyFrame. If not specified, and the + given library does not support lazy execution, then this will restrict + the API to lazy-only operations. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `DASK`, `DUCKDB`, + `IBIS` or `POLARS`. + - As a string: `"dask"`, `"duckdb"`, `"ibis"` or `"polars"` + - Directly as a module `dask.dataframe`, `duckdb`, `ibis` or `polars`. + session: Session to be used if backend is spark-like. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2], "b": [4, 6]}) + >>> df = nw.from_native(df_native) + + If we call `df.lazy`, we get a `narwhals.LazyFrame` backed by a Polars + LazyFrame. + + >>> df.lazy() # doctest: +SKIP + ┌─────────────────────────────┐ + | Narwhals LazyFrame | + |-----------------------------| + || + └─────────────────────────────┘ + + We can also pass DuckDB as the backend, and then we'll get a + `narwhals.LazyFrame` backed by a `duckdb.DuckDBPyRelation`. + + >>> df.lazy(backend=nw.Implementation.DUCKDB) + ┌──────────────────┐ + |Narwhals LazyFrame| + |------------------| + |┌───────┬───────┐ | + |│ a │ b │ | + |│ int64 │ int64 │ | + |├───────┼───────┤ | + |│ 1 │ 4 │ | + |│ 2 │ 6 │ | + |└───────┴───────┘ | + └──────────────────┘ + """ + lazy = self._compliant_frame.lazy + if backend is None: + return self._lazyframe(lazy(None, session=session), level="lazy") + lazy_backend = Implementation.from_backend(backend) + if is_lazy_allowed(lazy_backend): + return self._lazyframe(lazy(lazy_backend, session=session), level="lazy") + msg = f"Not-supported backend.\n\nExpected one of {get_args(_LazyAllowedImpl)} or `None`, got {lazy_backend}" + raise ValueError(msg) + + def to_native(self) -> DataFrameT: + """Convert Narwhals DataFrame to native one. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"foo": [1, 2, 3], "bar": [6.0, 7.0, 8.0], "ham": ["a", "b", "c"]} + ... ) + + Calling `to_native` on a Narwhals DataFrame returns the native object: + + >>> nw.from_native(df_native).to_native() + foo bar ham + 0 1 6.0 a + 1 2 7.0 b + 2 3 8.0 c + """ + return self._compliant_frame._native_frame + + def to_pandas(self) -> pd.DataFrame: + """Convert this DataFrame to a pandas DataFrame. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"foo": [1, 2, 3], "bar": [6.0, 7.0, 8.0], "ham": ["a", "b", "c"]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.to_pandas() + foo bar ham + 0 1 6.0 a + 1 2 7.0 b + 2 3 8.0 c + """ + return self._compliant_frame.to_pandas() + + def to_polars(self) -> pl.DataFrame: + """Convert this DataFrame to a polars DataFrame. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> df = nw.from_native(df_native) + >>> df.to_polars() + shape: (2, 2) + ┌─────┬─────┐ + │ foo ┆ bar │ + │ --- ┆ --- │ + │ i64 ┆ f64 │ + ╞═════╪═════╡ + │ 1 ┆ 6.0 │ + │ 2 ┆ 7.0 │ + └─────┴─────┘ + """ + return self._compliant_frame.to_polars() + + @overload + def write_csv(self, file: None = None) -> str: ... + + @overload + def write_csv(self, file: str | Path | BytesIO) -> None: ... + + def write_csv(self, file: str | Path | BytesIO | None = None) -> str | None: + r"""Write dataframe to comma-separated values (CSV) file. + + Arguments: + file: String, path object or file-like object to which the dataframe will be + written. If None, the resulting csv format is returned as a string. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"foo": [1, 2, 3], "bar": [6.0, 7.0, 8.0], "ham": ["a", "b", "c"]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.write_csv() # doctest: +SKIP + 'foo,bar,ham\n1,6.0,a\n2,7.0,b\n3,8.0,c\n' + + If we had passed a file name to `write_csv`, it would have been + written to that file. + """ + return self._compliant_frame.write_csv(file) + + def write_parquet(self, file: str | Path | BytesIO) -> None: + """Write dataframe to parquet file. + + Arguments: + file: String, path object or file-like object to which the dataframe will be + written. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> df = nw.from_native(df_native) + >>> df.write_parquet("out.parquet") # doctest:+SKIP + """ + self._compliant_frame.write_parquet(file) + + def to_numpy(self) -> _2DArray: + """Convert this DataFrame to a NumPy ndarray. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, 2], "bar": [6.5, 7.0]}) + >>> df = nw.from_native(df_native) + >>> df.to_numpy() + array([[1. , 6.5], + [2. , 7. ]]) + """ + return self._compliant_frame.to_numpy(None, copy=None) + + @property + def shape(self) -> tuple[int, int]: + """Get the shape of the DataFrame. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, 2]}) + >>> df = nw.from_native(df_native) + >>> df.shape + (2, 1) + """ + return self._compliant_frame.shape + + def get_column(self, name: str) -> Series[Any]: + """Get a single column by name. + + Arguments: + name: The column name as a string. + + Notes: + Although `name` is typed as `str`, pandas does allow non-string column + names, and they will work when passed to this function if the + `narwhals.DataFrame` is backed by a pandas dataframe with non-string + columns. This function can only be used to extract a column by name, so + there is no risk of ambiguity. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2]}) + >>> df = nw.from_native(df_native) + >>> df.get_column("a").to_native() + 0 1 + 1 2 + Name: a, dtype: int64 + """ + return self._series(self._compliant_frame.get_column(name), level=self._level) + + def estimated_size(self, unit: SizeUnit = "b") -> int | float: + """Return an estimation of the total (heap) allocated size of the `DataFrame`. + + Estimated size is given in the specified unit (bytes by default). + + Arguments: + unit: 'b', 'kb', 'mb', 'gb', 'tb', 'bytes', 'kilobytes', 'megabytes', + 'gigabytes', or 'terabytes'. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> df = nw.from_native(df_native) + >>> df.estimated_size() + 32 + """ + return self._compliant_frame.estimated_size(unit=unit) + + # `str` overlaps with `Sequence[str]` + # We can ignore this but we must keep this overload ordering + @overload + def __getitem__(self, item: tuple[SingleIndexSelector, SingleColSelector]) -> Any: ... + + @overload + def __getitem__( # type: ignore[overload-overlap] + self, item: str | tuple[MultiIndexSelector, SingleColSelector] + ) -> Series[Any]: ... + + @overload + def __getitem__( + self, + item: ( + SingleIndexSelector + | MultiIndexSelector + | MultiColSelector + | tuple[SingleIndexSelector, MultiColSelector] + | tuple[MultiIndexSelector, MultiColSelector] + ), + ) -> Self: ... + def __getitem__( # noqa: C901, PLR0912 + self, + item: ( + SingleIndexSelector + | SingleColSelector + | MultiColSelector + | MultiIndexSelector + | tuple[SingleIndexSelector, SingleColSelector] + | tuple[SingleIndexSelector, MultiColSelector] + | tuple[MultiIndexSelector, SingleColSelector] + | tuple[MultiIndexSelector, MultiColSelector] + ), + ) -> Series[Any] | Self | Any: + """Extract column or slice of DataFrame. + + Arguments: + item: How to slice dataframe. What happens depends on what is passed. It's easiest + to explain by example. Suppose we have a Dataframe `df` + + - `df['a']` extracts column `'a'` and returns a `Series`. + - `df[0:2]` extracts the first two rows and returns a `DataFrame`. + - `df[0:2, 'a']` extracts the first two rows from column `'a'` and returns + a `Series`. + - `df[0:2, 0]` extracts the first two rows from the first column and returns + a `Series`. + - `df[[0, 1], [0, 1, 2]]` extracts the first two rows and the first three columns + and returns a `DataFrame` + - `df[:, [0, 1, 2]]` extracts all rows from the first three columns and returns a + `DataFrame`. + - `df[:, ['a', 'c']]` extracts all rows and columns `'a'` and `'c'` and returns a + `DataFrame`. + - `df[:, [True, False, True]]` extracts all rows and columns in positions 0 and 2 + and returns a `DataFrame`. + - `df[['a', 'c']]` extracts all rows and columns `'a'` and `'c'` and returns a + `DataFrame`. + - `df[0: 2, ['a', 'c']]` extracts the first two rows and columns `'a'` and `'c'` and + returns a `DataFrame` + - `df[:, 0: 2]` extracts all rows from the first two columns and returns a `DataFrame` + - `df[:, 'a': 'c']` extracts all rows and all columns positioned between `'a'` and `'c'` + _inclusive_ and returns a `DataFrame`. For example, if the columns are + `'a', 'd', 'c', 'b'`, then that would extract columns `'a'`, `'d'`, and `'c'`. + + Notes: + - Integers are always interpreted as positions + - Strings are always interpreted as column names. + + In contrast with Polars, pandas allows non-string column names. + If you don't know whether the column name you're trying to extract + is definitely a string (e.g. `df[df.columns[0]]`) then you should + use `DataFrame.get_column` instead. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2]}) + >>> df = nw.from_native(df_native) + >>> df["a"].to_native() + 0 1 + 1 2 + Name: a, dtype: int64 + """ + from narwhals.series import Series + + msg = ( + f"Unexpected type for `DataFrame.__getitem__`, got: {type(item)}.\n\n" + "Hints:\n" + "- use `df.item` to select a single item.\n" + "- Use `df[indices, :]` to select rows positionally.\n" + "- Use `df.filter(mask)` to filter rows based on a boolean mask." + ) + + if isinstance(item, tuple): + if len(item) > 2: + tuple_msg = ( + "Tuples cannot be passed to DataFrame.__getitem__ directly.\n\n" + "Hint: instead of `df[indices]`, did you mean `df[indices, :]`?" + ) + raise TypeError(tuple_msg) + rows = None if not item or is_slice_none(item[0]) else item[0] + columns = None if len(item) < 2 or is_slice_none(item[1]) else item[1] + if rows is None and columns is None: + return self + elif is_index_selector(item): + rows = item + columns = None + elif is_sequence_like(item) or isinstance(item, (slice, str)): + rows = None + columns = item + else: + raise TypeError(msg) + + if isinstance(rows, str): + raise TypeError(msg) + + compliant = self._compliant_frame + + if isinstance(columns, bool): + raise TypeError(msg) + if isinstance(columns, (int, str)): + if isinstance(rows, int): + return self.item(rows, columns) + col_name = columns if isinstance(columns, str) else self.columns[columns] + series = self.get_column(col_name) + return series[rows] if rows is not None else series + if isinstance(rows, Series): + rows = rows._compliant_series + if isinstance(columns, Series): + columns = columns._compliant_series + if rows is None: + return self._with_compliant(compliant[:, columns]) + if columns is None: + return self._with_compliant(compliant[rows, :]) + return self._with_compliant(compliant[rows, columns]) + + def __contains__(self, key: str) -> bool: + return key in self.columns + + @overload + def to_dict(self, *, as_series: Literal[True] = ...) -> dict[str, Series[Any]]: ... + @overload + def to_dict(self, *, as_series: Literal[False]) -> dict[str, list[Any]]: ... + @overload + def to_dict( + self, *, as_series: bool = True + ) -> dict[str, Series[Any]] | dict[str, list[Any]]: ... + def to_dict( + self, *, as_series: bool = True + ) -> dict[str, Series[Any]] | dict[str, list[Any]]: + """Convert DataFrame to a dictionary mapping column name to values. + + Arguments: + as_series: If set to true ``True``, then the values are Narwhals Series, + otherwise the values are Any. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"A": [1, 2], "fruits": ["banana", "apple"]}) + >>> df = nw.from_native(df_native) + >>> df.to_dict(as_series=False) + {'A': [1, 2], 'fruits': ['banana', 'apple']} + """ + if as_series: + return { + key: self._series(value, level=self._level) + for key, value in self._compliant_frame.to_dict( + as_series=as_series + ).items() + } + return self._compliant_frame.to_dict(as_series=as_series) + + def row(self, index: int) -> tuple[Any, ...]: + """Get values at given row. + + Warning: + You should NEVER use this method to iterate over a DataFrame; + if you require row-iteration you should strongly prefer use of iter_rows() + instead. + + Arguments: + index: Row number. + + Notes: + cuDF doesn't support this method. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [1, 2], "b": [4, 5]}) + >>> nw.from_native(df_native).row(1) + (2, 5) + """ + return self._compliant_frame.row(index) + + # inherited + def pipe( + self, + function: Callable[Concatenate[Self, PS], R], + *args: PS.args, + **kwargs: PS.kwargs, + ) -> R: + """Pipe function call. + + Arguments: + function: Function to apply. + args: Positional arguments to pass to function. + kwargs: Keyword arguments to pass to function. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2], "ba": [4, 5]}) + >>> nw.from_native(df_native).pipe( + ... lambda _df: _df.select( + ... [x for x in _df.columns if len(x) == 1] + ... ).to_native() + ... ) + a + 0 1 + 1 2 + """ + return super().pipe(function, *args, **kwargs) + + def drop_nulls(self, subset: str | list[str] | None = None) -> Self: + """Drop rows that contain null values. + + Arguments: + subset: Column name(s) for which null values are considered. If set to None + (default), use all columns. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md) + for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [1.0, None], "ba": [1.0, 2.0]}) + >>> nw.from_native(df_native).drop_nulls().to_native() + pyarrow.Table + a: double + ba: double + ---- + a: [[1]] + ba: [[1]] + """ + return super().drop_nulls(subset=subset) + + def with_row_index( + self, name: str = "index", *, order_by: str | Sequence[str] | None = None + ) -> Self: + """Insert column which enumerates rows. + + Arguments: + name: The name of the column as a string. The default is "index". + order_by: Column(s) to order by when computing the row index. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [1, 2], "b": [4, 5]}) + >>> nw.from_native(df_native).with_row_index().to_native() + pyarrow.Table + index: int64 + a: int64 + b: int64 + ---- + index: [[0,1]] + a: [[1,2]] + b: [[4,5]] + """ + order_by_ = [order_by] if isinstance(order_by, str) else order_by + return self._with_compliant( + self._compliant_frame.with_row_index(name, order_by=order_by_) + ) + + @property + def schema(self) -> Schema: + r"""Get an ordered mapping of column names to their data type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> nw.from_native(df_native).schema + Schema({'foo': Int64, 'bar': Float64}) + """ + return super().schema + + def collect_schema(self) -> Schema: + r"""Get an ordered mapping of column names to their data type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> nw.from_native(df_native).collect_schema() + Schema({'foo': Int64, 'bar': Float64}) + """ + return super().collect_schema() + + @property + def columns(self) -> list[str]: + """Get column names. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> nw.from_native(df_native).columns + ['foo', 'bar'] + """ + return super().columns + + @overload + def rows(self, *, named: Literal[False] = False) -> list[tuple[Any, ...]]: ... + + @overload + def rows(self, *, named: Literal[True]) -> list[dict[str, Any]]: ... + + @overload + def rows(self, *, named: bool) -> list[tuple[Any, ...]] | list[dict[str, Any]]: ... + + def rows( + self, *, named: bool = False + ) -> list[tuple[Any, ...]] | list[dict[str, Any]]: + """Returns all data in the DataFrame as a list of rows of python-native values. + + Arguments: + named: By default, each row is returned as a tuple of values given + in the same order as the frame columns. Setting named=True will + return rows of dictionaries instead. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> nw.from_native(df_native).rows() + [(1, 6.0), (2, 7.0)] + """ + return self._compliant_frame.rows(named=named) # type: ignore[return-value] + + def iter_columns(self) -> Iterator[Series[Any]]: + """Returns an iterator over the columns of this DataFrame. + + Yields: + A Narwhals Series, backed by a native series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> iter_columns = nw.from_native(df_native).iter_columns() + >>> next(iter_columns) + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 1 | + |1 2 | + |Name: foo, dtype: int64| + └───────────────────────┘ + >>> next(iter_columns) + ┌─────────────────────────┐ + | Narwhals Series | + |-------------------------| + |0 6.0 | + |1 7.0 | + |Name: bar, dtype: float64| + └─────────────────────────┘ + """ + for series in self._compliant_frame.iter_columns(): + yield self._series(series, level=self._level) + + @overload + def iter_rows( + self, *, named: Literal[False] = ..., buffer_size: int = ... + ) -> Iterator[tuple[Any, ...]]: ... + + @overload + def iter_rows( + self, *, named: Literal[True], buffer_size: int = ... + ) -> Iterator[dict[str, Any]]: ... + + @overload + def iter_rows( + self, *, named: bool, buffer_size: int = ... + ) -> Iterator[tuple[Any, ...]] | Iterator[dict[str, Any]]: ... + + def iter_rows( + self, *, named: bool = False, buffer_size: int = 512 + ) -> Iterator[tuple[Any, ...]] | Iterator[dict[str, Any]]: + """Returns an iterator over the DataFrame of rows of python-native values. + + Arguments: + named: By default, each row is returned as a tuple of values given + in the same order as the frame columns. Setting named=True will + return rows of dictionaries instead. + buffer_size: Determines the number of rows that are buffered + internally while iterating over the data. + See https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.iter_rows.html + + Notes: + cuDF doesn't support this method. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> iter_rows = nw.from_native(df_native).iter_rows() + >>> next(iter_rows) + (1, 6.0) + >>> next(iter_rows) + (2, 7.0) + """ + return self._compliant_frame.iter_rows(named=named, buffer_size=buffer_size) # type: ignore[return-value] + + def with_columns( + self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr + ) -> Self: + r"""Add columns to this DataFrame. + + Added columns will replace existing columns with the same name. + + Arguments: + *exprs: Column(s) to add, specified as positional arguments. + Accepts expression input. Strings are parsed as column names, other + non-expression inputs are parsed as literals. + + **named_exprs: Additional columns to add, specified as keyword arguments. + The columns will be renamed to the keyword used. + + Note: + Creating a new DataFrame using this method does not create a new copy of + existing data. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [0.5, 4.0]}) + >>> ( + ... nw.from_native(df_native) + ... .with_columns((nw.col("a") * 2).alias("a*2")) + ... .to_native() + ... ) + a b a*2 + 0 1 0.5 2 + 1 2 4.0 4 + """ + return super().with_columns(*exprs, **named_exprs) + + def select( + self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr + ) -> Self: + r"""Select columns from this DataFrame. + + Arguments: + *exprs: Column(s) to select, specified as positional arguments. + Accepts expression input. Strings are parsed as column names, + other non-expression inputs are parsed as literals. + + **named_exprs: Additional columns to select, specified as keyword arguments. + The columns will be renamed to the keyword used. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [1, 2], "b": [3, 4]}) + >>> nw.from_native(df_native).select("a", a_plus_1=nw.col("a") + 1) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |pyarrow.Table | + |a: int64 | + |a_plus_1: int64 | + |---- | + |a: [[1,2]] | + |a_plus_1: [[2,3]] | + └──────────────────┘ + """ + return super().select(*exprs, **named_exprs) + + def rename(self, mapping: dict[str, str]) -> Self: + """Rename column names. + + Arguments: + mapping: Key value pairs that map from old name to new name. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "bar": [6, 7]}) + >>> nw.from_native(df_native).rename({"foo": "apple"}).to_native() + pyarrow.Table + apple: int64 + bar: int64 + ---- + apple: [[1,2]] + bar: [[6,7]] + """ + return super().rename(mapping) + + def head(self, n: int = 5) -> Self: + """Get the first `n` rows. + + Arguments: + n: Number of rows to return. If a negative value is passed, return all rows + except the last `abs(n)`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [0.5, 4.0]}) + >>> nw.from_native(df_native).head(1).to_native() + a b + 0 1 0.5 + """ + return super().head(n) + + def tail(self, n: int = 5) -> Self: + """Get the last `n` rows. + + Arguments: + n: Number of rows to return. If a negative value is passed, return all rows + except the first `abs(n)`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [0.5, 4.0]}) + >>> nw.from_native(df_native).tail(1) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 1 2 4.0 | + └──────────────────┘ + """ + return super().tail(n) + + def drop(self, *columns: str | Iterable[str], strict: bool = True) -> Self: + """Remove columns from the dataframe. + + Arguments: + *columns: Names of the columns that should be removed from the dataframe. + strict: Validate that all column names exist in the schema and throw an + exception if a column name does not exist in the schema. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"foo": [1, 2], "bar": [6.0, 7.0], "ham": ["a", "b"]} + ... ) + >>> nw.from_native(df_native).drop("ham").to_native() + foo bar + 0 1 6.0 + 1 2 7.0 + """ + return super().drop(*flatten(columns), strict=strict) + + def unique( + self, + subset: str | list[str] | None = None, + *, + keep: UniqueKeepStrategy = "any", + maintain_order: bool = False, + order_by: str | Sequence[str] | None = None, + ) -> Self: + """Drop duplicate rows from this dataframe. + + Arguments: + subset: Column name(s) to consider when identifying duplicate rows. + keep: {'first', 'last', 'any', 'none'} + Which of the duplicate rows to keep. + + * 'any': Does not give any guarantee of which row is kept. + This allows more optimizations. + * 'none': Don't keep duplicate rows. + * 'first': Keep first unique row. + * 'last': Keep last unique row. + maintain_order: Keep the same order as the original DataFrame. This may be more + expensive to compute. + order_by: Column(s) to order by when computing the row index. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"foo": [1, 2], "bar": ["a", "a"], "ham": ["b", "b"]} + ... ) + >>> nw.from_native(df_native).unique(["bar", "ham"]).to_native() + foo bar ham + 0 1 a b + """ + if keep not in {"any", "none", "first", "last"}: + msg = f"Expected {'any', 'none', 'first', 'last'}, got: {keep}" + raise ValueError(msg) + if isinstance(subset, str): + subset = [subset] + return self._with_compliant( + self._compliant_frame.unique( + subset, keep=keep, maintain_order=maintain_order, order_by=order_by + ) + ) + + def filter( + self, *predicates: IntoExpr | Iterable[IntoExpr] | list[bool], **constraints: Any + ) -> Self: + r"""Filter the rows in the DataFrame based on one or more predicate expressions. + + The original order of the remaining rows is preserved. + + Arguments: + *predicates: Expression(s) that evaluates to a boolean Series. Can + also be a boolean list(s). + **constraints: Column filters; use `name = value` to filter columns by the supplied value. + Each constraint will behave the same as `nw.col(name).eq(value)`, and will be implicitly + joined with the other filter conditions using &. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"foo": [1, 2, 3], "bar": [6, 7, 8], "ham": ["a", "b", "c"]} + ... ) + + Filter on one condition + + >>> nw.from_native(df_native).filter(nw.col("foo") > 1).to_native() + foo bar ham + 1 2 7 b + 2 3 8 c + + Filter on multiple conditions with implicit `&` + + >>> nw.from_native(df_native).filter( + ... nw.col("foo") < 3, nw.col("ham") == "a" + ... ).to_native() + foo bar ham + 0 1 6 a + + Filter on multiple conditions with `|` + + >>> nw.from_native(df_native).filter( + ... (nw.col("foo") == 1) | (nw.col("ham") == "c") + ... ).to_native() + foo bar ham + 0 1 6 a + 2 3 8 c + + Filter using `**kwargs` syntax + + >>> nw.from_native(df_native).filter(foo=2, ham="b").to_native() + foo bar ham + 1 2 7 b + """ + impl = self.implementation + parsed_predicates = ( + self._series.from_iterable("", p, backend=impl) if is_list_of(p, bool) else p + for p in predicates + ) + return super().filter(*parsed_predicates, **constraints) + + @overload + def group_by( + self, *keys: IntoExpr | Iterable[IntoExpr], drop_null_keys: Literal[False] = ... + ) -> GroupBy[Self]: ... + + @overload + def group_by( + self, *keys: str | Iterable[str], drop_null_keys: Literal[True] + ) -> GroupBy[Self]: ... + + def group_by( + self, *keys: IntoExpr | Iterable[IntoExpr], drop_null_keys: bool = False + ) -> GroupBy[Self]: + r"""Start a group by operation. + + Arguments: + *keys: Column(s) to group by. Accepts expression input. Strings are parsed as + column names. + drop_null_keys: if True, then groups where any key is null won't be included + in the result. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": ["a", "b", "a", "b", "c"], + ... "b": [1, 2, 1, 3, 3], + ... "c": [5, 4, 3, 2, 1], + ... } + ... ) + + Group by one column and compute the sum of another column + + >>> nw.from_native(df_native, eager_only=True).group_by("a").agg( + ... nw.col("b").sum() + ... ).sort("a").to_native() + a b + 0 a 2 + 1 b 5 + 2 c 3 + + Group by multiple columns and compute the max of another column + + >>> ( + ... nw.from_native(df_native, eager_only=True) + ... .group_by(["a", "b"]) + ... .agg(nw.max("c")) + ... .sort("a", "b") + ... .to_native() + ... ) + a b c + 0 a 1 5 + 1 b 2 4 + 2 b 3 2 + 3 c 3 1 + + Expressions are also accepted. + + >>> nw.from_native(df_native, eager_only=True).group_by( + ... "a", nw.col("b") // 2 + ... ).agg(nw.col("c").mean()).to_native() + a b c + 0 a 0 4.0 + 1 b 1 3.0 + 2 c 1 1.0 + """ + from narwhals.group_by import GroupBy + + flat_keys = flatten(keys) + + if all(isinstance(key, str) for key in flat_keys): + return GroupBy(self, flat_keys, drop_null_keys=drop_null_keys) + + from narwhals import col + from narwhals.expr import Expr + from narwhals.series import Series + + key_is_expr_or_series = tuple(isinstance(k, (Expr, Series)) for k in flat_keys) + + if drop_null_keys and any(key_is_expr_or_series): + msg = "drop_null_keys cannot be True when keys contains Expr or Series" + raise NotImplementedError(msg) + + _keys = [ + k if is_expr else col(k) + for k, is_expr in zip_strict(flat_keys, key_is_expr_or_series) + ] + expr_flat_keys = self._flatten_and_extract(*_keys) + check_expressions_preserve_length( + *expr_flat_keys, function_name="DataFrame.group_by" + ) + return GroupBy(self, expr_flat_keys, drop_null_keys=drop_null_keys) + + def sort( + self, + by: str | Iterable[str], + *more_by: str, + descending: bool | Sequence[bool] = False, + nulls_last: bool = False, + ) -> Self: + r"""Sort the dataframe by the given columns. + + Arguments: + by: Column(s) names to sort by. + *more_by: Additional columns to sort by, specified as positional arguments. + descending: Sort in descending order. When sorting by multiple columns, can be + specified per column by passing a sequence of booleans. + nulls_last: Place null values last. + + Note: + Unlike Polars, it is not possible to specify a sequence of booleans for + `nulls_last` in order to control per-column behaviour. Instead a single + boolean is applied for all `by` columns. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"foo": [2, 1], "bar": [6.0, 7.0], "ham": ["a", "b"]} + ... ) + >>> nw.from_native(df_native).sort("foo") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | foo bar ham | + | 1 1 7.0 b | + | 0 2 6.0 a | + └──────────────────┘ + """ + return super().sort(by, *more_by, descending=descending, nulls_last=nulls_last) + + def top_k( + self, k: int, *, by: str | Iterable[str], reverse: bool | Sequence[bool] = False + ) -> Self: + r"""Return the `k` largest rows. + + Non-null elements are always preferred over null elements, + regardless of the value of reverse. The output is not guaranteed + to be in any particular order, sort the outputs afterwards if you wish the output to be sorted. + + Arguments: + k: Number of rows to return. + by: Column(s) used to determine the top rows. Accepts expression input. Strings are parsed as column names. + reverse: Consider the k smallest elements of the by column(s) (instead of the k largest). + This can be specified per column by passing a sequence of booleans. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": ["a", "b", "a", "b", None, "c"], "b": [2, 1, 1, 3, 2, 1]} + ... ) + >>> nw.from_native(df_native).top_k(4, by=["b", "a"]) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 3 b 3 | + | 0 a 2 | + | 4 NaN 2 | + | 5 c 1 | + └──────────────────┘ + """ + return super().top_k(k, by=by, reverse=reverse) + + def join( + self, + other: Self, + on: str | list[str] | None = None, + how: JoinStrategy = "inner", + *, + left_on: str | list[str] | None = None, + right_on: str | list[str] | None = None, + suffix: str = "_right", + ) -> Self: + r"""Join in SQL-like fashion. + + Arguments: + other: DataFrame to join with. + on: Name(s) of the join columns in both DataFrames. If set, `left_on` and + `right_on` should be None. + how: Join strategy. + + * *inner*: Returns rows that have matching values in both tables. + * *left*: Returns all rows from the left table, and the matched rows from the right table. + * *full*: Returns all rows in both dataframes, with the suffix appended to the right join keys. + * *cross*: Returns the Cartesian product of rows from both tables. + * *semi*: Filter rows that have a match in the right table. + * *anti*: Filter rows that do not have a match in the right table. + left_on: Join column of the left DataFrame. + right_on: Join column of the right DataFrame. + suffix: Suffix to append to columns with a duplicate name. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_1_native = pd.DataFrame({"id": ["a", "b"], "price": [6.0, 7.0]}) + >>> df_2_native = pd.DataFrame({"id": ["a", "b", "c"], "qty": [1, 2, 3]}) + >>> nw.from_native(df_1_native).join(nw.from_native(df_2_native), on="id") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | id price qty | + | 0 a 6.0 1 | + | 1 b 7.0 2 | + └──────────────────┘ + """ + return super().join( + other, how=how, left_on=left_on, right_on=right_on, on=on, suffix=suffix + ) + + def join_asof( + self, + other: Self, + *, + left_on: str | None = None, + right_on: str | None = None, + on: str | None = None, + by_left: str | list[str] | None = None, + by_right: str | list[str] | None = None, + by: str | list[str] | None = None, + strategy: AsofJoinStrategy = "backward", + suffix: str = "_right", + ) -> Self: + """Perform an asof join. + + This is similar to a left-join except that we match on nearest key rather than equal keys. + + For Polars, both DataFrames must be sorted by the `on` key (within each `by` group + if specified). + + Arguments: + other: DataFrame to join with. + left_on: Name(s) of the left join column(s). + right_on: Name(s) of the right join column(s). + on: Join column of both DataFrames. If set, left_on and right_on should be None. + by_left: join on these columns before doing asof join. + by_right: join on these columns before doing asof join. + by: join on these columns before doing asof join. + strategy: Join strategy. The default is "backward". + suffix: Suffix to append to columns with a duplicate name. + + * *backward*: selects the last row in the right DataFrame whose "on" key is less than or equal to the left's key. + * *forward*: selects the first row in the right DataFrame whose "on" key is greater than or equal to the left's key. + * *nearest*: search selects the last row in the right DataFrame whose value is nearest to the left's key. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> data_gdp = { + ... "datetime": [ + ... datetime(2016, 1, 1), + ... datetime(2017, 1, 1), + ... datetime(2018, 1, 1), + ... datetime(2019, 1, 1), + ... datetime(2020, 1, 1), + ... ], + ... "gdp": [4164, 4411, 4566, 4696, 4827], + ... } + >>> data_population = { + ... "datetime": [ + ... datetime(2016, 3, 1), + ... datetime(2018, 8, 1), + ... datetime(2019, 1, 1), + ... ], + ... "population": [82.19, 82.66, 83.12], + ... } + >>> gdp_native = pd.DataFrame(data_gdp) + >>> population_native = pd.DataFrame(data_population) + >>> gdp = nw.from_native(gdp_native) + >>> population = nw.from_native(population_native) + >>> population.join_asof(gdp, on="datetime", strategy="backward") + ┌──────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------| + | datetime population gdp| + |0 2016-03-01 82.19 4164| + |1 2018-08-01 82.66 4566| + |2 2019-01-01 83.12 4696| + └──────────────────────────────┘ + """ + return super().join_asof( + other, + left_on=left_on, + right_on=right_on, + on=on, + by_left=by_left, + by_right=by_right, + by=by, + strategy=strategy, + suffix=suffix, + ) + + # --- descriptive --- + def is_duplicated(self) -> Series[Any]: + r"""Get a mask of all duplicated rows in this DataFrame. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [2, 2, 2], "bar": [6.0, 6.0, 7.0]}) + >>> nw.from_native(df_native).is_duplicated() + ┌───────────────┐ + |Narwhals Series| + |---------------| + | 0 True | + | 1 True | + | 2 False | + | dtype: bool | + └───────────────┘ + """ + return ~self.is_unique() + + def is_empty(self) -> bool: + r"""Check if the dataframe is empty. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [2, 2, 2], "bar": [6.0, 6.0, 7.0]}) + >>> nw.from_native(df_native).is_empty() + False + """ + return len(self) == 0 + + def is_unique(self) -> Series[Any]: + r"""Get a mask of all unique rows in this DataFrame. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [2, 2, 2], "bar": [6.0, 6.0, 7.0]}) + >>> nw.from_native(df_native).is_unique() + ┌───────────────┐ + |Narwhals Series| + |---------------| + | 0 False | + | 1 False | + | 2 True | + | dtype: bool | + └───────────────┘ + """ + return self._series(self._compliant_frame.is_unique(), level=self._level) + + def null_count(self) -> Self: + r"""Create a new DataFrame that shows the null counts per column. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, None], "bar": [2, 3]}) + >>> nw.from_native(df_native).null_count() + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | foo: int64 | + | bar: int64 | + | ---- | + | foo: [[1]] | + | bar: [[0]] | + └──────────────────┘ + """ + plx = self._compliant_frame.__narwhals_namespace__() + result = self._compliant_frame.select(plx.all().null_count()) + return self._with_compliant(result) + + def item(self, row: int | None = None, column: int | str | None = None) -> Any: + r"""Return the DataFrame as a scalar, or return the element at the given row/column. + + Arguments: + row: The *n*-th row. + column: The column selected via an integer or a string (column name). + + Notes: + If row/col not provided, this is equivalent to df[0,0], with a check that the shape is (1,1). + With row/col, this is equivalent to df[row,col]. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, None], "bar": [2, 3]}) + >>> nw.from_native(df_native).item(0, 1) + 2 + """ + return self._compliant_frame.item(row=row, column=column) + + def clone(self) -> Self: + r"""Create a copy of this DataFrame.""" + return self._with_compliant(self._compliant_frame.clone()) + + def gather_every(self, n: int, offset: int = 0) -> Self: + r"""Take every nth row in the DataFrame and return as a new DataFrame. + + Arguments: + n: Gather every *n*-th row. + offset: Starting index. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, None, 2, 3]}) + >>> nw.from_native(df_native).gather_every(2) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | foo: int64 | + | ---- | + | foo: [[1,2]] | + └──────────────────┘ + """ + return super().gather_every(n=n, offset=offset) + + def pivot( + self, + on: str | list[str], + *, + index: str | list[str] | None = None, + values: str | list[str] | None = None, + aggregate_function: PivotAgg | None = None, + maintain_order: bool | None = None, + sort_columns: bool = False, + separator: str = "_", + ) -> Self: + r"""Create a spreadsheet-style pivot table as a DataFrame. + + Arguments: + on: Name of the column(s) whose values will be used as the header of the + output DataFrame. + index: One or multiple keys to group by. If None, all remaining columns not + specified on `on` and `values` will be used. At least one of `index` and + `values` must be specified. + values: One or multiple keys to group by. If None, all remaining columns not + specified on `on` and `index` will be used. At least one of `index` and + `values` must be specified. + aggregate_function: Choose from + + - None: no aggregation takes place, will raise error if multiple values + are in group. + - A predefined aggregate function string, one of + {'min', 'max', 'first', 'last', 'sum', 'mean', 'median', 'len'} + maintain_order: Has no effect and is kept around only for backwards-compatibility. + sort_columns: Sort the transposed columns by name. Default is by order of + discovery. + separator: Used as separator/delimiter in generated column names in case of + multiple `values` columns. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> data = { + ... "ix": [1, 1, 2, 2, 1, 2], + ... "col": ["a", "a", "a", "a", "b", "b"], + ... "foo": [0, 1, 2, 2, 7, 1], + ... "bar": [0, 2, 0, 0, 9, 4], + ... } + >>> df_native = pd.DataFrame(data) + >>> nw.from_native(df_native).pivot( + ... "col", index="ix", aggregate_function="sum" + ... ) + ┌─────────────────────────────────┐ + | Narwhals DataFrame | + |---------------------------------| + | ix foo_a foo_b bar_a bar_b| + |0 1 1 7 2 9| + |1 2 4 1 0 4| + └─────────────────────────────────┘ + """ + if values is None and index is None: + msg = "At least one of `values` and `index` must be passed" + raise ValueError(msg) + if maintain_order is not None: + msg = ( + "`maintain_order` has no effect and is only kept around for backwards-compatibility. " + "You can safely remove this argument." + ) + issue_warning(msg, UserWarning) + on = [on] if isinstance(on, str) else on + values = [values] if isinstance(values, str) else values + index = [index] if isinstance(index, str) else index + + return self._with_compliant( + self._compliant_frame.pivot( + on=on, + index=index, + values=values, + aggregate_function=aggregate_function, + sort_columns=sort_columns, + separator=separator, + ) + ) + + def to_arrow(self) -> pa.Table: + r"""Convert to arrow table. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, None], "bar": [2, 3]}) + >>> nw.from_native(df_native).to_arrow() + pyarrow.Table + foo: double + bar: int64 + ---- + foo: [[1,null]] + bar: [[2,3]] + """ + return self._compliant_frame.to_arrow() + + def sample( + self, + n: int | None = None, + *, + fraction: float | None = None, + with_replacement: bool = False, + seed: int | None = None, + ) -> Self: + r"""Sample from this DataFrame. + + Arguments: + n: Number of items to return. Cannot be used with fraction. + fraction: Fraction of items to return. Cannot be used with n. + with_replacement: Allow values to be sampled more than once. + seed: Seed for the random number generator. If set to None (default), a random + seed is generated for each sample operation. + + Notes: + The results may not be consistent across libraries. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, 2, 3], "bar": [19, 32, 4]}) + >>> nw.from_native(df_native).sample(n=2) # doctest:+SKIP + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | foo bar | + | 2 3 4 | + | 1 2 32 | + └──────────────────┘ + """ + return self._with_compliant( + self._compliant_frame.sample( + n=n, fraction=fraction, with_replacement=with_replacement, seed=seed + ) + ) + + def unpivot( + self, + on: str | list[str] | None = None, + *, + index: str | list[str] | None = None, + variable_name: str = "variable", + value_name: str = "value", + ) -> Self: + r"""Unpivot a DataFrame from wide to long format. + + Optionally leaves identifiers set. + + This function is useful to massage a DataFrame into a format where one or more + columns are identifier variables (index) while all other columns, considered + measured variables (on), are "unpivoted" to the row axis leaving just + two non-identifier columns, 'variable' and 'value'. + + Arguments: + on: Column(s) to use as values variables; if `on` is empty all columns that + are not in `index` will be used. + index: Column(s) to use as identifier variables. + variable_name: Name to give to the `variable` column. Defaults to "variable". + value_name: Name to give to the `value` column. Defaults to "value". + + Notes: + If you're coming from pandas, this is similar to `pandas.DataFrame.melt`, + but with `index` replacing `id_vars` and `on` replacing `value_vars`. + In other frameworks, you might know this operation as `pivot_longer`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> data = {"a": ["x", "y", "z"], "b": [1, 3, 5], "c": [2, 4, 6]} + >>> df_native = pd.DataFrame(data) + >>> nw.from_native(df_native).unpivot(["b", "c"], index="a") + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + | a variable value| + |0 x b 1| + |1 y b 3| + |2 z b 5| + |3 x c 2| + |4 y c 4| + |5 z c 6| + └────────────────────┘ + """ + return super().unpivot( + on=on, index=index, variable_name=variable_name, value_name=value_name + ) + + def explode(self, columns: str | Sequence[str], *more_columns: str) -> Self: + """Explode the dataframe to long format by exploding the given columns. + + Notes: + It is possible to explode multiple columns only if these columns must have + matching element counts. + + Arguments: + columns: Column names. The underlying columns being exploded must be of the `List` data type. + *more_columns: Additional names of columns to explode, specified as positional arguments. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> data = {"a": ["x", "y"], "b": [[1, 2], [3]]} + >>> df_native = pl.DataFrame(data) + >>> nw.from_native(df_native).explode("b").to_native() + shape: (3, 2) + ┌─────┬─────┐ + │ a ┆ b │ + │ --- ┆ --- │ + │ str ┆ i64 │ + ╞═════╪═════╡ + │ x ┆ 1 │ + │ x ┆ 2 │ + │ y ┆ 3 │ + └─────┴─────┘ + """ + return super().explode(columns, *more_columns) + + +class LazyFrame(BaseFrame[LazyFrameT]): + """Narwhals LazyFrame, backed by a native lazyframe. + + Warning: + This class is not meant to be instantiated directly - instead use + [`narwhals.from_native`][] with a native + object that is a lazy dataframe from one of the supported + backend (e.g. polars.LazyFrame, dask_expr._collection.DataFrame): + ```py + narwhals.from_native(native_lazyframe) + ``` + """ + + _version: ClassVar[Version] = Version.MAIN + + @property + def _compliant(self) -> CompliantLazyFrame[Any, LazyFrameT, Self]: + return self._compliant_frame + + @property + def _dataframe(self) -> type[DataFrame[Any]]: + return DataFrame + + def _validate_metadata(self, metadata: ExprMetadata) -> None: + if metadata.n_orderable_ops > 0: + msg = ( + "Order-dependent expressions are not supported for use in LazyFrame.\n\n" + "Hint: To make the expression valid, specify `order_by`.\n\n" + "For example, if you have columns `'price'` and `'date'`:\n" + " - Instead of `nw.col('price').cum_sum()` write `nw.col('price').cum_sum().over(order_by='date')`.\n" + " - Instead of `nw.col('price').diff()` write `nw.col('price').diff().over(order_by='date')`.\n" + " - Instead of `nw.col('price').first()` write `nw.col('price').first().over(order_by='date')`\n" + " or `nw.col('price').first(order_by='date')`.\n\n" + "See https://narwhals-dev.github.io/narwhals/concepts/order_dependence/." + ) + raise InvalidOperationError(msg) + if metadata.is_filtration: + msg = ( + "Length-changing expressions are not supported for use in LazyFrame, unless\n" + "followed by an aggregation.\n\n" + "Hints:\n" + "- Instead of `lf.select(nw.col('a').head())`, use `lf.select('a').head()\n" + "- Instead of `lf.select(nw.col('a').drop_nulls()).select(nw.sum('a'))`,\n" + " use `lf.select(nw.col('a').drop_nulls().sum())\n" + ) + raise InvalidOperationError(msg) + + def __init__(self, df: Any, *, level: Literal["full", "lazy", "interchange"]) -> None: + self._level = level + self._compliant_frame: CompliantLazyFrame[Any, LazyFrameT, Self] + if is_compliant_lazyframe(df): + self._compliant_frame = df.__narwhals_lazyframe__() + else: # pragma: no cover + msg = f"Expected Polars LazyFrame or an object that implements `__narwhals_lazyframe__`, got: {type(df)}" + raise AssertionError(msg) + + def __repr__(self) -> str: # pragma: no cover + return generate_repr("Narwhals LazyFrame", self.to_native().__repr__()) + + def __getitem__(self, item: str | slice) -> NoReturn: + msg = "Slicing is not supported on LazyFrame" + raise TypeError(msg) + + def collect( + self, backend: IntoBackend[Polars | Pandas | Arrow] | None = None, **kwargs: Any + ) -> DataFrame[Any]: + r"""Materialize this LazyFrame into a DataFrame. + + As each underlying lazyframe has different arguments to set when materializing + the lazyframe into a dataframe, we allow to pass them as kwargs (see examples + below for how to generalize the specification). + + Arguments: + backend: specifies which eager backend collect to. This will be the underlying + backend for the resulting Narwhals DataFrame. If None, then the following + default conversions will be applied + + - `polars.LazyFrame` -> `polars.DataFrame` + - `dask.DataFrame` -> `pandas.DataFrame` + - `duckdb.PyRelation` -> `pyarrow.Table` + - `pyspark.DataFrame` -> `pyarrow.Table` + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW` + or `POLARS`. + - As a string: `"pandas"`, `"pyarrow"` or `"polars"` + - Directly as a module `pandas`, `pyarrow` or `polars`. + kwargs: backend specific kwargs to pass along. To know more please check the + backend specific documentation + + - [polars.LazyFrame.collect](https://docs.pola.rs/api/python/dev/reference/lazyframe/api/polars.LazyFrame.collect.html) + - [dask.dataframe.DataFrame.compute](https://docs.dask.org/en/stable/generated/dask.dataframe.DataFrame.compute.html) + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 2), (3, 4) df(a, b)") + >>> lf = nw.from_native(lf_native) + >>> lf + ┌──────────────────┐ + |Narwhals LazyFrame| + |------------------| + |┌───────┬───────┐ | + |│ a │ b │ | + |│ int32 │ int32 │ | + |├───────┼───────┤ | + |│ 1 │ 2 │ | + |│ 3 │ 4 │ | + |└───────┴───────┘ | + └──────────────────┘ + >>> lf.collect() + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int32 | + | b: int32 | + | ---- | + | a: [[1,3]] | + | b: [[2,4]] | + └──────────────────┘ + """ + collect = self._compliant_frame.collect + if backend is None: + return self._dataframe(collect(None, **kwargs), level="full") + eager_backend = Implementation.from_backend(backend) + if can_lazyframe_collect(eager_backend): + return self._dataframe(collect(eager_backend, **kwargs), level="full") + msg = f"Unsupported `backend` value.\nExpected one of {get_args(_LazyFrameCollectImpl)} or None, got: {eager_backend}." + raise ValueError(msg) + + def to_native(self) -> LazyFrameT: + """Convert Narwhals LazyFrame to native one. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 2), (3, 4) df(a, b)") + >>> nw.from_native(lf_native).to_native() + ┌───────┬───────┐ + │ a │ b │ + │ int32 │ int32 │ + ├───────┼───────┤ + │ 1 │ 2 │ + │ 3 │ 4 │ + └───────┴───────┘ + + """ + return to_native(narwhals_object=self, pass_through=False) + + # inherited + def pipe( + self, + function: Callable[Concatenate[Self, PS], R], + *args: PS.args, + **kwargs: PS.kwargs, + ) -> R: + """Pipe function call. + + Arguments: + function: Function to apply. + args: Positional arguments to pass to function. + kwargs: Keyword arguments to pass to function. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 2), (3, 4) df(a, b)") + >>> nw.from_native(lf_native).pipe(lambda x: x.select("a")).to_native() + ┌───────┐ + │ a │ + │ int32 │ + ├───────┤ + │ 1 │ + │ 3 │ + └───────┘ + + """ + return super().pipe(function, *args, **kwargs) + + def drop_nulls(self, subset: str | list[str] | None = None) -> Self: + """Drop rows that contain null values. + + Arguments: + subset: Column name(s) for which null values are considered. If set to None + (default), use all columns. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, NULL), (3, 4) df(a, b)") + >>> nw.from_native(lf_native).drop_nulls() + ┌──────────────────┐ + |Narwhals LazyFrame| + |------------------| + |┌───────┬───────┐ | + |│ a │ b │ | + |│ int32 │ int32 │ | + |├───────┼───────┤ | + |│ 3 │ 4 │ | + |└───────┴───────┘ | + └──────────────────┘ + """ + return super().drop_nulls(subset=subset) + + def with_row_index( + self, name: str = "index", *, order_by: str | Sequence[str] + ) -> Self: + """Insert column which enumerates rows. + + Arguments: + name: The name of the column as a string. The default is "index". + order_by: Column(s) to order by when computing the row index. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 5), (2, 4) df(a, b)") + >>> nw.from_native(lf_native).with_row_index(order_by="a").sort("a").collect() + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | index: int64 | + | a: int32 | + | b: int32 | + | ---- | + | index: [[0,1]] | + | a: [[1,2]] | + | b: [[5,4]] | + └──────────────────┘ + >>> nw.from_native(lf_native).with_row_index(order_by="b").sort("a").collect() + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | index: int64 | + | a: int32 | + | b: int32 | + | ---- | + | index: [[1,0]] | + | a: [[1,2]] | + | b: [[5,4]] | + └──────────────────┘ + """ + order_by_ = [order_by] if isinstance(order_by, str) else order_by + return self._with_compliant( + self._compliant_frame.with_row_index(name, order_by=order_by_) + ) + + @property + def schema(self) -> Schema: + r"""Get an ordered mapping of column names to their data type. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 4.5), (3, 2.) df(a, b)") + >>> nw.from_native(lf_native).schema # doctest:+SKIP + Schema({'a': Int32, 'b': Decimal(precision=2, scale=1)}) + """ + if self._compliant_frame._version is not Version.V1: + msg = ( + "Resolving the schema of a LazyFrame is a potentially expensive operation. " + "Use `LazyFrame.collect_schema()` to get the schema without this warning." + ) + issue_warning(msg, PerformanceWarning) + return super().schema + + def collect_schema(self) -> Schema: + r"""Get an ordered mapping of column names to their data type. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 4.5), (3, 2.) df(a, b)") + >>> nw.from_native(lf_native).collect_schema() + Schema({'a': Int32, 'b': Decimal(precision=2, scale=1)}) + """ + return super().collect_schema() + + @property + def columns(self) -> list[str]: + r"""Get column names. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 4.5), (3, 2.) df(a, b)") + >>> nw.from_native(lf_native).columns + ['a', 'b'] + """ + return super().columns + + def with_columns( + self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr + ) -> Self: + r"""Add columns to this LazyFrame. + + Added columns will replace existing columns with the same name. + + Arguments: + *exprs: Column(s) to add, specified as positional arguments. + Accepts expression input. Strings are parsed as column names, other + non-expression inputs are parsed as literals. + + **named_exprs: Additional columns to add, specified as keyword arguments. + The columns will be renamed to the keyword used. + + Note: + Creating a new LazyFrame using this method does not create a new copy of + existing data. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 4.5), (3, 2.) df(a, b)") + >>> nw.from_native(lf_native).with_columns(c=nw.col("a") + 1) + ┌────────────────────────────────┐ + | Narwhals LazyFrame | + |--------------------------------| + |┌───────┬──────────────┬───────┐| + |│ a │ b │ c │| + |│ int32 │ decimal(2,1) │ int32 │| + |├───────┼──────────────┼───────┤| + |│ 1 │ 4.5 │ 2 │| + |│ 3 │ 2.0 │ 4 │| + |└───────┴──────────────┴───────┘| + └────────────────────────────────┘ + """ + if not exprs and not named_exprs: + msg = "At least one expression must be passed to LazyFrame.with_columns" + raise ValueError(msg) + return super().with_columns(*exprs, **named_exprs) + + def select( + self, *exprs: IntoExpr | Iterable[IntoExpr], **named_exprs: IntoExpr + ) -> Self: + r"""Select columns from this LazyFrame. + + Arguments: + *exprs: Column(s) to select, specified as positional arguments. + Accepts expression input. Strings are parsed as column names. + **named_exprs: Additional columns to select, specified as keyword arguments. + The columns will be renamed to the keyword used. + + Notes: + If you'd like to select a column whose name isn't a string (for example, + if you're working with pandas) then you should explicitly use `nw.col` instead + of just passing the column name. For example, to select a column named + `0` use `df.select(nw.col(0))`, not `df.select(0)`. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 4.5), (3, 2.) df(a, b)") + >>> nw.from_native(lf_native).select("a", a_plus_1=nw.col("a") + 1) + ┌────────────────────┐ + | Narwhals LazyFrame | + |--------------------| + |┌───────┬──────────┐| + |│ a │ a_plus_1 │| + |│ int32 │ int32 │| + |├───────┼──────────┤| + |│ 1 │ 2 │| + |│ 3 │ 4 │| + |└───────┴──────────┘| + └────────────────────┘ + """ + if not exprs and not named_exprs: + msg = "At least one expression must be passed to LazyFrame.select" + raise ValueError(msg) + return super().select(*exprs, **named_exprs) + + def rename(self, mapping: dict[str, str]) -> Self: + r"""Rename column names. + + Arguments: + mapping: Key value pairs that map from old name to new name, or a + function that takes the old name as input and returns the + new name. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 4.5), (3, 2.) df(a, b)") + >>> nw.from_native(lf_native).rename({"a": "c"}) + ┌────────────────────────┐ + | Narwhals LazyFrame | + |------------------------| + |┌───────┬──────────────┐| + |│ c │ b │| + |│ int32 │ decimal(2,1) │| + |├───────┼──────────────┤| + |│ 1 │ 4.5 │| + |│ 3 │ 2.0 │| + |└───────┴──────────────┘| + └────────────────────────┘ + """ + return super().rename(mapping) + + def head(self, n: int = 5) -> Self: + r"""Get `n` rows. + + Arguments: + n: Number of rows to return. + + Examples: + >>> import dask.dataframe as dd + >>> import narwhals as nw + >>> lf_native = dd.from_dict({"a": [1, 2, 3], "b": [4, 5, 6]}, npartitions=1) + >>> nw.from_native(lf_native).head(2).collect() + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 4 | + | 1 2 5 | + └──────────────────┘ + """ + return super().head(n) + + def drop(self, *columns: str | Iterable[str], strict: bool = True) -> Self: + r"""Remove columns from the LazyFrame. + + Arguments: + *columns: Names of the columns that should be removed from the dataframe. + strict: Validate that all column names exist in the schema and throw an + exception if a column name does not exist in the schema. + + Warning: + `strict` argument is ignored for `polars<1.0.0`. + + Please consider upgrading to a newer version or pass to eager mode. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 2), (3, 4) df(a, b)") + >>> nw.from_native(lf_native).drop("a").to_native() + ┌───────┐ + │ b │ + │ int32 │ + ├───────┤ + │ 2 │ + │ 4 │ + └───────┘ + + """ + return super().drop(*flatten(columns), strict=strict) + + def unique( + self, + subset: str | list[str] | None = None, + *, + keep: UniqueKeepStrategy = "any", + order_by: str | Sequence[str] | None = None, + ) -> Self: + """Drop duplicate rows from this LazyFrame. + + Arguments: + subset: Column name(s) to consider when identifying duplicate rows. + If set to `None`, use all columns. + keep: {'any', 'none', 'first', 'last} + Which of the duplicate rows to keep. + + * 'any': Does not give any guarantee of which row is kept. + * 'none': Don't keep duplicate rows. + * 'first': Keep the first row. Requires `order_by` to be specified. + * 'last': Keep the last row. Requires `order_by` to be specified. + order_by: Column(s) to order by when computing the row index. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> lf_native = duckdb.sql("SELECT * FROM VALUES (1, 3), (1, 4) df(a, b)") + >>> nw.from_native(lf_native).unique("a").sort("a", descending=True) + ┌──────────────────┐ + |Narwhals LazyFrame| + |------------------| + |┌───────┬───────┐ | + |│ a │ b │ | + |│ int32 │ int32 │ | + |├───────┼───────┤ | + |│ 1 │ 3 │ | + |└───────┴───────┘ | + └──────────────────┘ + """ + if keep not in {"any", "none", "first", "last"}: + msg = f"Expected {'any', 'none', 'first', 'last'}, got: {keep}" + raise ValueError(msg) + if keep in {"first", "last"} and not order_by: + msg = ( + "narwhals.LazyFrame makes no assumptions about row order, so only " + "'first' and 'last' are only supported if `order_by` is passed." + ) + raise InvalidOperationError(msg) + if isinstance(subset, str): + subset = [subset] + return self._with_compliant( + self._compliant_frame.unique(subset=subset, keep=keep, order_by=order_by) + ) + + def filter( + self, *predicates: IntoExpr | Iterable[IntoExpr], **constraints: Any + ) -> Self: + r"""Filter the rows in the LazyFrame based on a predicate expression. + + The original order of the remaining rows is preserved. + + Arguments: + *predicates: Expression(s) that evaluates to a boolean Series. + **constraints: Column filters; use `name = value` to filter columns by the supplied value. + Each constraint will behave the same as `nw.col(name).eq(value)`, and will be implicitly + joined with the other filter conditions using &. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql(''' + ... SELECT * FROM VALUES + ... (1, 6, 'a'), + ... (2, 7, 'b'), + ... (3, 8, 'c') + ... df(foo, bar, ham) + ... ''') + + Filter on one condition + + >>> nw.from_native(df_native).filter(nw.col("foo") > 1).to_native() + ┌───────┬───────┬─────────┐ + │ foo │ bar │ ham │ + │ int32 │ int32 │ varchar │ + ├───────┼───────┼─────────┤ + │ 2 │ 7 │ b │ + │ 3 │ 8 │ c │ + └───────┴───────┴─────────┘ + + + Filter on multiple conditions with implicit `&` + + >>> nw.from_native(df_native).filter( + ... nw.col("foo") < 3, nw.col("ham") == "a" + ... ).to_native() + ┌───────┬───────┬─────────┐ + │ foo │ bar │ ham │ + │ int32 │ int32 │ varchar │ + ├───────┼───────┼─────────┤ + │ 1 │ 6 │ a │ + └───────┴───────┴─────────┘ + + + Filter on multiple conditions with `|` + + >>> nw.from_native(df_native).filter( + ... (nw.col("foo") == 1) | (nw.col("ham") == "c") + ... ).to_native() + ┌───────┬───────┬─────────┐ + │ foo │ bar │ ham │ + │ int32 │ int32 │ varchar │ + ├───────┼───────┼─────────┤ + │ 1 │ 6 │ a │ + │ 3 │ 8 │ c │ + └───────┴───────┴─────────┘ + + + Filter using `**kwargs` syntax + + >>> nw.from_native(df_native).filter(foo=2, ham="b").to_native() + ┌───────┬───────┬─────────┐ + │ foo │ bar │ ham │ + │ int32 │ int32 │ varchar │ + ├───────┼───────┼─────────┤ + │ 2 │ 7 │ b │ + └───────┴───────┴─────────┘ + + """ + predicates_ = tuple(tuple(p) if is_iterator(p) else p for p in predicates) + if predicates_contains_list_of_bool(predicates_): + msg = "`LazyFrame.filter` is not supported with Python boolean masks - use expressions instead." + raise TypeError(msg) + + return super().filter(*predicates_, **constraints) + + def sink_parquet(self, file: str | Path | BytesIO) -> None: + """Write LazyFrame to Parquet file. + + This may allow larger-than-RAM datasets to be written to disk. + + Arguments: + file: String, path object or file-like object to which the dataframe will be + written. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.LazyFrame({"foo": [1, 2], "bar": [6.0, 7.0]}) + >>> df = nw.from_native(df_native) + >>> df.sink_parquet("out.parquet") # doctest:+SKIP + """ + self._compliant_frame.sink_parquet(file) + + @overload + def group_by( + self, *keys: IntoExpr | Iterable[IntoExpr], drop_null_keys: Literal[False] = ... + ) -> LazyGroupBy[Self]: ... + + @overload + def group_by( + self, *keys: str | Iterable[str], drop_null_keys: Literal[True] + ) -> LazyGroupBy[Self]: ... + + def group_by( + self, *keys: IntoExpr | Iterable[IntoExpr], drop_null_keys: bool = False + ) -> LazyGroupBy[Self]: + r"""Start a group by operation. + + Arguments: + *keys: Column(s) to group by. Accepts expression input. Strings are parsed as + column names. + drop_null_keys: if True, then groups where any key is null won't be + included in the result. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES (1, 'a'), (2, 'b'), (3, 'a') df(a, b)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.group_by("b").agg(nw.col("a").sum()).sort("b").to_native() + ┌─────────┬────────┐ + │ b │ a │ + │ varchar │ int128 │ + ├─────────┼────────┤ + │ a │ 4 │ + │ b │ 2 │ + └─────────┴────────┘ + + + Expressions are also accepted. + + >>> df.group_by(nw.col("b").str.len_chars()).agg( + ... nw.col("a").sum() + ... ).to_native() + ┌───────┬────────┐ + │ b │ a │ + │ int64 │ int128 │ + ├───────┼────────┤ + │ 1 │ 6 │ + └───────┴────────┘ + + """ + from narwhals.group_by import LazyGroupBy + + flat_keys = flatten(keys) + + if all(isinstance(key, str) for key in flat_keys): + return LazyGroupBy(self, flat_keys, drop_null_keys=drop_null_keys) + + from narwhals import col + from narwhals.expr import Expr + + key_is_expr = tuple(isinstance(k, Expr) for k in flat_keys) + + if drop_null_keys and any(key_is_expr): + msg = "drop_null_keys cannot be True when keys contains Expr" + raise NotImplementedError(msg) + + _keys = [ + k if is_expr else col(k) for k, is_expr in zip_strict(flat_keys, key_is_expr) + ] + expr_flat_keys = self._flatten_and_extract(*_keys) + check_expressions_preserve_length( + *expr_flat_keys, function_name="LazyFrame.group_by" + ) + return LazyGroupBy(self, expr_flat_keys, drop_null_keys=drop_null_keys) + + def sort( + self, + by: str | Iterable[str], + *more_by: str, + descending: bool | Sequence[bool] = False, + nulls_last: bool = False, + ) -> Self: + r"""Sort the LazyFrame by the given columns. + + Arguments: + by: Column(s) names to sort by. + *more_by: Additional columns to sort by, specified as positional arguments. + descending: Sort in descending order. When sorting by multiple columns, can be + specified per column by passing a sequence of booleans. + nulls_last: Place null values last; can specify a single boolean applying to + all columns or a sequence of booleans for per-column control. + + Warning: + Unlike Polars, it is not possible to specify a sequence of booleans for + `nulls_last` in order to control per-column behaviour. Instead a single + boolean is applied for all `by` columns. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES (1, 6.0, 'a'), (2, 5.0, 'c'), (NULL, 4.0, 'b') df(a, b, c)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.sort("a") + ┌──────────────────────────────────┐ + | Narwhals LazyFrame | + |----------------------------------| + |┌───────┬──────────────┬─────────┐| + |│ a │ b │ c │| + |│ int32 │ decimal(2,1) │ varchar │| + |├───────┼──────────────┼─────────┤| + |│ NULL │ 4.0 │ b │| + |│ 1 │ 6.0 │ a │| + |│ 2 │ 5.0 │ c │| + |└───────┴──────────────┴─────────┘| + └──────────────────────────────────┘ + """ + return super().sort(by, *more_by, descending=descending, nulls_last=nulls_last) + + def top_k( + self, k: int, *, by: str | Iterable[str], reverse: bool | Sequence[bool] = False + ) -> Self: + r"""Return the `k` largest rows. + + Non-null elements are always preferred over null elements, + regardless of the value of reverse. The output is not guaranteed + to be in any particular order, sort the outputs afterwards if you wish the output to be sorted. + + Arguments: + k: Number of rows to return. + by: Column(s) used to determine the top rows. Accepts expression input. Strings are parsed as column names. + reverse: Consider the k smallest elements of the by column(s) (instead of the k largest). + This can be specified per column by passing a sequence of booleans. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES ('a', 2), ('b', 1), ('a', 1), ('b', 3), (NULL, 2), ('c', 1) df(a, b)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.top_k(4, by=["b", "a"]) + ┌───────────────────┐ + |Narwhals LazyFrame | + |-------------------| + |┌─────────┬───────┐| + |│ a │ b │| + |│ varchar │ int32 │| + |├─────────┼───────┤| + |│ b │ 3 │| + |│ a │ 2 │| + |│ NULL │ 2 │| + |│ c │ 1 │| + |└─────────┴───────┘| + └───────────────────┘ + """ + return super().top_k(k, by=by, reverse=reverse) + + def join( + self, + other: Self, + on: str | list[str] | None = None, + how: JoinStrategy = "inner", + *, + left_on: str | list[str] | None = None, + right_on: str | list[str] | None = None, + suffix: str = "_right", + ) -> Self: + r"""Add a join operation to the Logical Plan. + + Arguments: + other: Lazy DataFrame to join with. + on: Name(s) of the join columns in both DataFrames. If set, `left_on` and + `right_on` should be None. + how: Join strategy. + + * *inner*: Returns rows that have matching values in both tables. + * *left*: Returns all rows from the left table, and the matched rows from the right table. + * *full*: Returns all rows in both dataframes, with the suffix appended to the right join keys. + * *cross*: Returns the Cartesian product of rows from both tables. + * *semi*: Filter rows that have a match in the right table. + * *anti*: Filter rows that do not have a match in the right table. + left_on: Join column of the left DataFrame. + right_on: Join column of the right DataFrame. + suffix: Suffix to append to columns with a duplicate name. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native1 = duckdb.sql( + ... "SELECT * FROM VALUES (1, 'a'), (2, 'b') df(a, b)" + ... ) + >>> df_native2 = duckdb.sql( + ... "SELECT * FROM VALUES (1, 'x'), (3, 'y') df(a, c)" + ... ) + >>> df1 = nw.from_native(df_native1) + >>> df2 = nw.from_native(df_native2) + >>> df1.join(df2, on="a") + ┌─────────────────────────────┐ + | Narwhals LazyFrame | + |-----------------------------| + |┌───────┬─────────┬─────────┐| + |│ a │ b │ c │| + |│ int32 │ varchar │ varchar │| + |├───────┼─────────┼─────────┤| + |│ 1 │ a │ x │| + |└───────┴─────────┴─────────┘| + └─────────────────────────────┘ + """ + return super().join( + other, how=how, left_on=left_on, right_on=right_on, on=on, suffix=suffix + ) + + def join_asof( + self, + other: Self, + *, + left_on: str | None = None, + right_on: str | None = None, + on: str | None = None, + by_left: str | list[str] | None = None, + by_right: str | list[str] | None = None, + by: str | list[str] | None = None, + strategy: AsofJoinStrategy = "backward", + suffix: str = "_right", + ) -> Self: + """Perform an asof join. + + This is similar to a left-join except that we match on nearest key rather than equal keys. + + For Polars, both DataFrames must be sorted by the `on` key (within each `by` group + if specified). + + Arguments: + other: DataFrame to join with. + left_on: Name(s) of the left join column(s). + right_on: Name(s) of the right join column(s). + on: Join column of both DataFrames. If set, left_on and right_on should be None. + by_left: join on these columns before doing asof join + by_right: join on these columns before doing asof join + by: join on these columns before doing asof join + strategy: Join strategy. The default is "backward". + + * *backward*: selects the last row in the right DataFrame whose "on" key is less than or equal to the left's key. + * *forward*: selects the first row in the right DataFrame whose "on" key is greater than or equal to the left's key. + * *nearest*: search selects the last row in the right DataFrame whose value is nearest to the left's key. + + suffix: Suffix to append to columns with a duplicate name. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> data_gdp = { + ... "datetime": [ + ... datetime(2016, 1, 1), + ... datetime(2017, 1, 1), + ... datetime(2018, 1, 1), + ... datetime(2019, 1, 1), + ... datetime(2020, 1, 1), + ... ], + ... "gdp": [4164, 4411, 4566, 4696, 4827], + ... } + >>> data_population = { + ... "datetime": [ + ... datetime(2016, 3, 1), + ... datetime(2018, 8, 1), + ... datetime(2019, 1, 1), + ... ], + ... "population": [82.19, 82.66, 83.12], + ... } + >>> gdp_native = pl.DataFrame(data_gdp) + >>> population_native = pl.DataFrame(data_population) + >>> gdp = nw.from_native(gdp_native) + >>> population = nw.from_native(population_native) + >>> population.join_asof(gdp, on="datetime", strategy="backward").to_native() + shape: (3, 3) + ┌─────────────────────┬────────────┬──────┐ + │ datetime ┆ population ┆ gdp │ + │ --- ┆ --- ┆ --- │ + │ datetime[μs] ┆ f64 ┆ i64 │ + ╞═════════════════════╪════════════╪══════╡ + │ 2016-03-01 00:00:00 ┆ 82.19 ┆ 4164 │ + │ 2018-08-01 00:00:00 ┆ 82.66 ┆ 4566 │ + │ 2019-01-01 00:00:00 ┆ 83.12 ┆ 4696 │ + └─────────────────────┴────────────┴──────┘ + """ + return super().join_asof( + other, + left_on=left_on, + right_on=right_on, + on=on, + by_left=by_left, + by_right=by_right, + by=by, + strategy=strategy, + suffix=suffix, + ) + + def lazy(self) -> Self: + """Restrict available API methods to lazy-only ones. + + This is a no-op, and exists only for compatibility with `DataFrame.lazy`. + """ + return self + + def unpivot( + self, + on: str | list[str] | None = None, + *, + index: str | list[str] | None = None, + variable_name: str = "variable", + value_name: str = "value", + ) -> Self: + r"""Unpivot a DataFrame from wide to long format. + + Optionally leaves identifiers set. + + This function is useful to massage a DataFrame into a format where one or more + columns are identifier variables (index) while all other columns, considered + measured variables (on), are "unpivoted" to the row axis leaving just + two non-identifier columns, 'variable' and 'value'. + + Arguments: + on: Column(s) to use as values variables; if `on` is empty all columns that + are not in `index` will be used. + index: Column(s) to use as identifier variables. + variable_name: Name to give to the `variable` column. Defaults to "variable". + value_name: Name to give to the `value` column. Defaults to "value". + + Notes: + If you're coming from pandas, this is similar to `pandas.DataFrame.melt`, + but with `index` replacing `id_vars` and `on` replacing `value_vars`. + In other frameworks, you might know this operation as `pivot_longer`. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES ('x', 1, 2), ('y', 3, 4), ('z', 5, 6) df(a, b, c)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.unpivot(on=["b", "c"], index="a").sort("a", "variable").to_native() + ┌─────────┬──────────┬───────┐ + │ a │ variable │ value │ + │ varchar │ varchar │ int32 │ + ├─────────┼──────────┼───────┤ + │ x │ b │ 1 │ + │ x │ c │ 2 │ + │ y │ b │ 3 │ + │ y │ c │ 4 │ + │ z │ b │ 5 │ + │ z │ c │ 6 │ + └─────────┴──────────┴───────┘ + + """ + return super().unpivot( + on=on, index=index, variable_name=variable_name, value_name=value_name + ) + + def explode(self, columns: str | Sequence[str], *more_columns: str) -> Self: + """Explode the dataframe to long format by exploding the given columns. + + Notes: + It is possible to explode multiple columns only if these columns have + matching element counts. + + Arguments: + columns: Column names. The underlying columns being exploded must be of the `List` data type. + *more_columns: Additional names of columns to explode, specified as positional arguments. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES ('x', [1, 2]), ('y', [3, 4]), ('z', [5, 6]) df(a, b)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.explode("b").to_native() + ┌─────────┬───────┐ + │ a │ b │ + │ varchar │ int32 │ + ├─────────┼───────┤ + │ x │ 1 │ + │ x │ 2 │ + │ y │ 3 │ + │ y │ 4 │ + │ z │ 5 │ + │ z │ 6 │ + └─────────┴───────┘ + + """ + return super().explode(columns, *more_columns) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/dependencies.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7830166d83ed36263fa4dc14e8c169929eace7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/dependencies.py @@ -0,0 +1,631 @@ +# pandas / Polars / etc. : if a user passes a dataframe from one of these +# libraries, it means they must already have imported the given module. +# So, we can just check sys.modules. +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING, Any + +from narwhals._exceptions import issue_warning + +if TYPE_CHECKING: + import cudf + import dask.dataframe as dd + import duckdb + import ibis + import modin.pandas as mpd + import pandas as pd + import polars as pl + import pyarrow as pa + import pyspark.sql as pyspark_sql + from pyspark.sql.connect.dataframe import DataFrame as PySparkConnectDataFrame + from typing_extensions import TypeGuard, TypeIs + + from narwhals._spark_like.dataframe import SQLFrameDataFrame + from narwhals.dataframe import DataFrame, LazyFrame + from narwhals.series import Series + from narwhals.typing import ( + IntoDataFrameT, + IntoLazyFrameT, + IntoSeriesT, + PandasLikeDType, + _1DArray, + _1DArrayInt, + _2DArray, + _NDArray, + _NumpyScalar, + _ShapeT, + ) + + +# We silently allow these but - given that they claim +# to be drop-in replacements for pandas - testing is +# their responsibility. +IMPORT_HOOKS = frozenset(["fireducks"]) + + +def get_polars() -> Any: + """Get Polars module (if already imported - else return None).""" + return sys.modules.get("polars", None) + + +def get_pandas() -> Any: + """Get pandas module (if already imported - else return None).""" + return sys.modules.get("pandas", None) + + +def get_modin() -> Any: # pragma: no cover + """Get modin.pandas module (if already imported - else return None).""" + return sys.modules.get("modin.pandas", None) + + +def get_cudf() -> Any: + """Get cudf module (if already imported - else return None).""" + return sys.modules.get("cudf", None) + + +def get_cupy() -> Any: + """Get cupy module (if already imported - else return None).""" + return sys.modules.get("cupy", None) + + +def get_pyarrow() -> Any: # pragma: no cover + """Get pyarrow module (if already imported - else return None).""" + return sys.modules.get("pyarrow", None) + + +def get_numpy() -> Any: + """Get numpy module (if already imported - else return None).""" + return sys.modules.get("numpy", None) + + +def get_dask() -> Any: # pragma: no cover + """Get dask (if already imported - else return None).""" + return sys.modules.get("dask", None) + + +def get_dask_dataframe() -> Any: + """Get dask.dataframe module (if already imported - else return None).""" + return sys.modules.get("dask.dataframe", None) + + +def get_duckdb() -> Any: + """Get duckdb module (if already imported - else return None).""" + return sys.modules.get("duckdb", None) + + +def get_ibis() -> Any: + """Get ibis module (if already imported - else return None).""" + return sys.modules.get("ibis", None) + + +def get_dask_expr() -> Any: # pragma: no cover + """Get dask_expr module (if already imported - else return None).""" + if (dd := get_dask_dataframe()) is not None and hasattr(dd, "dask_expr"): + return dd.dask_expr + return sys.modules.get("dask_expr", None) + + +def get_pyspark() -> Any: # pragma: no cover + """Get pyspark module (if already imported - else return None).""" + return sys.modules.get("pyspark", None) + + +def get_pyspark_sql() -> Any: + """Get pyspark.sql module (if already imported - else return None).""" + return sys.modules.get("pyspark.sql", None) + + +def get_pyspark_connect() -> Any: + """Get pyspark.sql.connect module (if already imported - else return None).""" + return sys.modules.get("pyspark.sql.connect", None) + + +def get_sqlframe() -> Any: + """Get sqlframe module (if already imported - else return None).""" + return sys.modules.get("sqlframe", None) + + +def _warn_if_narwhals_df_or_lf(df: Any) -> None: + if is_narwhals_dataframe(df) or is_narwhals_lazyframe(df): + msg = ( + f"You passed a `{type(df)}` to `is_pandas_dataframe`.\n\n" + "Hint: Instead of e.g. `is_pandas_dataframe(df)`, " + "did you mean `is_pandas_dataframe(df.to_native())`?" + ) + issue_warning(msg, UserWarning) + + +def _warn_if_narwhals_series(ser: Any) -> None: + if is_narwhals_series(ser): + msg = ( + f"You passed a `{type(ser)}` to `is_pandas_series`.\n\n" + "Hint: Instead of e.g. `is_pandas_series(ser)`, " + "did you mean `is_pandas_series(ser.to_native())`?" + ) + issue_warning(msg, UserWarning) + + +def is_pandas_dataframe(df: Any) -> TypeIs[pd.DataFrame]: + """Check whether `df` is a pandas DataFrame without importing pandas. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return ((pd := get_pandas()) is not None and isinstance(df, pd.DataFrame)) or any( + (mod := sys.modules.get(module_name, None)) is not None + and isinstance(df, mod.pandas.DataFrame) + for module_name in IMPORT_HOOKS + ) + + +def is_pandas_series(ser: Any) -> TypeIs[pd.Series[Any]]: + """Check whether `ser` is a pandas Series without importing pandas. + + Warning: + This method cannot be called on Narwhals Series. + """ + _warn_if_narwhals_series(ser) + return ((pd := get_pandas()) is not None and isinstance(ser, pd.Series)) or any( + (mod := sys.modules.get(module_name, None)) is not None + and isinstance(ser, mod.pandas.Series) + for module_name in IMPORT_HOOKS + ) + + +def is_pandas_index(index: Any) -> TypeIs[pd.Index[Any]]: + """Check whether `index` is a pandas Index without importing pandas.""" + return ((pd := get_pandas()) is not None and isinstance(index, pd.Index)) or any( + (mod := sys.modules.get(module_name, None)) is not None + and isinstance(index, mod.pandas.Index) + for module_name in IMPORT_HOOKS + ) + + +def is_modin_dataframe(df: Any) -> TypeIs[mpd.DataFrame]: + """Check whether `df` is a modin DataFrame without importing modin. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (mpd := get_modin()) is not None and isinstance(df, mpd.DataFrame) + + +def is_modin_series(ser: Any) -> TypeIs[mpd.Series]: + """Check whether `ser` is a modin Series without importing modin. + + Warning: + This method cannot be called on Narwhals Series. + """ + _warn_if_narwhals_series(ser) + return (mpd := get_modin()) is not None and isinstance(ser, mpd.Series) + + +def is_modin_index(index: Any) -> TypeIs[mpd.Index[Any]]: # pragma: no cover + """Check whether `index` is a modin Index without importing modin.""" + return (mpd := get_modin()) is not None and isinstance(index, mpd.Index) + + +def is_cudf_dataframe(df: Any) -> TypeIs[cudf.DataFrame]: + """Check whether `df` is a cudf DataFrame without importing cudf. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (cudf := get_cudf()) is not None and isinstance(df, cudf.DataFrame) + + +def is_cudf_series(ser: Any) -> TypeIs[cudf.Series[Any]]: + """Check whether `ser` is a cudf Series without importing cudf. + + Warning: + This method cannot be called on Narwhals Series. + """ + _warn_if_narwhals_series(ser) + return (cudf := get_cudf()) is not None and isinstance(ser, cudf.Series) + + +def is_cudf_index(index: Any) -> TypeIs[cudf.Index]: + """Check whether `index` is a cudf Index without importing cudf.""" + return (cudf := get_cudf()) is not None and isinstance( + index, cudf.Index + ) # pragma: no cover + + +def is_cupy_scalar(obj: Any) -> bool: + return ( + (cupy := get_cupy()) is not None + and isinstance(obj, cupy.ndarray) + and obj.size == 1 + ) # pragma: no cover + + +def is_dask_dataframe(df: Any) -> TypeIs[dd.DataFrame]: + """Check whether `df` is a Dask DataFrame without importing Dask. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (dd := get_dask_dataframe()) is not None and isinstance(df, dd.DataFrame) + + +def is_duckdb_relation(df: Any) -> TypeIs[duckdb.DuckDBPyRelation]: + """Check whether `df` is a DuckDB Relation without importing DuckDB. + + Warning: + This method cannot be called on Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (duckdb := get_duckdb()) is not None and isinstance( + df, duckdb.DuckDBPyRelation + ) + + +def is_ibis_table(df: Any) -> TypeIs[ibis.Table]: + """Check whether `df` is a Ibis Table without importing Ibis. + + Warning: + This method cannot be called on Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (ibis := get_ibis()) is not None and isinstance(df, ibis.expr.types.Table) + + +def is_polars_dataframe(df: Any) -> TypeIs[pl.DataFrame]: + """Check whether `df` is a Polars DataFrame without importing Polars. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (pl := get_polars()) is not None and isinstance(df, pl.DataFrame) + + +def is_polars_lazyframe(df: Any) -> TypeIs[pl.LazyFrame]: + """Check whether `df` is a Polars LazyFrame without importing Polars. + + Warning: + This method cannot be called on Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (pl := get_polars()) is not None and isinstance(df, pl.LazyFrame) + + +def is_polars_series(ser: Any) -> TypeIs[pl.Series]: + """Check whether `ser` is a Polars Series without importing Polars. + + Warning: + This method cannot be called on Narwhals Series. + """ + _warn_if_narwhals_series(ser) + return (pl := get_polars()) is not None and isinstance(ser, pl.Series) + + +def is_polars_schema(obj: Any) -> TypeIs[pl.Schema]: + return ( + bool(pl := get_polars()) and hasattr(pl, "Schema") and isinstance(obj, pl.Schema) + ) + + +# NOTE: For `pl.Schema` only instantiated dtypes are expected +def is_polars_data_type(obj: Any) -> TypeIs[pl.DataType]: + return bool(pl := get_polars()) and isinstance(obj, pl.DataType) + + +def is_pyarrow_chunked_array(ser: Any) -> TypeIs[pa.ChunkedArray[Any]]: + """Check whether `ser` is a PyArrow ChunkedArray without importing PyArrow. + + Warning: + This method cannot be called on Narwhals Series. + """ + _warn_if_narwhals_series(ser) + return (pa := get_pyarrow()) is not None and isinstance(ser, pa.ChunkedArray) + + +def is_pyarrow_table(df: Any) -> TypeIs[pa.Table]: + """Check whether `df` is a PyArrow Table without importing PyArrow. + + Warning: + This method cannot be called on Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return (pa := get_pyarrow()) is not None and isinstance(df, pa.Table) + + +def is_pyarrow_scalar(obj: Any) -> TypeIs[pa.Scalar[Any]]: + return (pa := get_pyarrow()) is not None and isinstance(obj, pa.Scalar) + + +def is_pyarrow_schema(obj: Any) -> TypeIs[pa.Schema]: + return bool(pa := get_pyarrow()) and isinstance(obj, pa.Schema) + + +def is_pyarrow_data_type(obj: Any) -> TypeIs[pa.DataType]: + return bool(pa := get_pyarrow()) and isinstance(obj, pa.DataType) + + +def is_pyspark_dataframe(df: Any) -> TypeIs[pyspark_sql.DataFrame]: + """Check whether `df` is a PySpark DataFrame without importing PySpark. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return bool( + (pyspark_sql := get_pyspark_sql()) is not None + and isinstance(df, pyspark_sql.DataFrame) + ) + + +def is_pyspark_connect_dataframe(df: Any) -> TypeIs[PySparkConnectDataFrame]: + """Check whether `df` is a PySpark Connect DataFrame without importing PySpark. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + if get_pyspark_connect() is not None: # pragma: no cover + try: + from pyspark.sql.connect.dataframe import DataFrame + except ImportError: + return False + return isinstance(df, DataFrame) + return False + + +def is_sqlframe_dataframe(df: Any) -> TypeIs[SQLFrameDataFrame]: + """Check whether `df` is a SQLFrame DataFrame without importing SQLFrame. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + if get_sqlframe() is not None: + from sqlframe.base.dataframe import BaseDataFrame + + return isinstance(df, BaseDataFrame) + return False # pragma: no cover + + +def is_numpy_array(arr: Any | _NDArray[_ShapeT]) -> TypeIs[_NDArray[_ShapeT]]: + """Check whether `arr` is a NumPy Array without importing NumPy.""" + return (np := get_numpy()) is not None and isinstance(arr, np.ndarray) + + +def is_numpy_array_1d(arr: Any) -> TypeIs[_1DArray]: + """Check whether `arr` is a 1D NumPy Array without importing NumPy.""" + return is_numpy_array(arr) and arr.ndim == 1 + + +def is_numpy_array_1d_int(arr: Any) -> TypeIs[_1DArrayInt]: + return ( + (np := get_numpy()) + and is_numpy_array_1d(arr) + and np.issubdtype(arr.dtype, np.integer) + ) + + +def is_numpy_array_1d_bool(arr: Any) -> TypeIs[_1DArrayInt]: + return ( + (np := get_numpy()) + and is_numpy_array_1d(arr) + and np.issubdtype(arr.dtype, np.bool_) + ) + + +def is_numpy_array_2d(arr: Any) -> TypeIs[_2DArray]: + """Check whether `arr` is a 2D NumPy Array without importing NumPy.""" + return is_numpy_array(arr) and arr.ndim == 2 + + +def is_numpy_scalar(scalar: Any) -> TypeGuard[_NumpyScalar]: + """Check whether `scalar` is a NumPy Scalar without importing NumPy.""" + # NOTE: Needs to stay as `TypeGuard` + # - Used in `Series.__getitem__`, but not annotated + # - `TypeGuard` is *hiding* that the check introduces an intersection + return (np := get_numpy()) is not None and isinstance(scalar, np.generic) + + +def is_pandas_like_dataframe(df: Any) -> bool: + """Check whether `df` is a pandas-like DataFrame without doing any imports. + + By "pandas-like", we mean: pandas, Modin, cuDF. + + Warning: + This method cannot be called on a Narwhals DataFrame/LazyFrame. + """ + _warn_if_narwhals_df_or_lf(df) + return is_pandas_dataframe(df) or is_modin_dataframe(df) or is_cudf_dataframe(df) + + +def is_pandas_like_series(ser: Any) -> bool: + """Check whether `ser` is a pandas-like Series without doing any imports. + + By "pandas-like", we mean: pandas, Modin, cuDF. + + Warning: + This method cannot be called on Narwhals Series. + """ + _warn_if_narwhals_series(ser) + return is_pandas_series(ser) or is_modin_series(ser) or is_cudf_series(ser) + + +def is_pandas_like_index(index: Any) -> bool: + """Check whether `index` is a pandas-like Index without doing any imports. + + By "pandas-like", we mean: pandas, Modin, cuDF. + """ + return ( + is_pandas_index(index) or is_modin_index(index) or is_cudf_index(index) + ) # pragma: no cover + + +def is_pandas_like_dtype(obj: Any) -> TypeIs[PandasLikeDType]: + return bool(pd := get_pandas()) and isinstance( + obj, (pd.api.extensions.ExtensionDtype, get_numpy().dtype) + ) + + +def is_cudf_dtype( + obj: Any, +) -> TypeIs[pd.api.extensions.ExtensionDtype]: # pragma: no cover + return ( + bool(pd := get_pandas()) + and isinstance(obj, (pd.api.extensions.ExtensionDtype)) + and hasattr(obj, "to_arrow") + ) + + +def is_into_series(native_series: Any | IntoSeriesT) -> TypeIs[IntoSeriesT]: + """Check whether `native_series` can be converted to a Narwhals Series. + + Arguments: + native_series: The object to check. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import numpy as np + >>> import narwhals as nw + + >>> s_pd = pd.Series([1, 2, 3]) + >>> s_pl = pl.Series([1, 2, 3]) + >>> np_arr = np.array([1, 2, 3]) + + >>> nw.dependencies.is_into_series(s_pd) + True + >>> nw.dependencies.is_into_series(s_pl) + True + >>> nw.dependencies.is_into_series(np_arr) + False + """ + from narwhals.series import Series + + return ( + isinstance(native_series, Series) + or hasattr(native_series, "__narwhals_series__") + or is_polars_series(native_series) + or is_pyarrow_chunked_array(native_series) + or is_pandas_like_series(native_series) + ) + + +def is_into_dataframe(native_dataframe: Any | IntoDataFrameT) -> TypeIs[IntoDataFrameT]: + """Check whether `native_dataframe` can be converted to a Narwhals DataFrame. + + Arguments: + native_dataframe: The object to check. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import numpy as np + >>> from narwhals.dependencies import is_into_dataframe + + >>> df_pd = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + >>> df_pl = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + >>> np_arr = np.array([[1, 4], [2, 5], [3, 6]]) + + >>> is_into_dataframe(df_pd) + True + >>> is_into_dataframe(df_pl) + True + >>> is_into_dataframe(np_arr) + False + """ + from narwhals.dataframe import DataFrame + + return ( + isinstance(native_dataframe, DataFrame) + or hasattr(native_dataframe, "__narwhals_dataframe__") + or is_polars_dataframe(native_dataframe) + or is_pyarrow_table(native_dataframe) + or is_pandas_like_dataframe(native_dataframe) + ) + + +def is_narwhals_dataframe( + df: DataFrame[IntoDataFrameT] | Any, +) -> TypeIs[DataFrame[IntoDataFrameT]]: + """Check whether `df` is a Narwhals DataFrame. + + This is useful if you expect a user to pass in a Narwhals + DataFrame directly, and you want to catch both `narwhals.DataFrame` + and `narwhals.stable.v1.DataFrame`. + """ + from narwhals.dataframe import DataFrame + + return isinstance(df, DataFrame) + + +def is_narwhals_lazyframe( + lf: Any | LazyFrame[IntoLazyFrameT], +) -> TypeIs[LazyFrame[IntoLazyFrameT]]: + """Check whether `lf` is a Narwhals LazyFrame. + + This is useful if you expect a user to pass in a Narwhals + LazyFrame directly, and you want to catch both `narwhals.LazyFrame` + and `narwhals.stable.v1.LazyFrame`. + """ + from narwhals.dataframe import LazyFrame + + return isinstance(lf, LazyFrame) + + +def is_narwhals_series(ser: Any | Series[IntoSeriesT]) -> TypeIs[Series[IntoSeriesT]]: + """Check whether `ser` is a Narwhals Series. + + This is useful if you expect a user to pass in a Narwhals + Series directly, and you want to catch both `narwhals.Series` + and `narwhals.stable.v1.Series`. + """ + from narwhals.series import Series + + return isinstance(ser, Series) + + +def is_narwhals_series_int(ser: Any | Series[IntoSeriesT]) -> TypeIs[Series[IntoSeriesT]]: + return is_narwhals_series(ser) and ser.dtype.is_integer() + + +def is_narwhals_series_bool( + ser: Any | Series[IntoSeriesT], +) -> TypeIs[Series[IntoSeriesT]]: + return is_narwhals_series(ser) and ser.dtype.is_boolean() + + +__all__ = [ + "get_cudf", + "get_ibis", + "get_modin", + "get_numpy", + "get_pandas", + "get_polars", + "get_pyarrow", + "is_cudf_dataframe", + "is_cudf_series", + "is_dask_dataframe", + "is_ibis_table", + "is_into_dataframe", + "is_into_series", + "is_modin_dataframe", + "is_modin_series", + "is_narwhals_dataframe", + "is_narwhals_lazyframe", + "is_narwhals_series", + "is_numpy_array", + "is_pandas_dataframe", + "is_pandas_index", + "is_pandas_like_dataframe", + "is_pandas_like_series", + "is_pandas_series", + "is_polars_dataframe", + "is_polars_lazyframe", + "is_polars_series", + "is_pyarrow_chunked_array", + "is_pyarrow_table", +] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/dtypes.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..587b6c2758a34b0fb6711cdcbc4f7a73a0ddeb57 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/dtypes.py @@ -0,0 +1,1042 @@ +from __future__ import annotations + +import enum +from collections import OrderedDict +from collections.abc import Iterable, Mapping +from datetime import timezone +from itertools import starmap +from typing import TYPE_CHECKING + +from narwhals._utils import ( + _DeferredIterable, + isinstance_or_issubclass, + qualified_type_name, +) +from narwhals.exceptions import InvalidOperationError + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + from typing import Any + + import _typeshed + from typing_extensions import Self, TypeIs + + from narwhals.typing import IntoDType, TimeUnit + + +def _validate_dtype(dtype: DType | type[DType]) -> None: + if not isinstance_or_issubclass(dtype, DType): + msg = ( + f"Expected Narwhals dtype, got: {type(dtype)}.\n\n" + "Hint: if you were trying to cast to a type, use e.g. nw.Int64 instead of 'int64'." + ) + raise TypeError(msg) + + +def _is_into_dtype(obj: Any) -> TypeIs[IntoDType]: + return isinstance(obj, DType) or ( + isinstance(obj, DTypeClass) and not issubclass(obj, NestedType) + ) + + +def _is_nested_type(obj: Any) -> TypeIs[type[NestedType]]: + return isinstance(obj, DTypeClass) and issubclass(obj, NestedType) + + +def _validate_into_dtype(dtype: Any) -> None: + if not _is_into_dtype(dtype): + if _is_nested_type(dtype): + name = f"nw.{dtype.__name__}" + msg = ( + f"{name!r} is not valid in this context.\n\n" + f"Hint: instead of:\n\n" + f" {name}\n\n" + "use:\n\n" + f" {name}(...)" + ) + else: + msg = f"Expected Narwhals dtype, got: {qualified_type_name(dtype)!r}." + raise TypeError(msg) + + +class DTypeClass(type): + """Metaclass for DType classes. + + - Nicely print classes. + - Ensure [`__slots__`] are always defined to prevent `__dict__` creation (empty by default). + + [`__slots__`]: https://docs.python.org/3/reference/datamodel.html#object.__slots__ + """ + + def __repr__(cls) -> str: + return cls.__name__ + + # https://github.com/python/typeshed/blob/776508741d76b58f9dcb2aaf42f7d4596a48d580/stdlib/abc.pyi#L13-L19 + # https://github.com/python/typeshed/blob/776508741d76b58f9dcb2aaf42f7d4596a48d580/stdlib/_typeshed/__init__.pyi#L36-L40 + # https://github.com/astral-sh/ruff/issues/8353#issuecomment-1786238311 + # https://docs.python.org/3/reference/datamodel.html#creating-the-class-object + def __new__( + metacls: type[_typeshed.Self], + cls_name: str, + bases: tuple[type, ...], + namespace: dict[str, Any], + /, + **kwds: Any, + ) -> _typeshed.Self: + namespace.setdefault("__slots__", ()) + return super().__new__(metacls, cls_name, bases, namespace, **kwds) # type: ignore[no-any-return, misc] + + +class DType(metaclass=DTypeClass): + """Base class for all Narwhals data types.""" + + __slots__ = () # NOTE: Keep this one defined manually for the type checker + + def __repr__(self) -> str: + return self.__class__.__qualname__ + + @classmethod + def base_type(cls) -> type[Self]: + """Return this DType's fundamental/root type class. + + Examples: + >>> import narwhals as nw + >>> nw.Datetime("us").base_type() + Datetime + >>> nw.String.base_type() + String + >>> nw.List(nw.Int64).base_type() + List + """ + return cls + + @classmethod + def is_numeric(cls: type[Self]) -> bool: + """Check whether the data type is a numeric type.""" + return issubclass(cls, NumericType) + + @classmethod + def is_integer(cls: type[Self]) -> bool: + """Check whether the data type is an integer type.""" + return issubclass(cls, IntegerType) + + @classmethod + def is_signed_integer(cls: type[Self]) -> bool: + """Check whether the data type is a signed integer type.""" + return issubclass(cls, SignedIntegerType) + + @classmethod + def is_unsigned_integer(cls: type[Self]) -> bool: + """Check whether the data type is an unsigned integer type.""" + return issubclass(cls, UnsignedIntegerType) + + @classmethod + def is_float(cls: type[Self]) -> bool: + """Check whether the data type is a floating point type.""" + return issubclass(cls, FloatType) + + @classmethod + def is_decimal(cls: type[Self]) -> bool: + """Check whether the data type is a decimal type.""" + return issubclass(cls, Decimal) + + @classmethod + def is_temporal(cls: type[Self]) -> bool: + """Check whether the data type is a temporal type.""" + return issubclass(cls, TemporalType) + + @classmethod + def is_nested(cls: type[Self]) -> bool: + """Check whether the data type is a nested type.""" + return issubclass(cls, NestedType) + + @classmethod + def is_boolean(cls: type[Self]) -> bool: + """Check whether the data type is a boolean type.""" + return issubclass(cls, Boolean) + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + """Check if this DType is equivalent to another DType. + + Examples: + >>> import narwhals as nw + >>> nw.String() == nw.String() + True + >>> nw.String() == nw.String + True + >>> nw.Int16() == nw.Int32 + False + >>> nw.Boolean() == nw.Int8 + False + >>> nw.Date() == nw.Datetime + False + """ + return isinstance_or_issubclass(other, type(self)) + + def __hash__(self) -> int: + return hash(self.__class__) + + +class NumericType(DType): + """Base class for numeric data types.""" + + +class IntegerType(NumericType): + """Base class for integer data types.""" + + +class SignedIntegerType(IntegerType): + """Base class for signed integer data types.""" + + +class UnsignedIntegerType(IntegerType): + """Base class for unsigned integer data types.""" + + +class FloatType(NumericType): + """Base class for float data types.""" + + +class TemporalType(DType): + """Base class for temporal data types.""" + + +class NestedType(DType): + """Base class for nested data types.""" + + +class Decimal(NumericType): + """Decimal 128-bit type with an optional precision and non-negative scale. + + Arguments: + precision: Maximum number of digits in each number. If set to `None` (default), + the precision is set to 38 (the maximum supported by Polars). + scale: Number of digits to the right of the decimal point in each number. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s = pl.Series(["1.5"], dtype=pl.Decimal) + >>> nw.from_native(s, series_only=True).dtype + Decimal(precision=2, scale=1) + """ + + __slots__ = ("precision", "scale") + + precision: int + scale: int + + # !NOTE: Reason for `precision: int | None = None` rather than `precision: int = 38` + # is to mirror polars signature https://github.com/pola-rs/polars/blob/bb79993c3aa91d0db7d20be8f75c8075cad97067/py-polars/src/polars/datatypes/classes.py#L450-L454 + def __init__(self, precision: int | None = None, scale: int = 0) -> None: + precision = 38 if precision is None else precision + + if not ((is_int := isinstance(precision, int)) and 0 <= precision <= 38): + msg = f"precision must be a positive integer between 0 and 38, found {precision!r}" + raise ValueError(msg) if is_int else TypeError(msg) + + if not ((is_int := isinstance(scale, int)) and scale >= 0): + msg = f"scale must be a positive integer, found {scale!r}" + raise ValueError(msg) if is_int else TypeError(msg) + + if scale > precision: + msg = "scale must be less than or equal to precision" + raise InvalidOperationError(msg) + + self.precision = precision + self.scale = scale + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + return (other is Decimal) or ( + isinstance(other, self.__class__) + and self.precision == other.precision + and self.scale == other.scale + ) + + def __hash__(self) -> int: # pragma: no cover + return hash((self.__class__, self.precision, self.scale)) + + def __repr__(self) -> str: # pragma: no cover + class_name = self.__class__.__name__ + return f"{class_name}(precision={self.precision!r}, scale={self.scale!r})" + + +class Int128(SignedIntegerType): + """128-bit signed integer type. + + Examples: + >>> import polars as pl + >>> import pyarrow as pa + >>> import narwhals as nw + >>> import duckdb + >>> s_native = pl.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> df_native = pa.table({"a": [2, 1, 3, 7]}) + >>> rel = duckdb.sql(" SELECT CAST (a AS INT128) AS a FROM df_native ") + + >>> s.cast(nw.Int128).dtype + Int128 + >>> nw.from_native(rel).collect_schema()["a"] + Int128 + """ + + +class Int64(SignedIntegerType): + """64-bit signed integer type. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.Int64).dtype + Int64 + """ + + +class Int32(SignedIntegerType): + """32-bit signed integer type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[2, 1, 3, 7]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.Int32).dtype + Int32 + """ + + +class Int16(SignedIntegerType): + """16-bit signed integer type. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.Int16).dtype + Int16 + """ + + +class Int8(SignedIntegerType): + """8-bit signed integer type. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.Int8).dtype + Int8 + """ + + +class UInt128(UnsignedIntegerType): + """128-bit unsigned integer type. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> import duckdb + >>> df_native = pd.DataFrame({"a": [2, 1, 3, 7]}) + >>> rel = duckdb.sql(" SELECT CAST (a AS UINT128) AS a FROM df_native ") + >>> nw.from_native(rel).collect_schema()["a"] + UInt128 + """ + + +class UInt64(UnsignedIntegerType): + """64-bit unsigned integer type. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.UInt64).dtype + UInt64 + """ + + +class UInt32(UnsignedIntegerType): + """32-bit unsigned integer type. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.UInt32).dtype + UInt32 + """ + + +class UInt16(UnsignedIntegerType): + """16-bit unsigned integer type. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.UInt16).dtype + UInt16 + """ + + +class UInt8(UnsignedIntegerType): + """8-bit unsigned integer type. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([2, 1, 3, 7]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.UInt8).dtype + UInt8 + """ + + +class Float64(FloatType): + """64-bit floating point type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[0.001, 0.1, 0.01, 0.1]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.Float64).dtype + Float64 + """ + + +class Float32(FloatType): + """32-bit floating point type. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([0.001, 0.1, 0.01, 0.1]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cast(nw.Float32).dtype + Float32 + """ + + +class String(DType): + """UTF-8 encoded string type. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["beluga", "narwhal", "orca", "vaquita"]) + >>> nw.from_native(s_native, series_only=True).dtype + String + """ + + +class Boolean(DType): + """Boolean type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[True, False, False, True]]) + >>> nw.from_native(s_native, series_only=True).dtype + Boolean + """ + + +class Object(DType): + """Data type for wrapping arbitrary Python objects. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> class Foo: ... + >>> s_native = pd.Series([Foo(), Foo()]) + >>> nw.from_native(s_native, series_only=True).dtype + Object + """ + + +class Unknown(DType): + """Type representing DataType values that could not be determined statically. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(pd.period_range("2000-01", periods=4, freq="M")) + >>> nw.from_native(s_native, series_only=True).dtype + Unknown + """ + + +class _DatetimeMeta(DTypeClass): + @property + def time_unit(cls) -> TimeUnit: + """Unit of time. Defaults to `'us'` (microseconds).""" + return "us" + + @property + def time_zone(cls) -> str | None: + """Time zone string. Defaults to `None`.""" + return None + + +class Datetime(TemporalType, metaclass=_DatetimeMeta): + """Data type representing a calendar date and time of day. + + Arguments: + time_unit: Unit of time. Defaults to `'us'` (microseconds). + time_zone: Time zone string, as defined in zoneinfo (to see valid strings run + `import zoneinfo; zoneinfo.available_timezones()` for a full list). + + Notes: + Adapted from [Polars implementation](https://github.com/pola-rs/polars/blob/py-1.7.1/py-polars/polars/datatypes/classes.py#L398-L457) + + Examples: + >>> from datetime import datetime, timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = ( + ... pl.Series([datetime(2024, 12, 9) + timedelta(days=n) for n in range(5)]) + ... .cast(pl.Datetime("ms")) + ... .dt.replace_time_zone("Africa/Accra") + ... ) + >>> nw.from_native(s_native, series_only=True).dtype + Datetime(time_unit='ms', time_zone='Africa/Accra') + """ + + __slots__ = ("time_unit", "time_zone") + + def __init__( + self, time_unit: TimeUnit = "us", time_zone: str | timezone | None = None + ) -> None: + if time_unit not in {"s", "ms", "us", "ns"}: + msg = ( + "invalid `time_unit`" + f"\n\nExpected one of {{'ns','us','ms', 's'}}, got {time_unit!r}." + ) + raise ValueError(msg) + + if isinstance(time_zone, timezone): + time_zone = str(time_zone) + + self.time_unit: TimeUnit = time_unit + """Unit of time.""" + self.time_zone: str | None = time_zone + """Time zone string, as defined in zoneinfo. + + Notes: + To see valid strings run `import zoneinfo; zoneinfo.available_timezones()` for a full list. + """ + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + """Check if this Datetime is equivalent to another DType. + + Examples: + >>> import narwhals as nw + >>> nw.Datetime("s") == nw.Datetime("s") + True + >>> nw.Datetime() == nw.Datetime("us") + True + >>> nw.Datetime("us") == nw.Datetime("ns") + False + >>> nw.Datetime("us", "UTC") == nw.Datetime(time_unit="us", time_zone="UTC") + True + >>> nw.Datetime(time_zone="UTC") == nw.Datetime(time_zone="EST") + False + >>> nw.Datetime() == nw.Duration() + False + >>> nw.Datetime("ms") == nw.Datetime + True + """ + if type(other) is _DatetimeMeta: + return True + if isinstance(other, self.__class__): + return self.time_unit == other.time_unit and self.time_zone == other.time_zone + return False # pragma: no cover + + def __hash__(self) -> int: # pragma: no cover + return hash((self.__class__, self.time_unit, self.time_zone)) + + def __repr__(self) -> str: # pragma: no cover + class_name = self.__class__.__name__ + return f"{class_name}(time_unit={self.time_unit!r}, time_zone={self.time_zone!r})" + + +class _DurationMeta(DTypeClass): + @property + def time_unit(cls) -> TimeUnit: + """Unit of time. Defaults to `'us'` (microseconds).""" + return "us" + + +class Duration(TemporalType, metaclass=_DurationMeta): + """Data type representing a time duration. + + Arguments: + time_unit: Unit of time. Defaults to `'us'` (microseconds). + + Notes: + Adapted from [Polars implementation](https://github.com/pola-rs/polars/blob/py-1.7.1/py-polars/polars/datatypes/classes.py#L460-L502) + + Examples: + >>> from datetime import timedelta + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [[timedelta(seconds=d) for d in range(1, 4)]], type=pa.duration("ms") + ... ) + >>> nw.from_native(s_native, series_only=True).dtype + Duration(time_unit='ms') + """ + + __slots__ = ("time_unit",) + + def __init__(self, time_unit: TimeUnit = "us") -> None: + if time_unit not in {"s", "ms", "us", "ns"}: + msg = ( + "invalid `time_unit`" + f"\n\nExpected one of {{'ns','us','ms', 's'}}, got {time_unit!r}." + ) + raise ValueError(msg) + + self.time_unit: TimeUnit = time_unit + """Unit of time.""" + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + """Check if this Duration is equivalent to another DType. + + Examples: + >>> import narwhals as nw + >>> nw.Duration("us") == nw.Duration("us") + True + >>> nw.Duration() == nw.Duration("us") + True + >>> nw.Duration("us") == nw.Duration("ns") + False + >>> nw.Duration() == nw.Datetime() + False + >>> nw.Duration("ms") == nw.Duration + True + """ + if type(other) is _DurationMeta: + return True + if isinstance(other, self.__class__): + return self.time_unit == other.time_unit + return False # pragma: no cover + + def __hash__(self) -> int: # pragma: no cover + return hash((self.__class__, self.time_unit)) + + def __repr__(self) -> str: # pragma: no cover + class_name = self.__class__.__name__ + return f"{class_name}(time_unit={self.time_unit!r})" + + +class Categorical(DType): + """A categorical encoding of a set of strings. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series(["beluga", "narwhal", "orca"]) + >>> nw.from_native(s_native, series_only=True).cast(nw.Categorical).dtype + Categorical + """ + + +class Enum(DType): + """A fixed categorical encoding of a unique set of strings. + + Polars has an Enum data type. In pandas, ordered categories get mapped + to Enum. PyArrow has no Enum equivalent. + + Examples: + >>> import narwhals as nw + >>> nw.Enum(["beluga", "narwhal", "orca"]) + Enum(categories=['beluga', 'narwhal', 'orca']) + """ + + __slots__ = ("_cached_categories", "_delayed_categories") + + def __init__(self, categories: Iterable[str] | type[enum.Enum]) -> None: + self._delayed_categories: _DeferredIterable[str] | None = None + self._cached_categories: tuple[str, ...] | None = None + + if isinstance(categories, _DeferredIterable): + self._delayed_categories = categories + elif isinstance(categories, type) and issubclass(categories, enum.Enum): + self._cached_categories = tuple(member.value for member in categories) + else: + self._cached_categories = tuple(categories) + + @property + def categories(self) -> tuple[str, ...]: + """The categories in the dataset.""" + if (cached := self._cached_categories) is not None: + return cached + if (delayed := self._delayed_categories) is not None: + self._cached_categories = delayed.to_tuple() + return self._cached_categories + msg = f"Internal structure of {type(self).__name__!r} is invalid." # pragma: no cover + raise TypeError(msg) # pragma: no cover + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + """Check if this Enum is equivalent to another DType. + + Examples: + >>> import narwhals as nw + >>> nw.Enum(["a", "b", "c"]) == nw.Enum(["a", "b", "c"]) + True + >>> import polars as pl + >>> categories = pl.Series(["a", "b", "c"]) + >>> nw.Enum(["a", "b", "c"]) == nw.Enum(categories) + True + >>> nw.Enum(["a", "b", "c"]) == nw.Enum(["b", "a", "c"]) + False + >>> nw.Enum(["a", "b", "c"]) == nw.Enum(["a"]) + False + >>> nw.Enum(["a", "b", "c"]) == nw.Categorical + False + >>> nw.Enum(["a", "b", "c"]) == nw.Enum + True + """ + if type(other) is DTypeClass: + return other is Enum + return isinstance(other, type(self)) and self.categories == other.categories + + def __hash__(self) -> int: + return hash((self.__class__, tuple(self.categories))) + + def __repr__(self) -> str: + return f"{type(self).__name__}(categories={list(self.categories)!r})" + + +class Field: + """Definition of a single field within a `Struct` DType. + + Arguments: + name: The name of the field within its parent `Struct`. + dtype: The `DType` of the field's values. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> data = [{"a": 1, "b": ["narwhal", "beluga"]}, {"a": 2, "b": ["orca"]}] + >>> ser_pa = pa.chunked_array([data]) + >>> nw.from_native(ser_pa, series_only=True).dtype.fields + [Field('a', Int64), Field('b', List(String))] + """ + + __slots__ = ("dtype", "name") + name: str + """The name of the field within its parent `Struct`.""" + dtype: IntoDType + """The `DType` of the field's values.""" + + def __init__(self, name: str, dtype: IntoDType) -> None: + self.name = name + self.dtype = dtype + + def __eq__(self, other: Field) -> bool: # type: ignore[override] + """Check if this Field is equivalent to another Field. + + Two fields are equivalent if they have the same name and the same dtype. + + Examples: + >>> import narwhals as nw + >>> nw.Field("a", nw.String) == nw.Field("a", nw.String()) + True + >>> nw.Field("a", nw.String) == nw.Field("a", nw.String) + True + >>> nw.Field("a", nw.String) == nw.Field("a", nw.Datetime) + False + >>> nw.Field("a", nw.String) == nw.Field("b", nw.String) + False + >>> nw.Field("a", nw.String) == nw.String + False + """ + return ( + isinstance(other, Field) + and (self.name == other.name) + and (self.dtype == other.dtype) + ) + + def __hash__(self) -> int: + return hash((self.name, self.dtype)) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return f"{class_name}({self.name!r}, {self.dtype})" + + +class Struct(NestedType): + """Struct composite type. + + Arguments: + fields: The fields that make up the struct. Can be either a sequence of Field + objects or a mapping of column names to data types. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [[{"a": 1, "b": ["narwhal", "beluga"]}, {"a": 2, "b": ["orca"]}]] + ... ) + >>> nw.from_native(s_native, series_only=True).dtype + Struct({'a': Int64, 'b': List(String)}) + """ + + __slots__ = ("fields",) + fields: list[Field] + """The fields that make up the struct.""" + + def __init__(self, fields: Sequence[Field] | Mapping[str, IntoDType]) -> None: + if isinstance(fields, Mapping): + self.fields = list(starmap(Field, fields.items())) + else: + self.fields = list(fields) + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + """Check if this Struct is equivalent to another DType. + + Examples: + >>> import narwhals as nw + >>> nw.Struct({"a": nw.Int64}) == nw.Struct({"a": nw.Int64}) + True + >>> nw.Struct({"a": nw.Int64}) == nw.Struct({"a": nw.Boolean}) + False + >>> nw.Struct({"a": nw.Int64}) == nw.Struct({"b": nw.Int64}) + False + >>> nw.Struct({"a": nw.Int64}) == nw.Struct([nw.Field("a", nw.Int64)]) + True + + If a parent type is not specific about its inner type, we infer it as equal + + >>> nw.Struct({"a": nw.Int64}) == nw.Struct + True + """ + if type(other) is DTypeClass and issubclass(other, self.__class__): + return True + if isinstance(other, self.__class__): + return self.fields == other.fields + return False + + def __hash__(self) -> int: + return hash((self.__class__, tuple(self.fields))) + + def __iter__(self) -> Iterator[tuple[str, IntoDType]]: # pragma: no cover + for fld in self.fields: + yield fld.name, fld.dtype + + def __reversed__(self) -> Iterator[tuple[str, IntoDType]]: + for fld in reversed(self.fields): + yield fld.name, fld.dtype + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return f"{class_name}({dict(self)})" + + def to_schema(self) -> OrderedDict[str, IntoDType]: + """Return Struct dtype as a schema dict.""" + return OrderedDict(self) + + +class List(NestedType): + """Variable length list type. + + Examples: + >>> import pandas as pd + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [["narwhal", "orca"], ["beluga", "vaquita"]], + ... dtype=pd.ArrowDtype(pa.large_list(pa.large_string())), + ... ) + >>> nw.from_native(s_native, series_only=True).dtype + List(String) + """ + + __slots__ = ("inner",) + inner: IntoDType + """The DType of the values within each list.""" + + def __init__(self, inner: IntoDType) -> None: + self.inner = inner + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + """Check if this List is equivalent to another DType. + + Examples: + >>> import narwhals as nw + >>> nw.List(nw.Int64) == nw.List(nw.Int64) + True + >>> nw.List(nw.Int64) == nw.List(nw.Float32) + False + + If a parent type is not specific about its inner type, we infer it as equal + + >>> nw.List(nw.Int64) == nw.List + True + """ + if type(other) is DTypeClass and issubclass(other, self.__class__): + return True + if isinstance(other, self.__class__): + return self.inner == other.inner + return False + + def __hash__(self) -> int: + return hash((self.__class__, self.inner)) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return f"{class_name}({self.inner!r})" + + +class Array(NestedType): + """Fixed length list type. + + Arguments: + inner: The datatype of the values within each array. + shape: The shape of the arrays. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[1, 2], [3, 4], [5, 6]], dtype=pl.Array(pl.Int32, 2)) + >>> nw.from_native(s_native, series_only=True).dtype + Array(Int32, shape=(2,)) + """ + + __slots__ = ("inner", "shape", "size") + inner: IntoDType + """The DType of the values within each array.""" + size: int + """The size of the Array.""" + shape: tuple[int, ...] + """The shape of the arrays.""" + + def __init__(self, inner: IntoDType, shape: int | tuple[int, ...]) -> None: + inner_shape: tuple[int, ...] = inner.shape if isinstance(inner, Array) else () + if isinstance(shape, int): + self.inner = inner + self.size = shape + self.shape = (shape, *inner_shape) + + elif isinstance(shape, tuple) and len(shape) != 0 and isinstance(shape[0], int): + if len(shape) > 1: + inner = Array(inner, shape[1:]) + + self.inner = inner + self.size = shape[0] + self.shape = shape + inner_shape + + else: + msg = f"invalid input for shape: {shape!r}" + raise TypeError(msg) + + def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override] + """Check if this Array is equivalent to another DType. + + Examples: + >>> import narwhals as nw + >>> nw.Array(nw.Int64, 2) == nw.Array(nw.Int64, 2) + True + >>> nw.Array(nw.Int64, 2) == nw.Array(nw.String, 2) + False + >>> nw.Array(nw.Int64, 2) == nw.Array(nw.Int64, 4) + False + + If a parent type is not specific about its inner type, we infer it as equal + + >>> nw.Array(nw.Int64, 2) == nw.Array + True + """ + if type(other) is DTypeClass and issubclass(other, self.__class__): + return True + if isinstance(other, self.__class__): + if self.shape != other.shape: + return False + return self.inner == other.inner + return False + + def __hash__(self) -> int: + return hash((self.__class__, self.inner, self.shape)) + + def __repr__(self) -> str: + # Get leaf type + dtype_ = self + for _ in self.shape: + dtype_ = dtype_.inner # type: ignore[assignment] + + class_name = self.__class__.__name__ + return f"{class_name}({dtype_!r}, shape={self.shape})" + + +class Date(TemporalType): + """Data type representing a calendar date. + + Examples: + >>> from datetime import date, timedelta + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [[date(2024, 12, 1) + timedelta(days=d) for d in range(4)]] + ... ) + >>> nw.from_native(s_native, series_only=True).dtype + Date + """ + + +class Time(TemporalType): + """Data type representing the time of day. + + Examples: + >>> import polars as pl + >>> import pyarrow as pa + >>> import narwhals as nw + >>> import duckdb + >>> from datetime import time + >>> data = [time(9, 0), time(9, 1, 10), time(9, 2)] + >>> ser_pl = pl.Series(data) + >>> ser_pa = pa.chunked_array([pa.array(data, type=pa.time64("ns"))]) + >>> rel = duckdb.sql( + ... " SELECT * FROM (VALUES (TIME '12:00:00'), (TIME '14:30:15')) df(t)" + ... ) + + >>> nw.from_native(ser_pl, series_only=True).dtype + Time + >>> nw.from_native(ser_pa, series_only=True).dtype + Time + >>> nw.from_native(rel).collect_schema()["t"] + Time + """ + + +class Binary(DType): + """Binary type. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> import pyarrow as pa + >>> import duckdb + >>> data = [b"test1", b"test2"] + >>> ser_pl = pl.Series(data, dtype=pl.Binary) + >>> ser_pa = pa.chunked_array([pa.array(data, type=pa.binary())]) + >>> rel = duckdb.sql( + ... "SELECT * FROM (VALUES (BLOB 'test1'), (BLOB 'test2')) AS df(t)" + ... ) + + >>> nw.from_native(ser_pl, series_only=True).dtype + Binary + >>> nw.from_native(ser_pa, series_only=True).dtype + Binary + >>> nw.from_native(rel).collect_schema()["t"] + Binary + """ diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/exceptions.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..447ff87a1db4c69f14a6e2f1853ddd84691680fe --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/exceptions.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Collection, Iterable + + +class NarwhalsError(ValueError): + """Base class for all Narwhals exceptions.""" + + +class FormattedKeyError(KeyError): + """KeyError with formatted error message. + + Python's `KeyError` has special casing around formatting + (see https://bugs.python.org/issue2651). Use this class when the error + message has newlines and other special format characters. + Needed by https://github.com/tensorflow/tensorflow/issues/36857. + """ + + message: str + + def __init__(self, message: str) -> None: + self.message = message + + def __str__(self) -> str: + return self.message + + +class ColumnNotFoundError(FormattedKeyError, NarwhalsError): + """Exception raised when column name isn't present.""" + + message: str + + def __init__(self, message: str) -> None: + self.message = message + super().__init__(self.message) + + @classmethod + def from_missing_and_available_column_names( + cls, missing_columns: Iterable[str], available_columns: Collection[str], / + ) -> ColumnNotFoundError: + message = ( + f"The following columns were not found: {sorted(missing_columns)}" + f"\n\nHint: Did you mean one of these columns: {list(available_columns)}?" + ) + return ColumnNotFoundError(message) + + @classmethod + def from_available_column_names( + cls, available_columns: Collection[str] + ) -> ColumnNotFoundError: + message = ( + "The selected columns were not found." + f"\n\nHint: Did you mean one of these columns: {list(available_columns)}?" + ) + return ColumnNotFoundError(message) + + +class ComputeError(NarwhalsError): + """Exception raised when the underlying computation could not be evaluated.""" + + +class ShapeError(NarwhalsError): + """Exception raised when trying to perform operations on data structures with incompatible shapes.""" + + +class MultiOutputExpressionError(NarwhalsError): + """Exception raised when using multi-output expression in unsupported context.""" + + +class DuplicateError(NarwhalsError): + """Exception when duplicate column names are encountered.""" + + +class InvalidOperationError(NarwhalsError): + """Exception raised during invalid operations.""" + + +class InvalidIntoExprError(TypeError, NarwhalsError): + """Exception raised when object can't be converted to expression.""" + + message: str + + def __init__(self, message: str) -> None: + self.message = message + super().__init__(self.message) + + @classmethod + def from_invalid_type(cls: type, invalid_type: type) -> InvalidIntoExprError: + message = ( + f"Expected an object which can be converted into an expression, got {invalid_type}\n\n" + "Hint:\n" + "- if you were trying to select a column which does not have a string\n" + " column name, then you should explicitly use `nw.col`.\n" + " For example, `df.select(nw.col(0))` if you have a column named `0`.\n" + "- if you were trying to create a new literal column, then you \n" + " should explicitly use `nw.lit`.\n" + " For example, `df.select(nw.lit(0))` if you want to create a new\n" + " column with literal value `0`." + ) + return InvalidIntoExprError(message) + + +class UnsupportedDTypeError(NarwhalsError): + """Exception raised when trying to convert to a DType which is not supported by the given backend.""" + + +class NarwhalsUnstableWarning(UserWarning): + """Warning issued when a method or function is considered unstable in the stable api.""" + + +class PerformanceWarning(Warning): ... diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/expr.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6f616f713edbcbf5fca9232e7c5162009ab152 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr.py @@ -0,0 +1,2527 @@ +from __future__ import annotations + +import math +from collections.abc import Iterable, Mapping, Sequence +from typing import TYPE_CHECKING, Any, Callable + +from narwhals._expression_parsing import ExprKind, ExprNode, evaluate_nodes +from narwhals._utils import ( + _validate_rolling_arguments, + ensure_type, + flatten, + no_default, + unstable, +) +from narwhals.dtypes import _validate_dtype +from narwhals.exceptions import ComputeError, InvalidOperationError +from narwhals.expr_cat import ExprCatNamespace +from narwhals.expr_dt import ExprDateTimeNamespace +from narwhals.expr_list import ExprListNamespace +from narwhals.expr_name import ExprNameNamespace +from narwhals.expr_str import ExprStringNamespace +from narwhals.expr_struct import ExprStructNamespace +from narwhals.translate import to_native + +if TYPE_CHECKING: + from typing import NoReturn, TypeVar + + from typing_extensions import Concatenate, ParamSpec, Self + + from narwhals._compliant import CompliantExpr, CompliantNamespace + from narwhals._typing import NoDefault + from narwhals.dtypes import DType + from narwhals.series import Series + from narwhals.typing import ( + ClosedInterval, + FillNullStrategy, + IntoDType, + IntoExpr, + ModeKeepStrategy, + NonNestedLiteral, + NumericLiteral, + RankMethod, + RollingInterpolationMethod, + TemporalLiteral, + ) + + PS = ParamSpec("PS") + R = TypeVar("R") + + +class Expr: + def __init__(self, *nodes: ExprNode) -> None: + self._nodes = nodes + + def _to_compliant_expr( + self, ns: CompliantNamespace[Any, Any] + ) -> CompliantExpr[Any, Any]: + return evaluate_nodes(self._nodes, ns) + + def _append_node(self, node: ExprNode) -> Self: + return self.__class__(*self._nodes, node) + + def _with_over_node(self, node: ExprNode) -> Self: + # insert `over` before any elementwise operations. + # check "how it works" page in docs for why we do this. + new_nodes = list(self._nodes) + kwargs_no_order_by = { + key: value if key != "order_by" else [] + for (key, value) in node.kwargs.items() + } + node_without_order_by = node._with_kwargs(**kwargs_no_order_by) + n = len(new_nodes) + i = n + while i > 0 and (_node := new_nodes[i - 1]).kind is ExprKind.ELEMENTWISE: + i -= 1 + _node._push_down_over_node_in_place(node, node_without_order_by) + if i == n: + # node could not be pushed down, just append as-is + new_nodes.append(node) + return self.__class__(*new_nodes) + if node.kwargs["order_by"] and any(node.is_orderable() for node in new_nodes[:i]): + new_nodes.insert(i, node) + elif node.kwargs["partition_by"] and any( + not node.is_elementwise() for node in new_nodes[:i] + ): + new_nodes.insert(i, node_without_order_by) + elif all(node.is_elementwise() for node in new_nodes): + msg = "Cannot apply `over` to elementwise expression." + raise InvalidOperationError(msg) + return self.__class__(*new_nodes) + + def __repr__(self) -> str: + """Pretty-print the expression by combining all nodes in the metadata.""" + return ".".join(repr(node) for node in self._nodes) + + def __bool__(self) -> NoReturn: + msg = ( + f"the truth value of {type(self)} is ambiguous" + "\n\n" + "You probably got here by using a Python standard library function instead " + "of the native expressions API.\n" + "Here are some things you might want to try:\n" + "- instead of `nw.col('a') and nw.col('b')`, use `nw.col('a') & nw.col('b')`\n" + "- instead of `nw.col('a') in [y, z]`, use `nw.col('a').is_in([y, z])`\n" + "- instead of `max(nw.col('a'), nw.col('b'))`, use `nw.max_horizontal(nw.col('a'), nw.col('b'))`\n" + ) + raise TypeError(msg) + + def _taxicab_norm(self) -> Self: + # This is just used to test out the stable api feature in a realistic-ish way. + # It's not intended to be used. + return self.abs().sum() + + # --- convert --- + def alias(self, name: str) -> Self: + """Rename the expression. + + Arguments: + name: The new name. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [4, 5]}) + >>> df = nw.from_native(df_native) + >>> df.select((nw.col("b") + 10).alias("c")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | c | + | 0 14 | + | 1 15 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "alias", name=name)) + + def pipe( + self, + function: Callable[Concatenate[Self, PS], R], + *args: PS.args, + **kwargs: PS.kwargs, + ) -> R: + """Pipe function call. + + Arguments: + function: Function to apply. + args: Positional arguments to pass to function. + kwargs: Keyword arguments to pass to function. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 4]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_piped=nw.col("a").pipe(lambda x: x + 1)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a a_piped | + | 0 1 2 | + | 1 2 3 | + | 2 3 4 | + | 3 4 5 | + └──────────────────┘ + """ + return function(self, *args, **kwargs) + + def cast(self, dtype: IntoDType) -> Self: + """Redefine an object's data type. + + Arguments: + dtype: Data type that the object will be cast into. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, 2, 3], "bar": [6.0, 7.0, 8.0]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("foo").cast(nw.Float32), nw.col("bar").cast(nw.UInt8)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | foo bar | + | 0 1.0 6 | + | 1 2.0 7 | + | 2 3.0 8 | + └──────────────────┘ + """ + _validate_dtype(dtype) + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "cast", dtype=dtype)) + + # --- binary --- + def _with_binary(self, attr: str, other: Self | Any) -> Self: + node = ExprNode(ExprKind.ELEMENTWISE, attr, exprs=(other,), str_as_lit=True) + return self._append_node(node) + + def __eq__(self, other: Self | Any) -> Self: # type: ignore[override] + return self._with_binary("__eq__", other) + + def __ne__(self, other: Self | Any) -> Self: # type: ignore[override] + return self._with_binary("__ne__", other) + + def __and__(self, other: Any) -> Self: + return self._with_binary("__and__", other) + + def __rand__(self, other: Any) -> Self: + return (self & other).alias("literal") # type: ignore[no-any-return] + + def __or__(self, other: Any) -> Self: + return self._with_binary("__or__", other) + + def __ror__(self, other: Any) -> Self: + return (self | other).alias("literal") # type: ignore[no-any-return] + + def __add__(self, other: Any) -> Self: + return self._with_binary("__add__", other) + + def __radd__(self, other: Any) -> Self: + return (self + other).alias("literal") # type: ignore[no-any-return] + + def __sub__(self, other: Any) -> Self: + return self._with_binary("__sub__", other) + + def __rsub__(self, other: Any) -> Self: + return self._with_binary("__rsub__", other) + + def __truediv__(self, other: Any) -> Self: + return self._with_binary("__truediv__", other) + + def __rtruediv__(self, other: Any) -> Self: + return self._with_binary("__rtruediv__", other) + + def __mul__(self, other: Any) -> Self: + return self._with_binary("__mul__", other) + + def __rmul__(self, other: Any) -> Self: + return (self * other).alias("literal") # type: ignore[no-any-return] + + def __le__(self, other: Any) -> Self: + return self._with_binary("__le__", other) + + def __lt__(self, other: Any) -> Self: + return self._with_binary("__lt__", other) + + def __gt__(self, other: Any) -> Self: + return self._with_binary("__gt__", other) + + def __ge__(self, other: Any) -> Self: + return self._with_binary("__ge__", other) + + def __pow__(self, other: Any) -> Self: + return self._with_binary("__pow__", other) + + def __rpow__(self, other: Any) -> Self: + return self._with_binary("__rpow__", other) + + def __floordiv__(self, other: Any) -> Self: + return self._with_binary("__floordiv__", other) + + def __rfloordiv__(self, other: Any) -> Self: + return self._with_binary("__rfloordiv__", other) + + def __mod__(self, other: Any) -> Self: + return self._with_binary("__mod__", other) + + def __rmod__(self, other: Any) -> Self: + return self._with_binary("__rmod__", other) + + # --- unary --- + def __invert__(self) -> Self: + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "__invert__")) + + def any(self) -> Self: + """Return whether any of the values in the column are `True`. + + If there are no non-null elements, the result is `False`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [True, False], "b": [True, True]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").any()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 True True | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "any")) + + def all(self) -> Self: + """Return whether all values in the column are `True`. + + If there are no non-null elements, the result is `True`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [True, False], "b": [True, True]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").all()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 False True | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "all")) + + def ewm_mean( + self, + *, + com: float | None = None, + span: float | None = None, + half_life: float | None = None, + alpha: float | None = None, + adjust: bool = True, + min_samples: int = 1, + ignore_nulls: bool = False, + ) -> Self: + r"""Compute exponentially-weighted moving average. + + Arguments: + com: Specify decay in terms of center of mass, $\gamma$, with
$\alpha = \frac{1}{1+\gamma}\forall\gamma\geq0$ + span: Specify decay in terms of span, $\theta$, with
$\alpha = \frac{2}{\theta + 1} \forall \theta \geq 1$ + half_life: Specify decay in terms of half-life, $\tau$, with
$\alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \tau } \right\} \forall \tau > 0$ + alpha: Specify smoothing factor alpha directly, $0 < \alpha \leq 1$. + adjust: Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings + + - When `adjust=True` (the default) the EW function is calculated + using weights $w_i = (1 - \alpha)^i$ + - When `adjust=False` the EW function is calculated recursively by + $$ + y_0=x_0 + $$ + $$ + y_t = (1 - \alpha)y_{t - 1} + \alpha x_t + $$ + min_samples: Minimum number of observations in window required to have a value, (otherwise result is null). + ignore_nulls: Ignore missing values when calculating weights. + + - When `ignore_nulls=False` (default), weights are based on absolute + positions. + For example, the weights of $x_0$ and $x_2$ used in + calculating the final weighted average of $[x_0, None, x_2]$ are + $(1-\alpha)^2$ and $1$ if `adjust=True`, and + $(1-\alpha)^2$ and $\alpha$ if `adjust=False`. + - When `ignore_nulls=True`, weights are based + on relative positions. For example, the weights of + $x_0$ and $x_2$ used in calculating the final weighted + average of $[x_0, None, x_2]$ are + $1-\alpha$ and $1$ if `adjust=True`, + and $1-\alpha$ and $\alpha$ if `adjust=False`. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> from narwhals.typing import IntoFrameT + >>> + >>> data = {"a": [1, 2, 3]} + >>> df_pd = pd.DataFrame(data) + >>> df_pl = pl.DataFrame(data) + + We define a library agnostic function: + + >>> def agnostic_ewm_mean(df_native: IntoFrameT) -> IntoFrameT: + ... df = nw.from_native(df_native) + ... return df.select( + ... nw.col("a").ewm_mean(com=1, ignore_nulls=False) + ... ).to_native() + + We can then pass either pandas or Polars to `agnostic_ewm_mean`: + + >>> agnostic_ewm_mean(df_pd) + a + 0 1.000000 + 1 1.666667 + 2 2.428571 + + >>> agnostic_ewm_mean(df_pl) # doctest: +NORMALIZE_WHITESPACE + shape: (3, 1) + ┌──────────┐ + │ a │ + │ --- │ + │ f64 │ + ╞══════════╡ + │ 1.0 │ + │ 1.666667 │ + │ 2.428571 │ + └──────────┘ + """ + return self._append_node( + ExprNode( + ExprKind.ORDERABLE_WINDOW, + "ewm_mean", + com=com, + span=span, + half_life=half_life, + alpha=alpha, + adjust=adjust, + min_samples=min_samples, + ignore_nulls=ignore_nulls, + ) + ) + + def mean(self) -> Self: + """Get mean value. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [-1, 0, 1], "b": [2, 4, 6]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").mean()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 0.0 4.0 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "mean")) + + def median(self) -> Self: + """Get median value. + + Notes: + Results might slightly differ across backends due to differences in the underlying algorithms used to compute the median. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 8, 3], "b": [4, 5, 2]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").median()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 3.0 4.0 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "median")) + + def std(self, *, ddof: int = 1) -> Self: + """Get standard deviation. + + Arguments: + ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, + where N represents the number of elements. By default ddof is 1. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [20, 25, 60], "b": [1.5, 1, -1.4]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").std(ddof=0)) + ┌─────────────────────┐ + | Narwhals DataFrame | + |---------------------| + | a b| + |0 17.79513 1.265789| + └─────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "std", ddof=ddof)) + + def var(self, *, ddof: int = 1) -> Self: + """Get variance. + + Arguments: + ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, + where N represents the number of elements. By default ddof is 1. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [20, 25, 60], "b": [1.5, 1, -1.4]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").var(ddof=0)) + ┌───────────────────────┐ + | Narwhals DataFrame | + |-----------------------| + | a b| + |0 316.666667 1.602222| + └───────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "var", ddof=ddof)) + + def map_batches( + self, + function: Callable[[Any], CompliantExpr[Any, Any]], + return_dtype: DType | None = None, + *, + returns_scalar: bool = False, + ) -> Self: + """Apply a custom python function to a whole Series or sequence of Series. + + The output of this custom function is presumed to be either a Series, + or a NumPy array (in which case it will be automatically converted into + a Series). + + Arguments: + function: Function to apply to Series. + return_dtype: Dtype of the output Series. + If not set, the dtype will be inferred based on the first non-null value + that is returned by the function. + returns_scalar: If the function returns a scalar, by default it will be wrapped + in a list in the output, since the assumption is that the function always + returns something Series-like. + If you want to keep the result as a scalar, set this argument to True. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a", "b") + ... .map_batches(lambda s: s.to_numpy() + 1, return_dtype=nw.Float64) + ... .name.suffix("_mapped") + ... ) + ┌───────────────────────────┐ + | Narwhals DataFrame | + |---------------------------| + | a b a_mapped b_mapped| + |0 1 4 2.0 5.0| + |1 2 5 3.0 6.0| + |2 3 6 4.0 7.0| + └───────────────────────────┘ + """ + kind = ( + ExprKind.ORDERABLE_AGGREGATION + if returns_scalar + else ExprKind.ORDERABLE_FILTRATION + ) + return self._append_node( + ExprNode( + kind, + "map_batches", + function=function, + return_dtype=return_dtype, + returns_scalar=returns_scalar, + ) + ) + + def skew(self) -> Self: + """Calculate the sample skewness of a column. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [1, 1, 2, 10, 100]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").skew()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 0.0 1.472427 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "skew")) + + def kurtosis(self) -> Self: + """Compute the kurtosis (Fisher's definition) without bias correction. + + Kurtosis is the fourth central moment divided by the square of the variance. + The Fisher's definition is used where 3.0 is subtracted from the result to give 0.0 for a normal distribution. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [1, 1, 2, 10, 100]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").kurtosis()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 -1.3 0.210657 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "kurtosis")) + + def sum(self) -> Self: + """Return the sum value. + + If there are no non-null elements, the result is zero. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql("SELECT * FROM VALUES (5, 50), (10, 100) df(a, b)") + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").sum()) + ┌───────────────────┐ + |Narwhals LazyFrame | + |-------------------| + |┌────────┬────────┐| + |│ a │ b │| + |│ int128 │ int128 │| + |├────────┼────────┤| + |│ 15 │ 150 │| + |└────────┴────────┘| + └───────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "sum")) + + def min(self) -> Self: + """Returns the minimum value(s) from a column(s). + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [4, 3]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.min("a", "b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 3 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "min")) + + def max(self) -> Self: + """Returns the maximum value(s) from a column(s). + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [10, 20], "b": [50, 100]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.max("a", "b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 20 100 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "max")) + + def count(self) -> Self: + """Returns the number of non-null elements in the column. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3], "b": [None, 4, 4]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.all().count()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 3 2 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "count")) + + def n_unique(self) -> Self: + """Returns count of unique values. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 4, 5], "b": [1, 1, 3, 3, 5]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").n_unique()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 5 3 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "n_unique")) + + def unique(self) -> Self: + """Return unique values of this expression. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 1, 3, 5, 5], "b": [2, 4, 4, 6, 6]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").unique().sum()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 9 12 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.FILTRATION, "unique")) + + def abs(self) -> Self: + """Return absolute value of each element. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, -2], "b": [-3, 4]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a", "b").abs().name.suffix("_abs")) + ┌─────────────────────┐ + | Narwhals DataFrame | + |---------------------| + | a b a_abs b_abs| + |0 1 -3 1 3| + |1 -2 4 2 4| + └─────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "abs")) + + def cum_sum(self, *, reverse: bool = False) -> Self: + """Return cumulative sum. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 1, 3, 5, 5], "b": [2, 4, 4, 6, 6]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_cum_sum=nw.col("a").cum_sum()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b a_cum_sum| + |0 1 2 1| + |1 1 4 2| + |2 3 4 5| + |3 5 6 10| + |4 5 6 15| + └──────────────────┘ + """ + return self._append_node( + ExprNode(ExprKind.ORDERABLE_WINDOW, "cum_sum", reverse=reverse) + ) + + def diff(self) -> Self: + """Returns the difference between each element and the previous one. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Notes: + pandas may change the dtype here, for example when introducing missing + values in an integer column. To ensure, that the dtype doesn't change, + you may want to use `fill_null` and `cast`. For example, to calculate + the diff and fill missing values with `0` in a Int64 column, you could + do: + + nw.col("a").diff().fill_null(0).cast(nw.Int64) + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 1, 3, 5, 5]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_diff=nw.col("a").diff()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (5, 2) | + | ┌─────┬────────┐ | + | │ a ┆ a_diff │ | + | │ --- ┆ --- │ | + | │ i64 ┆ i64 │ | + | ╞═════╪════════╡ | + | │ 1 ┆ null │ | + | │ 1 ┆ 0 │ | + | │ 3 ┆ 2 │ | + | │ 5 ┆ 2 │ | + | │ 5 ┆ 0 │ | + | └─────┴────────┘ | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ORDERABLE_WINDOW, "diff")) + + def shift(self, n: int) -> Self: + """Shift values by `n` positions. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + n: Number of positions to shift values by. + + Notes: + pandas may change the dtype here, for example when introducing missing + values in an integer column. To ensure, that the dtype doesn't change, + you may want to use `fill_null` and `cast`. For example, to shift + and fill missing values with `0` in a Int64 column, you could + do: + + nw.col("a").shift(1).fill_null(0).cast(nw.Int64) + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 1, 3, 5, 5]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_shift=nw.col("a").shift(n=1)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |shape: (5, 2) | + |┌─────┬─────────┐ | + |│ a ┆ a_shift │ | + |│ --- ┆ --- │ | + |│ i64 ┆ i64 │ | + |╞═════╪═════════╡ | + |│ 1 ┆ null │ | + |│ 1 ┆ 1 │ | + |│ 3 ┆ 1 │ | + |│ 5 ┆ 3 │ | + |│ 5 ┆ 5 │ | + |└─────┴─────────┘ | + └──────────────────┘ + """ + ensure_type(n, int, param_name="n") + return self._append_node(ExprNode(ExprKind.ORDERABLE_WINDOW, "shift", n=n)) + + def replace_strict( + self, + old: Sequence[Any] | Mapping[Any, Any], + new: Sequence[Any] | None = None, + *, + default: Any | NoDefault = no_default, + return_dtype: IntoDType | None = None, + ) -> Self: + """Replace all values by different values. + + Arguments: + old: Sequence of values to replace. It also accepts a mapping of values to + their replacement as syntactic sugar for + `replace_strict(old=list(mapping.keys()), new=list(mapping.values()))`. + new: Sequence of values to replace by. Length must match the length of `old`. + default: Set values that were not replaced to this value. If no default is + specified, (default), an error is raised if any values were not replaced. + Accepts expression input. Non-expression inputs are parsed as literals. + return_dtype: The data type of the resulting expression. If set to `None` + (default), the data type is determined automatically based on the other + inputs. + + Raises: + InvalidOperationError: If any non-null values in the original column were not + replaced, and no default was specified. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [3, 0, 1, 2]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... b=nw.col("a").replace_strict( + ... [0, 1, 2, 3], + ... ["zero", "one", "two", "three"], + ... return_dtype=nw.String, + ... ) + ... ) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 3 three | + | 1 0 zero | + | 2 1 one | + | 3 2 two | + └──────────────────┘ + + Replace values and set a default for values not in the mapping: + + >>> data = {"a": [1, 2, 3, 4], "b": ["beluga", "narwhal", "orca", "vaquita"]} + >>> df = nw.from_native(pd.DataFrame(data)) + >>> df.with_columns( + ... a_replaced=nw.col("a").replace_strict( + ... {1: "one", 2: "two"}, + ... default=nw.concat_str(nw.lit("default_"), nw.col("b")), + ... return_dtype=nw.String, + ... ) + ... ) + ┌──────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------| + | a b a_replaced| + |0 1 beluga one| + |1 2 narwhal two| + |2 3 orca default_orca| + |3 4 vaquita default_vaquita| + └──────────────────────────────┘ + """ + if new is None: + if not isinstance(old, Mapping): + msg = "`new` argument is required if `old` argument is not a Mapping type" + raise TypeError(msg) + + new = list(old.values()) + old = list(old.keys()) + + if default is no_default: + node = ExprNode( + ExprKind.ELEMENTWISE, + "replace_strict", + default=default, + old=old, + new=new, + return_dtype=return_dtype, + ) + else: + node = ExprNode( + ExprKind.ELEMENTWISE, + "replace_strict", + exprs=(default,), + old=old, + new=new, + return_dtype=return_dtype, + str_as_lit=True, + ) + return self._append_node(node) + + # --- transform --- + def is_between( + self, + lower_bound: Any | IntoExpr, + upper_bound: Any | IntoExpr, + closed: ClosedInterval = "both", + ) -> Self: + """Check if this expression is between the given lower and upper bounds. + + Arguments: + lower_bound: Lower bound value. String literals are interpreted as column names. + upper_bound: Upper bound value. String literals are interpreted as column names. + closed: Define which sides of the interval are closed (inclusive). Options are {"left", "right", "none", "both"}. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 4, 5]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(b=nw.col("a").is_between(2, 4, "right")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 False | + | 1 2 False | + | 2 3 True | + | 3 4 True | + | 4 5 False | + └──────────────────┘ + """ + node = ExprNode( + ExprKind.ELEMENTWISE, + "is_between", + exprs=(lower_bound, upper_bound), + closed=closed, + ) + return self._append_node(node) + + def is_in(self, other: Any) -> Self: + """Check if elements of this expression are present in the other iterable. + + Arguments: + other: iterable + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 9, 10]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(b=nw.col("a").is_in([1, 2])) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 True | + | 1 2 True | + | 2 9 False | + | 3 10 False | + └──────────────────┘ + """ + if isinstance(other, Iterable) and not isinstance(other, (str, bytes)): + return self._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "is_in", + other=to_native(other, pass_through=True), + ) + ) + msg = "Narwhals `is_in` doesn't accept expressions as an argument, as opposed to Polars. You should provide an iterable instead." + raise NotImplementedError(msg) + + def filter(self, *predicates: Any) -> Self: + """Filters elements based on a condition, returning a new expression. + + Arguments: + predicates: Conditions to filter by (which get AND-ed together). + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [2, 3, 4, 5, 6, 7], "b": [10, 11, 12, 13, 14, 15]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.select( + ... nw.col("a").filter(nw.col("a") > 4), + ... nw.col("b").filter(nw.col("b") < 13), + ... ) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 3 5 10 | + | 4 6 11 | + | 5 7 12 | + └──────────────────┘ + """ + return self._append_node( + ExprNode(ExprKind.FILTRATION, "filter", exprs=predicates) + ) + + def is_null(self) -> Self: + """Returns a boolean Series indicating which values are null. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES (null, CAST('NaN' AS DOUBLE)), (2, 2.) df(a, b)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_is_null=nw.col("a").is_null(), b_is_null=nw.col("b").is_null() + ... ) + ┌──────────────────────────────────────────┐ + | Narwhals LazyFrame | + |------------------------------------------| + |┌───────┬────────┬───────────┬───────────┐| + |│ a │ b │ a_is_null │ b_is_null │| + |│ int32 │ double │ boolean │ boolean │| + |├───────┼────────┼───────────┼───────────┤| + |│ NULL │ nan │ true │ false │| + |│ 2 │ 2.0 │ false │ false │| + |└───────┴────────┴───────────┴───────────┘| + └──────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "is_null")) + + def is_nan(self) -> Self: + """Indicate which values are NaN. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES (null, CAST('NaN' AS DOUBLE)), (2, 2.) df(a, b)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_is_nan=nw.col("a").is_nan(), b_is_nan=nw.col("b").is_nan() + ... ) + ┌────────────────────────────────────────┐ + | Narwhals LazyFrame | + |----------------------------------------| + |┌───────┬────────┬──────────┬──────────┐| + |│ a │ b │ a_is_nan │ b_is_nan │| + |│ int32 │ double │ boolean │ boolean │| + |├───────┼────────┼──────────┼──────────┤| + |│ NULL │ nan │ NULL │ true │| + |│ 2 │ 2.0 │ false │ false │| + |└───────┴────────┴──────────┴──────────┘| + └────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "is_nan")) + + def fill_null( + self, + value: Expr | NonNestedLiteral = None, + strategy: FillNullStrategy | None = None, + limit: int | None = None, + ) -> Self: + """Fill null values with given value. + + Arguments: + value: Value or expression used to fill null values. + strategy: Strategy used to fill null values. + limit: Number of consecutive null values to fill when using the 'forward' or 'backward' strategy. + + Notes: + - pandas handles null values differently from other libraries. + See [null_handling](../concepts/null_handling.md/) + for reference. + - For pandas Series of `object` dtype, `fill_null` will not automatically change the + Series' dtype as pandas used to do. Explicitly call `cast` if you want the dtype to change. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... { + ... "a": [2, None, None, 3], + ... "b": [2.0, float("nan"), float("nan"), 3.0], + ... "c": [1, 2, 3, 4], + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a", "b").fill_null(0).name.suffix("_filled"), + ... nw.col("a").fill_null(nw.col("c")).name.suffix("_filled_with_c"), + ... ) + ┌────────────────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------------------------------------| + |shape: (4, 6) | + |┌──────┬─────┬─────┬──────────┬──────────┬─────────────────┐| + |│ a ┆ b ┆ c ┆ a_filled ┆ b_filled ┆ a_filled_with_c │| + |│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │| + |│ i64 ┆ f64 ┆ i64 ┆ i64 ┆ f64 ┆ i64 │| + |╞══════╪═════╪═════╪══════════╪══════════╪═════════════════╡| + |│ 2 ┆ 2.0 ┆ 1 ┆ 2 ┆ 2.0 ┆ 2 │| + |│ null ┆ NaN ┆ 2 ┆ 0 ┆ NaN ┆ 2 │| + |│ null ┆ NaN ┆ 3 ┆ 0 ┆ NaN ┆ 3 │| + |│ 3 ┆ 3.0 ┆ 4 ┆ 3 ┆ 3.0 ┆ 3 │| + |└──────┴─────┴─────┴──────────┴──────────┴─────────────────┘| + └────────────────────────────────────────────────────────────┘ + + Using a strategy: + + >>> df.select( + ... nw.col("a", "b"), + ... nw.col("a", "b") + ... .fill_null(strategy="forward", limit=1) + ... .name.suffix("_nulls_forward_filled"), + ... ) + ┌────────────────────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------------------------------------------| + |shape: (4, 4) | + |┌──────┬─────┬────────────────────────┬────────────────────────┐| + |│ a ┆ b ┆ a_nulls_forward_filled ┆ b_nulls_forward_filled │| + |│ --- ┆ --- ┆ --- ┆ --- │| + |│ i64 ┆ f64 ┆ i64 ┆ f64 │| + |╞══════╪═════╪════════════════════════╪════════════════════════╡| + |│ 2 ┆ 2.0 ┆ 2 ┆ 2.0 │| + |│ null ┆ NaN ┆ 2 ┆ NaN │| + |│ null ┆ NaN ┆ null ┆ NaN │| + |│ 3 ┆ 3.0 ┆ 3 ┆ 3.0 │| + |└──────┴─────┴────────────────────────┴────────────────────────┘| + └────────────────────────────────────────────────────────────────┘ + """ + if value is not None and strategy is not None: + msg = "cannot specify both `value` and `strategy`" + raise ValueError(msg) + if value is None and strategy is None: + msg = "must specify either a fill `value` or `strategy`" + raise ValueError(msg) + if strategy is not None and strategy not in {"forward", "backward"}: + msg = f"strategy not supported: {strategy}" + raise ValueError(msg) + + if strategy is not None: + node = ExprNode( + ExprKind.ORDERABLE_WINDOW, + "fill_null", + value=value, + strategy=strategy, + limit=limit, + ) + else: + node = ExprNode( + ExprKind.ELEMENTWISE, + "fill_null", + exprs=(value,), + strategy=strategy, + limit=limit, + str_as_lit=True, + ) + return self._append_node(node) + + def fill_nan(self, value: float | None) -> Self: + """Fill floating point NaN values with given value. + + Arguments: + value: Value used to fill NaN values. + + Notes: + This function only fills `'NaN'` values, not null ones, except for pandas + which doesn't distinguish between them. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES (5.::DOUBLE, 50.::DOUBLE), ('NaN', null) df(a, b)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a", "b").fill_nan(0).name.suffix("_nans_filled")) + ┌───────────────────────────────────────────────────┐ + | Narwhals LazyFrame | + |---------------------------------------------------| + |┌────────┬────────┬───────────────┬───────────────┐| + |│ a │ b │ a_nans_filled │ b_nans_filled │| + |│ double │ double │ double │ double │| + |├────────┼────────┼───────────────┼───────────────┤| + |│ 5.0 │ 50.0 │ 5.0 │ 50.0 │| + |│ nan │ NULL │ 0.0 │ NULL │| + |└────────┴────────┴───────────────┴───────────────┘| + └───────────────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "fill_nan", value=value)) + + # --- partial reduction --- + def drop_nulls(self) -> Self: + """Drop null values. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [2.0, 4.0, float("nan"), 3.0, None, 5.0]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").drop_nulls()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (5, 1) | + | ┌─────┐ | + | │ a │ | + | │ --- │ | + | │ f64 │ | + | ╞═════╡ | + | │ 2.0 │ | + | │ 4.0 │ | + | │ NaN │ | + | │ 3.0 │ | + | │ 5.0 │ | + | └─────┘ | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.FILTRATION, "drop_nulls")) + + def over( + self, + *partition_by: str | Sequence[str], + order_by: str | Sequence[str] | None = None, + ) -> Self: + """Compute expressions over the given groups (optionally with given order). + + Arguments: + partition_by: Names of columns to compute window expression over. + Must be names of columns, as opposed to expressions - + so, this is a bit less flexible than Polars' `Expr.over`. + order_by: Column(s) to order window functions by. + For lazy backends, this argument is required when `over` is applied + to order-dependent functions, see [order-dependence](../concepts/order_dependence.md). + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 4], "b": ["x", "x", "y"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_min_per_group=nw.col("a").min().over("b")) + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + | a b a_min_per_group| + |0 1 x 1| + |1 2 x 1| + |2 4 y 4| + └────────────────────────┘ + + Cumulative operations are also supported, but (currently) only for + pandas and Polars: + + >>> df.with_columns(a_cum_sum_per_group=nw.col("a").cum_sum().over("b")) + ┌────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------| + | a b a_cum_sum_per_group| + |0 1 x 1| + |1 2 x 3| + |2 4 y 4| + └────────────────────────────┘ + """ + flat_partition_by = flatten(partition_by) + flat_order_by = [order_by] if isinstance(order_by, str) else (order_by or []) + if not flat_partition_by and not flat_order_by: # pragma: no cover + msg = "At least one of `partition_by` or `order_by` must be specified." + raise ValueError(msg) + node = ExprNode( + ExprKind.OVER, "over", partition_by=flat_partition_by, order_by=flat_order_by + ) + return self._with_over_node(node) + + def is_duplicated(self) -> Self: + r"""Return a boolean mask indicating duplicated values. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 1], "b": ["a", "a", "b", "c"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.all().is_duplicated().name.suffix("_is_duplicated")) + ┌─────────────────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------------------| + | a b a_is_duplicated b_is_duplicated| + |0 1 a True True| + |1 2 a False True| + |2 3 b False False| + |3 1 c True False| + └─────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.WINDOW, "is_duplicated")) + + def is_unique(self) -> Self: + r"""Return a boolean mask indicating unique values. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 1], "b": ["a", "a", "b", "c"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.all().is_unique().name.suffix("_is_unique")) + ┌─────────────────────────────────┐ + | Narwhals DataFrame | + |---------------------------------| + | a b a_is_unique b_is_unique| + |0 1 a False False| + |1 2 a True False| + |2 3 b True True| + |3 1 c False True| + └─────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.WINDOW, "is_unique")) + + def null_count(self) -> Self: + r"""Count null values. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [1, 2, None, 1], "b": ["a", None, "b", None]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.all().null_count()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 2 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "null_count")) + + def is_first_distinct(self) -> Self: + r"""Return a boolean mask indicating the first occurrence of each distinct value. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 1], "b": ["a", "a", "b", "c"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.all().is_first_distinct().name.suffix("_is_first_distinct") + ... ) + ┌─────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |-------------------------------------------------| + | a b a_is_first_distinct b_is_first_distinct| + |0 1 a True True| + |1 2 a True False| + |2 3 b True True| + |3 1 c False True| + └─────────────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ORDERABLE_WINDOW, "is_first_distinct")) + + def is_last_distinct(self) -> Self: + r"""Return a boolean mask indicating the last occurrence of each distinct value. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3, 1], "b": ["a", "a", "b", "c"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.all().is_last_distinct().name.suffix("_is_last_distinct") + ... ) + ┌───────────────────────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------------------------| + | a b a_is_last_distinct b_is_last_distinct| + |0 1 a False False| + |1 2 a True True| + |2 3 b True True| + |3 1 c True True| + └───────────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ORDERABLE_WINDOW, "is_last_distinct")) + + def quantile( + self, quantile: float, interpolation: RollingInterpolationMethod + ) -> Self: + r"""Get quantile value. + + Arguments: + quantile: Quantile between 0.0 and 1.0. + interpolation: Interpolation method. + + Note: + - pandas and Polars may have implementation differences for a given interpolation method. + - [dask](https://docs.dask.org/en/stable/generated/dask.dataframe.Series.quantile.html) has + its own method to approximate quantile and it doesn't implement 'nearest', 'higher', + 'lower', 'midpoint' as interpolation method - use 'linear' which is closest to the + native 'dask' - method. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": list(range(50)), "b": list(range(50, 100))} + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a", "b").quantile(0.5, interpolation="linear")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 24.5 74.5 | + └──────────────────┘ + """ + return self._append_node( + ExprNode( + ExprKind.AGGREGATION, + "quantile", + quantile=quantile, + interpolation=interpolation, + ) + ) + + def round(self, decimals: int = 0) -> Self: + r"""Round underlying floating point data by `decimals` digits. + + Arguments: + decimals: Number of decimals to round by. + + + Notes: + For values exactly halfway between rounded decimal values pandas behaves differently than Polars and Arrow. + + pandas rounds to the nearest even value (e.g. -0.5 and 0.5 round to 0.0, 1.5 and 2.5 round to 2.0, 3.5 and + 4.5 to 4.0, etc..). + + Polars and Arrow round away from 0 (e.g. -0.5 to -1.0, 0.5 to 1.0, 1.5 to 2.0, 2.5 to 3.0, etc..). + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1.12345, 2.56789, 3.901234]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_rounded=nw.col("a").round(1)) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + | a a_rounded| + |0 1.123450 1.1| + |1 2.567890 2.6| + |2 3.901234 3.9| + └──────────────────────┘ + """ + return self._append_node( + ExprNode(ExprKind.ELEMENTWISE, "round", decimals=decimals) + ) + + def floor(self) -> Self: + r"""Compute the numerical floor. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"values": [1.1, 4.3, -1.3]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns(floor=nw.col("values").floor()) + >>> result + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + |pyarrow.Table | + |values: double | + |floor: double | + |---- | + |values: [[1.1,4.3,-1.3]]| + |floor: [[1,4,-2]] | + └────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "floor")) + + def ceil(self) -> Self: + r"""Compute the numerical ceiling. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"values": [1.1, 4.3, -1.3]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns(ceil=nw.col("values").ceil()) + >>> result + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + |pyarrow.Table | + |values: double | + |ceil: double | + |---- | + |values: [[1.1,4.3,-1.3]]| + |ceil: [[2,5,-1]] | + └────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "ceil")) + + def len(self) -> Self: + r"""Return the number of elements in the column. + + Null values count towards the total. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["x", "y", "z"], "b": [1, 2, 1]}) + >>> df = nw.from_native(df_native) + >>> df.select( + ... nw.col("a").filter(nw.col("b") == 1).len().alias("a1"), + ... nw.col("a").filter(nw.col("b") == 2).len().alias("a2"), + ... ) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a1 a2 | + | 0 2 1 | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.AGGREGATION, "len")) + + def clip( + self, + lower_bound: IntoExpr | NumericLiteral | TemporalLiteral | None = None, + upper_bound: IntoExpr | NumericLiteral | TemporalLiteral | None = None, + ) -> Self: + r"""Clip values in the Series. + + Arguments: + lower_bound: Lower bound value. String literals are treated as column names. + upper_bound: Upper bound value. String literals are treated as column names. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 2, 3]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_clipped=nw.col("a").clip(-1, 3)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a a_clipped | + | 0 1 1 | + | 1 2 2 | + | 2 3 3 | + └──────────────────┘ + """ + if upper_bound is None: + return self._append_node( + ExprNode(ExprKind.ELEMENTWISE, "clip_lower", exprs=(lower_bound,)) + ) + if lower_bound is None: + return self._append_node( + ExprNode(ExprKind.ELEMENTWISE, "clip_upper", exprs=(upper_bound,)) + ) + return self._append_node( + ExprNode(ExprKind.ELEMENTWISE, "clip", exprs=(lower_bound, upper_bound)) + ) + + def first(self, order_by: str | Iterable[str] | None = None) -> Self: + """Get the first value. + + Notes: + For lazy backends, this can only be used with `over` or with `order_by`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> data = {"a": [1, 1, 2, 2], "b": ["foo", None, None, "baz"]} + >>> df_native = pd.DataFrame(data) + >>> df = nw.from_native(df_native) + >>> df.select(nw.all().first()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 foo | + └──────────────────┘ + + >>> df.group_by("a").agg(nw.col("b").first()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 foo | + | 1 2 NaN | + └──────────────────┘ + """ + if order_by is None: + return self._append_node(ExprNode(ExprKind.ORDERABLE_AGGREGATION, "first")) + return self._append_node( + ExprNode( + ExprKind.AGGREGATION, + "first", + order_by=[order_by] if isinstance(order_by, str) else order_by, + ) + ) + + def last(self, order_by: str | Iterable[str] | None = None) -> Self: + """Get the last value. + + Notes: + For lazy backends, this can only be used with `over` or with `order_by`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> data = {"a": [1, 1, 2, 2], "b": ["foo", None, None, "baz"]} + >>> df_native = pa.table(data) + >>> df = nw.from_native(df_native) + >>> df.select(nw.all().last()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int64 | + | b: string | + | ---- | + | a: [[2]] | + | b: [["baz"]] | + └──────────────────┘ + + >>> df.group_by("a").agg(nw.col("b").last()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |pyarrow.Table | + |a: int64 | + |b: string | + |---- | + |a: [[1,2]] | + |b: [[null,"baz"]] | + └──────────────────┘ + """ + if order_by is None: + return self._append_node(ExprNode(ExprKind.ORDERABLE_AGGREGATION, "last")) + return self._append_node( + ExprNode( + ExprKind.AGGREGATION, + "last", + order_by=[order_by] if isinstance(order_by, str) else order_by, + ) + ) + + def mode(self, *, keep: ModeKeepStrategy = "all") -> Self: + r"""Compute the most occurring value(s). + + Can return multiple values. + + Arguments: + keep: Whether to keep all modes or any mode found. Remark that `keep='any'` + is not deterministic for multimodal values. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 1, 2, 3], "b": [1, 1, 2, 2]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").mode()).sort("a") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a | + | 0 1 | + └──────────────────┘ + """ + _supported_keep_values = ("all", "any") + if keep not in _supported_keep_values: # pragma: no cover + msg = f"`keep` must be one of {_supported_keep_values}, found '{keep}'" + raise ValueError(msg) + kind = ExprKind.AGGREGATION if keep == "any" else ExprKind.FILTRATION + return self._append_node(ExprNode(kind, "mode", keep=keep)) + + def is_finite(self) -> Self: + """Returns boolean values indicating which original values are finite. + + Warning: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + `is_finite` will return False for NaN and Null's in the Dask and + pandas non-nullable backend, while for Polars, PyArrow and pandas + nullable backends null values are kept as such. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [float("nan"), float("inf"), 2.0, None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_is_finite=nw.col("a").is_finite()) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + |shape: (4, 2) | + |┌──────┬─────────────┐| + |│ a ┆ a_is_finite │| + |│ --- ┆ --- │| + |│ f64 ┆ bool │| + |╞══════╪═════════════╡| + |│ NaN ┆ false │| + |│ inf ┆ false │| + |│ 2.0 ┆ true │| + |│ null ┆ null │| + |└──────┴─────────────┘| + └──────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "is_finite")) + + def cum_count(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative count of the non-null values in the column. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["x", "k", None, "d"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").cum_count().alias("a_cum_count"), + ... nw.col("a").cum_count(reverse=True).alias("a_cum_count_reverse"), + ... ) + ┌────────────────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------------------| + | a a_cum_count a_cum_count_reverse| + |0 x 1 3| + |1 k 2 2| + |2 NaN 2 1| + |3 d 3 1| + └────────────────────────────────────────┘ + """ + return self._append_node( + ExprNode(ExprKind.ORDERABLE_WINDOW, "cum_count", reverse=reverse) + ) + + def cum_min(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative min of the non-null values in the column. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [3, 1, None, 2]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").cum_min().alias("a_cum_min"), + ... nw.col("a").cum_min(reverse=True).alias("a_cum_min_reverse"), + ... ) + ┌────────────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------------| + | a a_cum_min a_cum_min_reverse| + |0 3.0 3.0 1.0| + |1 1.0 1.0 1.0| + |2 NaN NaN NaN| + |3 2.0 1.0 2.0| + └────────────────────────────────────┘ + """ + return self._append_node( + ExprNode(ExprKind.ORDERABLE_WINDOW, "cum_min", reverse=reverse) + ) + + def cum_max(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative max of the non-null values in the column. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 3, None, 2]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").cum_max().alias("a_cum_max"), + ... nw.col("a").cum_max(reverse=True).alias("a_cum_max_reverse"), + ... ) + ┌────────────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------------| + | a a_cum_max a_cum_max_reverse| + |0 1.0 1.0 3.0| + |1 3.0 3.0 3.0| + |2 NaN NaN NaN| + |3 2.0 3.0 2.0| + └────────────────────────────────────┘ + """ + return self._append_node( + ExprNode(ExprKind.ORDERABLE_WINDOW, "cum_max", reverse=reverse) + ) + + def cum_prod(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative product of the non-null values in the column. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1, 3, None, 2]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").cum_prod().alias("a_cum_prod"), + ... nw.col("a").cum_prod(reverse=True).alias("a_cum_prod_reverse"), + ... ) + ┌──────────────────────────────────────┐ + | Narwhals DataFrame | + |--------------------------------------| + | a a_cum_prod a_cum_prod_reverse| + |0 1.0 1.0 6.0| + |1 3.0 3.0 6.0| + |2 NaN NaN NaN| + |3 2.0 6.0 2.0| + └──────────────────────────────────────┘ + """ + return self._append_node( + ExprNode(ExprKind.ORDERABLE_WINDOW, "cum_prod", reverse=reverse) + ) + + def rolling_sum( + self, window_size: int, *, min_samples: int | None = None, center: bool = False + ) -> Self: + """Apply a rolling sum (moving sum) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their sum. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size` + center: Set the labels at the center of the window. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1.0, 2.0, None, 4.0]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_rolling_sum=nw.col("a").rolling_sum(window_size=3, min_samples=1) + ... ) + ┌─────────────────────┐ + | Narwhals DataFrame | + |---------------------| + | a a_rolling_sum| + |0 1.0 1.0| + |1 2.0 3.0| + |2 NaN 3.0| + |3 4.0 6.0| + └─────────────────────┘ + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + return self._append_node( + ExprNode( + ExprKind.ORDERABLE_WINDOW, + "rolling_sum", + window_size=window_size, + min_samples=min_samples, + center=center, + ) + ) + + def rolling_mean( + self, window_size: int, *, min_samples: int | None = None, center: bool = False + ) -> Self: + """Apply a rolling mean (moving mean) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their mean. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size` + center: Set the labels at the center of the window. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1.0, 2.0, None, 4.0]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_rolling_mean=nw.col("a").rolling_mean(window_size=3, min_samples=1) + ... ) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + | a a_rolling_mean| + |0 1.0 1.0| + |1 2.0 1.5| + |2 NaN 1.5| + |3 4.0 3.0| + └──────────────────────┘ + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + return self._append_node( + ExprNode( + ExprKind.ORDERABLE_WINDOW, + "rolling_mean", + window_size=window_size, + min_samples=min_samples, + center=center, + ) + ) + + def rolling_var( + self, + window_size: int, + *, + min_samples: int | None = None, + center: bool = False, + ddof: int = 1, + ) -> Self: + """Apply a rolling variance (moving variance) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their variance. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size`. + center: Set the labels at the center of the window. + ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1.0, 2.0, None, 4.0]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_rolling_var=nw.col("a").rolling_var(window_size=3, min_samples=1) + ... ) + ┌─────────────────────┐ + | Narwhals DataFrame | + |---------------------| + | a a_rolling_var| + |0 1.0 NaN| + |1 2.0 0.5| + |2 NaN 0.5| + |3 4.0 2.0| + └─────────────────────┘ + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + return self._append_node( + ExprNode( + ExprKind.ORDERABLE_WINDOW, + "rolling_var", + ddof=ddof, + window_size=window_size, + min_samples=min_samples, + center=center, + ) + ) + + def rolling_std( + self, + window_size: int, + *, + min_samples: int | None = None, + center: bool = False, + ddof: int = 1, + ) -> Self: + """Apply a rolling standard deviation (moving standard deviation) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their standard deviation. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size`. + center: Set the labels at the center of the window. + ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [1.0, 2.0, None, 4.0]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_rolling_std=nw.col("a").rolling_std(window_size=3, min_samples=1) + ... ) + ┌─────────────────────┐ + | Narwhals DataFrame | + |---------------------| + | a a_rolling_std| + |0 1.0 NaN| + |1 2.0 0.707107| + |2 NaN 0.707107| + |3 4.0 1.414214| + └─────────────────────┘ + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + return self._append_node( + ExprNode( + ExprKind.ORDERABLE_WINDOW, + "rolling_std", + ddof=ddof, + window_size=window_size, + min_samples=min_samples, + center=center, + ) + ) + + def rank(self, method: RankMethod = "average", *, descending: bool = False) -> Self: + """Assign ranks to data, dealing with ties appropriately. + + Notes: + The resulting dtype may differ between backends. + + Info: + For lazy backends, this operation must be followed by `Expr.over` with + `order_by` specified, see [order-dependence](../concepts/order_dependence.md). + + Arguments: + method: The method used to assign ranks to tied elements. + The following methods are available (default is 'average') + + - *"average"*: The average of the ranks that would have been assigned to + all the tied values is assigned to each value. + - *"min"*: The minimum of the ranks that would have been assigned to all + the tied values is assigned to each value. (This is also referred to + as "competition" ranking.) + - *"max"*: The maximum of the ranks that would have been assigned to all + the tied values is assigned to each value. + - *"dense"*: Like "min", but the rank of the next highest element is + assigned the rank immediately after those assigned to the tied elements. + - *"ordinal"*: All values are given a distinct rank, corresponding to the + order that the values occur in the Series. + + descending: Rank in descending order. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": [3, 6, 1, 1, 6]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns(rank=nw.col("a").rank(method="dense")) + >>> result + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a rank | + | 0 3 2.0 | + | 1 6 3.0 | + | 2 1 1.0 | + | 3 1 1.0 | + | 4 6 3.0 | + └──────────────────┘ + """ + supported_rank_methods = {"average", "min", "max", "dense", "ordinal"} + if method not in supported_rank_methods: + msg = ( + "Ranking method must be one of {'average', 'min', 'max', 'dense', 'ordinal'}. " + f"Found '{method}'" + ) + raise ValueError(msg) + + return self._append_node( + ExprNode(ExprKind.WINDOW, "rank", method=method, descending=descending) + ) + + def log(self, base: float = math.e) -> Self: + r"""Compute the logarithm to a given base. + + Arguments: + base: Given base, defaults to `e` + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"values": [1, 2, 4]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns( + ... log=nw.col("values").log(), log_2=nw.col("values").log(base=2) + ... ) + >>> result + ┌────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------------------------| + |pyarrow.Table | + |values: int64 | + |log: double | + |log_2: double | + |---- | + |values: [[1,2,4]] | + |log: [[0,0.6931471805599453,1.3862943611198906]]| + |log_2: [[0,1,2]] | + └────────────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "log", base=base)) + + def exp(self) -> Self: + r"""Compute the exponent. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"values": [-1, 0, 1]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns(exp=nw.col("values").exp()) + >>> result + ┌────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------------------------| + |pyarrow.Table | + |values: int64 | + |exp: double | + |---- | + |values: [[-1,0,1]] | + |exp: [[0.36787944117144233,1,2.718281828459045]]| + └────────────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "exp")) + + def sin(self) -> Self: + r"""Compute the element-wise value for the sine. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> from math import pi + >>> df_native = pa.table({"values": [0, pi / 2, 3 * pi / 2]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns(sin=nw.col("values").sin()) + >>> result + ┌─────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |-------------------------------------------------| + |pyarrow.Table | + |values: double | + |sin: double | + |---- | + |values: [[0,1.5707963267948966,4.71238898038469]]| + |sin: [[0,1,-1]] | + └─────────────────────────────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "sin")) + + def cos(self) -> Self: + r"""Compute the element-wise value for the cosine. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> from math import pi + >>> df_native = pa.table({"values": [0, pi / 2, pi]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns(cos=nw.col("values").cos()).select( + ... nw.all().round(4) + ... ) + >>> result + ┌───────────────────────────┐ + | Narwhals DataFrame | + |---------------------------| + |pyarrow.Table | + |values: double | + |cos: double | + |---- | + |values: [[0,1.5708,3.1416]]| + |cos: [[1,0,-1]] | + └───────────────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "cos")) + + def sqrt(self) -> Self: + r"""Compute the square root of the elements. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"values": [1, 4, 9]}) + >>> df = nw.from_native(df_native) + >>> result = df.with_columns(sqrt=nw.col("values").sqrt()) + >>> result + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |pyarrow.Table | + |values: int64 | + |sqrt: double | + |---- | + |values: [[1,4,9]] | + |sqrt: [[1,2,3]] | + └──────────────────┘ + """ + return self._append_node(ExprNode(ExprKind.ELEMENTWISE, "sqrt")) + + def is_close( # noqa: PLR0914 + self, + other: Expr | Series[Any] | NumericLiteral, + *, + abs_tol: float = 0.0, + rel_tol: float = 1e-09, + nans_equal: bool = False, + ) -> Self: + r"""Check if this expression is close, i.e. almost equal, to the other expression. + + Two values `a` and `b` are considered close if the following condition holds: + + $$ + |a-b| \le max \{ \text{rel\_tol} \cdot max \{ |a|, |b| \}, \text{abs\_tol} \} + $$ + + Arguments: + other: Values to compare with. + abs_tol: Absolute tolerance. This is the maximum allowed absolute difference + between two values. Must be non-negative. + rel_tol: Relative tolerance. This is the maximum allowed difference between + two values, relative to the larger absolute value. Must be in the range + [0, 1). + nans_equal: Whether NaN values should be considered equal. + + Notes: + The implementation of this method is symmetric and mirrors the behavior of + `math.isclose`. Specifically note that this behavior is different to + `numpy.isclose`. + + Examples: + >>> import duckdb + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> data = { + ... "x": [1.0, float("inf"), 1.41, None, float("nan")], + ... "y": [1.2, float("inf"), 1.40, None, float("nan")], + ... } + >>> _table = pa.table(data) + >>> df_native = duckdb.table("_table") + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... is_close=nw.col("x").is_close( + ... nw.col("y"), abs_tol=0.1, nans_equal=True + ... ) + ... ) + ┌──────────────────────────────┐ + | Narwhals LazyFrame | + |------------------------------| + |┌────────┬────────┬──────────┐| + |│ x │ y │ is_close │| + |│ double │ double │ boolean │| + |├────────┼────────┼──────────┤| + |│ 1.0 │ 1.2 │ false │| + |│ inf │ inf │ true │| + |│ 1.41 │ 1.4 │ true │| + |│ NULL │ NULL │ NULL │| + |│ nan │ nan │ true │| + |└────────┴────────┴──────────┘| + └──────────────────────────────┘ + """ + if abs_tol < 0: + msg = f"`abs_tol` must be non-negative but got {abs_tol}" + raise ComputeError(msg) + + if not (0 <= rel_tol < 1): + msg = f"`rel_tol` must be in the range [0, 1) but got {rel_tol}" + raise ComputeError(msg) + + from decimal import Decimal + + other_f: Expr | Series[Any] | NumericLiteral + other_abs: Expr | Series[Any] | NumericLiteral + other_is_nan: Expr | Series[Any] | bool + other_is_inf: Expr | Series[Any] | bool + other_is_not_inf: Expr | Series[Any] | bool + + # Promote to float to handle non-float numeric types (e.g. Decimal, integers). + # Adding 0.0 lets each backend decide the appropriate float type. + self_f = self + 0.0 + + if isinstance(other, (float, int, Decimal)): + from math import isinf, isnan + + other_f = float(other) + # NOTE: See https://discuss.python.org/t/inferred-type-of-function-that-calls-dunder-abs-abs/101447 + other_abs = other_f.__abs__() + other_is_nan = isnan(other_f) + other_is_inf = isinf(other_f) + + # Define the other_is_not_inf variable to prevent triggering the following warning: + # > DeprecationWarning: Bitwise inversion '~' on bool is deprecated and will be + # > removed in Python 3.16. + other_is_not_inf = not other_is_inf + + else: + other_f = other + 0.0 + other_abs, other_is_nan = other_f.abs(), other_f.is_nan() + other_is_not_inf = other_f.is_finite() | other_is_nan + other_is_inf = ~other_is_not_inf + + rel_threshold = ( + self_f.abs().clip(lower_bound=other_abs, upper_bound=None) * rel_tol + ) + tolerance = rel_threshold.clip(lower_bound=abs_tol, upper_bound=None) + + self_is_nan = self_f.is_nan() + self_is_not_inf = self_f.is_finite() | self_is_nan + + # Values are close if abs_diff <= tolerance, and both finite + is_close = ( + ((self_f - other_f).abs() <= tolerance) & self_is_not_inf & other_is_not_inf + ) + + # Handle infinity cases: infinities are close/equal if they have the same sign + self_sign, other_sign = self_f > 0, other_f > 0 + is_same_inf = (~self_is_not_inf) & other_is_inf & (self_sign == other_sign) + + # Handle nan cases: + # * If any value is NaN, then False (via `& ~either_nan`) + # * However, if `nans_equals = True` and if _both_ values are NaN, then True + either_nan = self_is_nan | other_is_nan + result = (is_close | is_same_inf) & ~either_nan + + if nans_equal: + both_nan = self_is_nan & other_is_nan + result = result | both_nan + + return result + + @unstable + def any_value(self, *, ignore_nulls: bool = False) -> Self: + """Get a random value from the column. + + Warning: + This functionality is considered **unstable** as it diverges from the polars API. + It may be changed at any point without it being considered a breaking change. + + Arguments: + ignore_nulls: Whether to ignore null values or not. + If `True` and there are no not-null elements, then `None` is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> data = {"a": [1, 1, 2, 2], "b": [None, "foo", "baz", None]} + >>> df_native = pa.table(data) + >>> df = nw.from_native(df_native) + >>> df.select(nw.all().any_value(ignore_nulls=False)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int64 | + | b: null | + | ---- | + | a: [[1]] | + | b: [1 nulls] | + └──────────────────┘ + + >>> df.group_by("a").agg(nw.col("b").any_value(ignore_nulls=True)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |pyarrow.Table | + |a: int64 | + |b: string | + |---- | + |a: [[1,2]] | + |b: [["foo","baz"]]| + └──────────────────┘ + + """ + return self._append_node( + ExprNode(ExprKind.AGGREGATION, "any_value", ignore_nulls=ignore_nulls) + ) + + @property + def str(self) -> ExprStringNamespace[Self]: + return ExprStringNamespace(self) + + @property + def dt(self) -> ExprDateTimeNamespace[Self]: + return ExprDateTimeNamespace(self) + + @property + def cat(self) -> ExprCatNamespace[Self]: + return ExprCatNamespace(self) + + @property + def name(self) -> ExprNameNamespace[Self]: + return ExprNameNamespace(self) + + @property + def list(self) -> ExprListNamespace[Self]: + return ExprListNamespace(self) + + @property + def struct(self) -> ExprStructNamespace[Self]: + return ExprStructNamespace(self) + + +__all__ = ["Expr"] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_cat.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_cat.py new file mode 100644 index 0000000000000000000000000000000000000000..ff29bdd64d5fbd996e817e3b86f8c92fc6dae590 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_cat.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode + +if TYPE_CHECKING: + from narwhals.expr import Expr + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprCatNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def get_categories(self) -> ExprT: + """Get unique categories from column. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"fruits": ["apple", "mango", "mango"]}, + ... schema={"fruits": pl.Categorical}, + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("fruits").cat.get_categories()).to_native() + shape: (2, 1) + ┌────────┐ + │ fruits │ + │ --- │ + │ str │ + ╞════════╡ + │ apple │ + │ mango │ + └────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.FILTRATION, "cat.get_categories") + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_dt.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_dt.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8c31055e6db5fad7ea4cf04fd1512a23212120 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_dt.py @@ -0,0 +1,738 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode + +if TYPE_CHECKING: + from narwhals.expr import Expr + from narwhals.typing import TimeUnit + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprDateTimeNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def date(self) -> ExprT: + """Extract the date from underlying DateTime representation. + + Raises: + NotImplementedError: If pandas default backend is being used. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [datetime(2012, 1, 7, 10), datetime(2027, 12, 13)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.date()).to_native() + shape: (2, 1) + ┌────────────┐ + │ a │ + │ --- │ + │ date │ + ╞════════════╡ + │ 2012-01-07 │ + │ 2027-12-13 │ + └────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.date")) + + def year(self) -> ExprT: + """Extract year from underlying DateTime representation. + + Returns the year number in the calendar date. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.year().alias("year")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a year| + |0 1978-06-01 1978| + |1 2065-01-01 2065| + └──────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.year")) + + def month(self) -> ExprT: + """Extract month from underlying DateTime representation. + + Returns the month number starting from 1. The return value ranges from 1 to 12. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.month().alias("month")).to_native() + pyarrow.Table + a: timestamp[us] + month: int64 + ---- + a: [[1978-06-01 00:00:00.000000,2065-01-01 00:00:00.000000]] + month: [[6,1]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.month")) + + def day(self) -> ExprT: + """Extract day from underlying DateTime representation. + + Returns the day of month starting from 1. The return value ranges from 1 to 31. (The last day of month differs by months.) + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.day().alias("day")).to_native() + pyarrow.Table + a: timestamp[us] + day: int64 + ---- + a: [[1978-06-01 00:00:00.000000,2065-01-01 00:00:00.000000]] + day: [[1,1]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.day")) + + def hour(self) -> ExprT: + """Extract hour from underlying DateTime representation. + + Returns the hour number from 0 to 23. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [datetime(1978, 1, 1, 1), datetime(2065, 1, 1, 10)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.hour().alias("hour")) + ┌──────────────────────────────┐ + | Narwhals DataFrame | + |------------------------------| + |shape: (2, 2) | + |┌─────────────────────┬──────┐| + |│ a ┆ hour │| + |│ --- ┆ --- │| + |│ datetime[μs] ┆ i8 │| + |╞═════════════════════╪══════╡| + |│ 1978-01-01 01:00:00 ┆ 1 │| + |│ 2065-01-01 10:00:00 ┆ 10 │| + |└─────────────────────┴──────┘| + └──────────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.hour")) + + def minute(self) -> ExprT: + """Extract minutes from underlying DateTime representation. + + Returns the minute number from 0 to 59. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(1978, 1, 1, 1, 1), datetime(2065, 1, 1, 10, 20)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.minute().alias("minute")).to_native() + a minute + 0 1978-01-01 01:01:00 1 + 1 2065-01-01 10:20:00 20 + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.minute")) + + def second(self) -> ExprT: + """Extract seconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1), + ... datetime(2065, 1, 1, 10, 20, 30), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("a").dt.second().alias("second")).to_native() + pyarrow.Table + a: timestamp[us] + second: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.000000]] + second: [[1,30]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.second")) + + def millisecond(self) -> ExprT: + """Extract milliseconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1, 0), + ... datetime(2065, 1, 1, 10, 20, 30, 67000), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").dt.millisecond().alias("millisecond") + ... ).to_native() + pyarrow.Table + a: timestamp[us] + millisecond: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]] + millisecond: [[0,67]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.millisecond")) + + def microsecond(self) -> ExprT: + """Extract microseconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1, 0), + ... datetime(2065, 1, 1, 10, 20, 30, 67000), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").dt.microsecond().alias("microsecond") + ... ).to_native() + pyarrow.Table + a: timestamp[us] + microsecond: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]] + microsecond: [[0,67000]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.microsecond")) + + def nanosecond(self) -> ExprT: + """Extract Nanoseconds from underlying DateTime representation. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... datetime(1978, 1, 1, 1, 1, 1, 0), + ... datetime(2065, 1, 1, 10, 20, 30, 67000), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("a").dt.nanosecond().alias("nanosecond") + ... ).to_native() + pyarrow.Table + a: timestamp[us] + nanosecond: int64 + ---- + a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]] + nanosecond: [[0,67000000]] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.nanosecond")) + + def ordinal_day(self) -> ExprT: + """Get ordinal day. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(2020, 1, 1), datetime(2020, 8, 3)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_ordinal_day=nw.col("a").dt.ordinal_day()) + ┌───────────────────────────┐ + | Narwhals DataFrame | + |---------------------------| + | a a_ordinal_day| + |0 2020-01-01 1| + |1 2020-08-03 216| + └───────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.ordinal_day")) + + def weekday(self) -> ExprT: + """Extract the week day from the underlying Date representation. + + Note that Monday = 1 and Sunday = 7. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... {"a": [datetime(2020, 1, 1), datetime(2020, 8, 3)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_week_day=nw.col("a").dt.weekday()) + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + | a a_week_day| + |0 2020-01-01 3| + |1 2020-08-03 1| + └────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.weekday")) + + def total_minutes(self) -> ExprT: + """Get total minutes. + + Notes: + The function outputs the total minutes in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [timedelta(minutes=10), timedelta(minutes=20, seconds=40)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_minutes=nw.col("a").dt.total_minutes() + ... ).to_native() + shape: (2, 2) + ┌──────────────┬─────────────────┐ + │ a ┆ a_total_minutes │ + │ --- ┆ --- │ + │ duration[μs] ┆ i64 │ + ╞══════════════╪═════════════════╡ + │ 10m ┆ 10 │ + │ 20m 40s ┆ 20 │ + └──────────────┴─────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.total_minutes")) + + def total_seconds(self) -> ExprT: + """Get total seconds. + + Notes: + The function outputs the total seconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [timedelta(seconds=10), timedelta(seconds=20, milliseconds=40)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_seconds=nw.col("a").dt.total_seconds() + ... ).to_native() + shape: (2, 2) + ┌──────────────┬─────────────────┐ + │ a ┆ a_total_seconds │ + │ --- ┆ --- │ + │ duration[μs] ┆ i64 │ + ╞══════════════╪═════════════════╡ + │ 10s ┆ 10 │ + │ 20s 40ms ┆ 20 │ + └──────────────┴─────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.total_seconds")) + + def total_milliseconds(self) -> ExprT: + """Get total milliseconds. + + Notes: + The function outputs the total milliseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... { + ... "a": [ + ... timedelta(milliseconds=10), + ... timedelta(milliseconds=20, microseconds=40), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_milliseconds=nw.col("a").dt.total_milliseconds() + ... ).to_native() + shape: (2, 2) + ┌──────────────┬──────────────────────┐ + │ a ┆ a_total_milliseconds │ + │ --- ┆ --- │ + │ duration[μs] ┆ i64 │ + ╞══════════════╪══════════════════════╡ + │ 10ms ┆ 10 │ + │ 20040µs ┆ 20 │ + └──────────────┴──────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.total_milliseconds") + ) + + def total_microseconds(self) -> ExprT: + """Get total microseconds. + + Notes: + The function outputs the total microseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table( + ... { + ... "a": [ + ... timedelta(microseconds=10), + ... timedelta(milliseconds=1, microseconds=200), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_total_microseconds=nw.col("a").dt.total_microseconds() + ... ).to_native() + pyarrow.Table + a: duration[us] + a_total_microseconds: int64 + ---- + a: [[10,1200]] + a_total_microseconds: [[10,1200]] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.total_microseconds") + ) + + def total_nanoseconds(self) -> ExprT: + """Get total nanoseconds. + + Notes: + The function outputs the total nanoseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` and `cast` in this case. + + Examples: + >>> from datetime import timedelta + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": pd.to_datetime( + ... [ + ... "2024-01-01 00:00:00.000000001", + ... "2024-01-01 00:00:00.000000002", + ... ] + ... ) + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... a_diff_total_nanoseconds=nw.col("a").diff().dt.total_nanoseconds() + ... ).to_native() + a a_diff_total_nanoseconds + 0 2024-01-01 00:00:00.000000001 NaN + 1 2024-01-01 00:00:00.000000002 1.0 + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.total_nanoseconds") + ) + + def to_string(self, format: str) -> ExprT: + """Convert a Date/Time/Datetime column into a String column with the given format. + + Arguments: + format: Format to format temporal column with. + + Notes: + Unfortunately, different libraries interpret format directives a bit + differently. + + - Chrono, the library used by Polars, uses `"%.f"` for fractional seconds, + whereas pandas and Python stdlib use `".%f"`. + - PyArrow interprets `"%S"` as "seconds, including fractional seconds" + whereas most other tools interpret it as "just seconds, as 2 digits". + --- + Therefore, we make the following adjustments. + + - for pandas-like libraries, we replace `"%S.%f"` with `"%S%.f"`. + - for PyArrow, we replace `"%S.%f"` with `"%S"`. + --- + Workarounds like these don't make us happy, and we try to avoid them as + much as possible, but here we feel like it's the best compromise. + + If you just want to format a date/datetime Series as a local datetime + string, and have it work as consistently as possible across libraries, + we suggest using: + + - `"%Y-%m-%dT%H:%M:%S%.f"` for datetimes + - `"%Y-%m-%d"` for dates + --- + Though note that, even then, different tools may return a different number + of trailing zeros. Nonetheless, this is probably consistent enough for + most applications. + + If you have an application where this is not enough, please open an issue + and let us know. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"a": [datetime(2020, 3, 1), datetime(2020, 5, 1)]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.to_string("%Y/%m/%d %H:%M:%S")) + ┌───────────────────────┐ + | Narwhals DataFrame | + |-----------------------| + |shape: (2, 1) | + |┌─────────────────────┐| + |│ a │| + |│ --- │| + |│ str │| + |╞═════════════════════╡| + |│ 2020/03/01 00:00:00 │| + |│ 2020/05/01 00:00:00 │| + |└─────────────────────┘| + └───────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.to_string", format=format) + ) + + def replace_time_zone(self, time_zone: str | None) -> ExprT: + """Replace time zone. + + Arguments: + time_zone: Target time zone. + + Examples: + >>> from datetime import datetime, timezone + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": [ + ... datetime(2024, 1, 1, tzinfo=timezone.utc), + ... datetime(2024, 1, 2, tzinfo=timezone.utc), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.replace_time_zone("Asia/Kathmandu")).to_native() + a + 0 2024-01-01 00:00:00+05:45 + 1 2024-01-02 00:00:00+05:45 + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.replace_time_zone", time_zone=time_zone) + ) + + def convert_time_zone(self, time_zone: str) -> ExprT: + """Convert to a new time zone. + + If converting from a time-zone-naive column, then conversion happens + as if converting from UTC. + + Arguments: + time_zone: Target time zone. + + Examples: + >>> from datetime import datetime, timezone + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": [ + ... datetime(2024, 1, 1, tzinfo=timezone.utc), + ... datetime(2024, 1, 2, tzinfo=timezone.utc), + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").dt.convert_time_zone("Asia/Kathmandu")).to_native() + a + 0 2024-01-01 05:45:00+05:45 + 1 2024-01-02 05:45:00+05:45 + """ + if time_zone is None: + msg = "Target `time_zone` cannot be `None` in `convert_time_zone`. Please use `replace_time_zone(None)` if you want to remove the time zone." + raise TypeError(msg) + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.convert_time_zone", time_zone=time_zone) + ) + + def timestamp(self, time_unit: TimeUnit = "us") -> ExprT: + """Return a timestamp in the given time unit. + + Arguments: + time_unit: One of + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + + Examples: + >>> from datetime import date + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"date": [date(2001, 1, 1), None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("date").dt.timestamp("ms").alias("timestamp_ms")) + ┌─────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------| + |shape: (2, 2) | + |┌────────────┬──────────────┐| + |│ date ┆ timestamp_ms │| + |│ --- ┆ --- │| + |│ date ┆ i64 │| + |╞════════════╪══════════════╡| + |│ 2001-01-01 ┆ 978307200000 │| + |│ null ┆ null │| + |└────────────┴──────────────┘| + └─────────────────────────────┘ + """ + if time_unit not in {"ns", "us", "ms"}: + msg = ( + "invalid `time_unit`" + f"\n\nExpected one of {{'ns', 'us', 'ms'}}, got {time_unit!r}." + ) + raise ValueError(msg) + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.timestamp", time_unit=time_unit) + ) + + def truncate(self, every: str) -> ExprT: + """Divide the date/datetime range into buckets. + + Arguments: + every: Length of bucket. Must be of form ``, + where `multiple` is a positive integer and `unit` is one of + + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + - 's': second. + - 'm': minute. + - 'h': hour. + - 'd': day. + - 'mo': month. + - 'q': quarter. + - 'y': year. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"datetime": [datetime(2021, 3, 1, 12, 34)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("datetime").dt.truncate("1h").alias("datetime_trunc") + ... ) + ┌─────────────────────────────────────────────┐ + | Narwhals DataFrame | + |---------------------------------------------| + |shape: (1, 2) | + |┌─────────────────────┬─────────────────────┐| + |│ datetime ┆ datetime_trunc │| + |│ --- ┆ --- │| + |│ datetime[μs] ┆ datetime[μs] │| + |╞═════════════════════╪═════════════════════╡| + |│ 2021-03-01 12:34:00 ┆ 2021-03-01 12:00:00 │| + |└─────────────────────┴─────────────────────┘| + └─────────────────────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.truncate", every=every) + ) + + def offset_by(self, by: str) -> ExprT: + """Offset this date by a relative time offset. + + Arguments: + by: The offset. Must be of form ``, + where `multiple` is a positive integer and `unit` is one of + + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + - 's': second. + - 'm': minute. + - 'h': hour. + - 'd': day. + - 'mo': month. + - 'q': quarter. + - 'y': year. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"datetime": [datetime(2021, 3, 1, 12, 34)]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... nw.col("datetime").dt.offset_by("1h").alias("datetime_offset_by_1h") + ... ) + ┌───────────────────────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------------------------| + |shape: (1, 2) | + |┌─────────────────────┬───────────────────────┐| + |│ datetime ┆ datetime_offset_by_1h │| + |│ --- ┆ --- │| + |│ datetime[μs] ┆ datetime[μs] │| + |╞═════════════════════╪═══════════════════════╡| + |│ 2021-03-01 12:34:00 ┆ 2021-03-01 13:34:00 │| + |└─────────────────────┴───────────────────────┘| + └───────────────────────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "dt.offset_by", by=by) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_list.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_list.py new file mode 100644 index 0000000000000000000000000000000000000000..48f322c7ddf861f539115ecb76a52a64191dbb6f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_list.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode + +if TYPE_CHECKING: + from narwhals.expr import Expr + from narwhals.typing import NonNestedLiteral + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprListNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def len(self) -> ExprT: + """Return the number of elements in each list. + + Null values count towards the total. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [[1, 2], [3, 4, None], None, []]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_len=nw.col("a").list.len()) + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + |shape: (4, 2) | + |┌──────────────┬───────┐| + |│ a ┆ a_len │| + |│ --- ┆ --- │| + |│ list[i64] ┆ u32 │| + |╞══════════════╪═══════╡| + |│ [1, 2] ┆ 2 │| + |│ [3, 4, null] ┆ 3 │| + |│ null ┆ null │| + |│ [] ┆ 0 │| + |└──────────────┴───────┘| + └────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.len")) + + def unique(self) -> ExprT: + """Get the unique/distinct values in the list. + + Null values are included in the result. The order of unique values is not guaranteed. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [[1, 1, 2], [3, 3, None], None, []]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_unique=nw.col("a").list.unique()) + ┌────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------| + |shape: (4, 2) | + |┌──────────────┬───────────┐| + |│ a ┆ a_unique │| + |│ --- ┆ --- │| + |│ list[i64] ┆ list[i64] │| + |╞══════════════╪═══════════╡| + |│ [1, 1, 2] ┆ [1, 2] │| + |│ [3, 3, null] ┆ [null, 3] │| + |│ null ┆ null │| + |│ [] ┆ [] │| + |└──────────────┴───────────┘| + └────────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.unique")) + + def contains(self, item: NonNestedLiteral) -> ExprT: + """Check if sublists contain the given item. + + Arguments: + item: Item that will be checked for membership. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [[1, 2], None, []]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_contains_1=nw.col("a").list.contains(1)) + ┌────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------| + |shape: (3, 2) | + |┌───────────┬──────────────┐| + |│ a ┆ a_contains_1 │| + |│ --- ┆ --- │| + |│ list[i64] ┆ bool │| + |╞═══════════╪══════════════╡| + |│ [1, 2] ┆ true │| + |│ null ┆ null │| + |│ [] ┆ false │| + |└───────────┴──────────────┘| + └────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "list.contains", item=item) + ) + + def get(self, index: int) -> ExprT: + """Return the value by index in each list. + + Negative indices are not accepted. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [[1, 2], [3, 4, None], [None, 5]]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_first=nw.col("a").list.get(0)) + ┌──────────────────────────┐ + | Narwhals DataFrame | + |--------------------------| + |shape: (3, 2) | + |┌──────────────┬─────────┐| + |│ a ┆ a_first │| + |│ --- ┆ --- │| + |│ list[i64] ┆ i64 │| + |╞══════════════╪═════════╡| + |│ [1, 2] ┆ 1 │| + |│ [3, 4, null] ┆ 3 │| + |│ [null, 5] ┆ null │| + |└──────────────┴─────────┘| + └──────────────────────────┘ + """ + if not isinstance(index, int): + msg = ( + f"Index must be of type 'int'. Got type '{type(index).__name__}' instead." + ) + raise TypeError(msg) + + if index < 0: + msg = f"Index {index} is out of bounds: should be greater than or equal to 0." + raise ValueError(msg) + + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "list.get", index=index) + ) + + def min(self) -> ExprT: + """Compute the min value of the lists in the array. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql("SELECT * FROM VALUES ([1]), ([3, 4, NULL]) df(a)") + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_min=nw.col("a").list.min()) + ┌────────────────────────┐ + | Narwhals LazyFrame | + |------------------------| + |┌──────────────┬───────┐| + |│ a │ a_min │| + |│ int32[] │ int32 │| + |├──────────────┼───────┤| + |│ [1] │ 1 │| + |│ [3, 4, NULL] │ 3 │| + |└──────────────┴───────┘| + └────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.min")) + + def max(self) -> ExprT: + """Compute the max value of the lists in the array. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [[1], [3, 4, None]]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_max=nw.col("a").list.max()) + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + |shape: (2, 2) | + |┌──────────────┬───────┐| + |│ a ┆ a_max │| + |│ --- ┆ --- │| + |│ list[i64] ┆ i64 │| + |╞══════════════╪═══════╡| + |│ [1] ┆ 1 │| + |│ [3, 4, null] ┆ 4 │| + |└──────────────┴───────┘| + └────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.max")) + + def mean(self) -> ExprT: + """Compute the mean value of the lists in the array. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": [[1], [3, 4, None]]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_mean=nw.col("a").list.mean()) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + |pyarrow.Table | + |a: list | + | child 0, item: int64| + |a_mean: double | + |---- | + |a: [[[1],[3,4,null]]] | + |a_mean: [[1,3.5]] | + └──────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.mean")) + + def median(self) -> ExprT: + """Compute the median value of the lists in the array. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql("SELECT * FROM VALUES ([1]), ([3, 4, NULL]) df(a)") + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_median=nw.col("a").list.median()) + ┌───────────────────────────┐ + | Narwhals LazyFrame | + |---------------------------| + |┌──────────────┬──────────┐| + |│ a │ a_median │| + |│ int32[] │ double │| + |├──────────────┼──────────┤| + |│ [1] │ 1.0 │| + |│ [3, 4, NULL] │ 3.5 │| + |└──────────────┴──────────┘| + └───────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.median")) + + def sum(self) -> ExprT: + """Compute the sum value of the lists in the array. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [[1], [3, 4, None]]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_sum=nw.col("a").list.sum()) + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + |shape: (2, 2) | + |┌──────────────┬───────┐| + |│ a ┆ a_sum │| + |│ --- ┆ --- │| + |│ list[i64] ┆ i64 │| + |╞══════════════╪═══════╡| + |│ [1] ┆ 1 │| + |│ [3, 4, null] ┆ 7 │| + |└──────────────┴───────┘| + └────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.sum")) + + def sort(self, *, descending: bool = False, nulls_last: bool = False) -> ExprT: + """Sort the lists of the expression. + + Arguments: + descending: Sort in descending order. + nulls_last: Place null values last. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> df_native = duckdb.sql( + ... "SELECT * FROM VALUES ([2, -1, 1]), ([3, -4, NULL]) df(a)" + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(a_sorted=nw.col("a").list.sort()) + ┌─────────────────────────────────┐ + | Narwhals LazyFrame | + |---------------------------------| + |┌───────────────┬───────────────┐| + |│ a │ a_sorted │| + |│ int32[] │ int32[] │| + |├───────────────┼───────────────┤| + |│ [2, -1, 1] │ [-1, 1, 2] │| + |│ [3, -4, NULL] │ [NULL, -4, 3] │| + |└───────────────┴───────────────┘| + └─────────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "list.sort", + descending=descending, + nulls_last=nulls_last, + ) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_name.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_name.py new file mode 100644 index 0000000000000000000000000000000000000000..64525aae5636ce1702515adfdac648154ecc5364 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_name.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode + +if TYPE_CHECKING: + from narwhals.expr import Expr + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprNameNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def keep(self) -> ExprT: + r"""Keep the original root name of the expression. + + Notes: + For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, 2], "BAR": [4, 5]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("foo").alias("alias_for_foo").name.keep()).columns + ['foo'] + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "name.keep")) + + def map(self, function: Callable[[str], str]) -> ExprT: + r"""Rename the output of an expression by mapping a function over the root name. + + Arguments: + function: Function that maps a root name to a new name. + + Notes: + For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": [1, 2], "BAR": [4, 5]}) + >>> df = nw.from_native(df_native) + >>> renaming_func = lambda s: s[::-1] # reverse column name + >>> df.select(nw.col("foo", "BAR").name.map(renaming_func)).columns + ['oof', 'RAB'] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "name.map", function=function) + ) + + def prefix(self, prefix: str) -> ExprT: + r"""Add a prefix to the root column name of the expression. + + Arguments: + prefix: Prefix to add to the root column name. + + Notes: + For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"foo": [1, 2], "BAR": [4, 5]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("foo", "BAR").name.prefix("with_prefix")).columns + ['with_prefixfoo', 'with_prefixBAR'] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "name.prefix", prefix=prefix) + ) + + def suffix(self, suffix: str) -> ExprT: + r"""Add a suffix to the root column name of the expression. + + Arguments: + suffix: Suffix to add to the root column name. + + Notes: + For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"foo": [1, 2], "BAR": [4, 5]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("foo", "BAR").name.suffix("_with_suffix")).columns + ['foo_with_suffix', 'BAR_with_suffix'] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "name.suffix", suffix=suffix) + ) + + def to_lowercase(self) -> ExprT: + r"""Make the root column name lowercase. + + Notes: + For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "BAR": [4, 5]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("foo", "BAR").name.to_lowercase()).columns + ['foo', 'bar'] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "name.to_lowercase") + ) + + def to_uppercase(self) -> ExprT: + r"""Make the root column name uppercase. + + Notes: + For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"foo": [1, 2], "BAR": [4, 5]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("foo", "BAR").name.to_uppercase()).columns + ['FOO', 'BAR'] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "name.to_uppercase") + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_str.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_str.py new file mode 100644 index 0000000000000000000000000000000000000000..2dcfccac83037d156c0ae3b2b2fa0f9709d2f5f5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_str.py @@ -0,0 +1,579 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode + +if TYPE_CHECKING: + from narwhals.expr import Expr + from narwhals.typing import IntoExpr + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprStringNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def len_chars(self) -> ExprT: + r"""Return the length of each string as the number of characters. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"words": ["foo", "345", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(words_len=nw.col("words").str.len_chars()) + ┌─────────────────────┐ + | Narwhals DataFrame | + |---------------------| + |shape: (3, 2) | + |┌───────┬───────────┐| + |│ words ┆ words_len │| + |│ --- ┆ --- │| + |│ str ┆ u32 │| + |╞═══════╪═══════════╡| + |│ foo ┆ 3 │| + |│ 345 ┆ 3 │| + |│ null ┆ null │| + |└───────┴───────────┘| + └─────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.len_chars")) + + def replace( + self, pattern: str, value: str | IntoExpr, *, literal: bool = False, n: int = 1 + ) -> ExprT: + r"""Replace first matching regex/literal substring with a new string value. + + Arguments: + pattern: A valid regular expression pattern. + value: String that will replace the matched substring. + literal: Treat `pattern` as a literal string. + n: Number of matches to replace. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": ["123abc", "abc abc123"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(replaced=nw.col("foo").str.replace("abc", "")) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + | foo replaced| + |0 123abc 123| + |1 abc abc123 abc123| + └──────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "str.replace", + exprs=(value,), + pattern=pattern, + literal=literal, + n=n, + str_as_lit=True, + ) + ) + + def replace_all( + self, pattern: str, value: IntoExpr, *, literal: bool = False + ) -> ExprT: + r"""Replace all matching regex/literal substring with a new string value. + + Arguments: + pattern: A valid regular expression pattern. + value: String that will replace the matched substring. + literal: Treat `pattern` as a literal string. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"foo": ["123abc", "abc abc123"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(replaced=nw.col("foo").str.replace_all("abc", "")) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + | foo replaced| + |0 123abc 123| + |1 abc abc123 123| + └──────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "str.replace_all", + exprs=(value,), + pattern=pattern, + literal=literal, + str_as_lit=True, + ) + ) + + def strip_chars(self, characters: str | None = None) -> ExprT: + r"""Remove leading and trailing characters. + + Arguments: + characters: The set of characters to be removed. All combinations of this + set of characters will be stripped from the start and end of the string. + If set to None (default), all leading and trailing whitespace is removed + instead. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"fruits": ["apple", "\nmango"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(stripped=nw.col("fruits").str.strip_chars()).to_dict( + ... as_series=False + ... ) + {'fruits': ['apple', '\nmango'], 'stripped': ['apple', 'mango']} + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.strip_chars", characters=characters) + ) + + def starts_with(self, prefix: str) -> ExprT: + r"""Check if string values start with a substring. + + Arguments: + prefix: prefix substring + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["apple", "mango", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(has_prefix=nw.col("fruits").str.starts_with("app")) + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + | fruits has_prefix| + |0 apple True| + |1 mango False| + |2 NaN False| + └────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.starts_with", prefix=prefix) + ) + + def ends_with(self, suffix: str) -> ExprT: + r"""Check if string values end with a substring. + + Arguments: + suffix: suffix substring + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["apple", "mango", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(has_suffix=nw.col("fruits").str.ends_with("ngo")) + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + | fruits has_suffix| + |0 apple False| + |1 mango True| + |2 NaN False| + └────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.ends_with", suffix=suffix) + ) + + def contains(self, pattern: str | IntoExpr, *, literal: bool = False) -> ExprT: + r"""Check if string contains a substring that matches a pattern. + + Arguments: + pattern: A Character sequence, valid regular expression pattern, or another + Expr. + literal: If True, treats the pattern as a literal string. + If False, assumes the pattern is a regular expression. + + Warning: + Passing an expression as `pattern` is only supported by DuckDB, Ibis, Polars, + PySpark and SQLFrame. Other backends, such as pandas and PyArrow, will raise + a `TypeError`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"pets": ["cat", "dog", "rabbit and parrot"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns( + ... default_match=nw.col("pets").str.contains("cat|parrot"), + ... case_insensitive_match=nw.col("pets").str.contains("cat|(?i)parrot"), + ... ).to_native() + pyarrow.Table + pets: string + default_match: bool + case_insensitive_match: bool + ---- + pets: [["cat","dog","rabbit and parrot"]] + default_match: [[true,false,true]] + case_insensitive_match: [[true,false,true]] + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "str.contains", + exprs=(pattern,), + literal=literal, + str_as_lit=True, + ) + ) + + def slice(self, offset: int, length: int | None = None) -> ExprT: + r"""Create subslices of the string values of an expression. + + Arguments: + offset: Start index. Negative indexing is supported. + length: Length of the slice. If set to `None` (default), the slice is taken to the + end of the string. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"s": ["pear", None, "papaya"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(s_sliced=nw.col("s").str.slice(4, length=3)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | s s_sliced| + |0 pear | + |1 NaN NaN| + |2 papaya ya| + └──────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=offset, length=length) + ) + + def split(self, by: str) -> ExprT: + r"""Split the string values of an expression by a substring. + + Arguments: + by: Substring to split by. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"s": ["foo bar", "foo_bar"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(nw.col("s").str.split("_").alias("s_split")) + ┌────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------| + |shape: (2, 2) | + |┌─────────┬────────────────┐| + |│ s ┆ s_split │| + |│ --- ┆ --- │| + |│ str ┆ list[str] │| + |╞═════════╪════════════════╡| + |│ foo bar ┆ ["foo bar"] │| + |│ foo_bar ┆ ["foo", "bar"] │| + |└─────────┴────────────────┘| + └────────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.split", by=by)) + + def head(self, n: int = 5) -> ExprT: + r"""Take the first n elements of each string. + + Arguments: + n: Number of elements to take. Negative indexing is **not** supported. + + Notes: + If the length of the string has fewer than `n` characters, the full string is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"lyrics": ["taata", "taatatata", "zukkyun"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(lyrics_head=nw.col("lyrics").str.head()).to_native() + pyarrow.Table + lyrics: string + lyrics_head: string + ---- + lyrics: [["taata","taatatata","zukkyun"]] + lyrics_head: [["taata","taata","zukky"]] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=0, length=n) + ) + + def tail(self, n: int = 5) -> ExprT: + r"""Take the last n elements of each string. + + Arguments: + n: Number of elements to take. Negative indexing is **not** supported. + + Notes: + If the length of the string has fewer than `n` characters, the full string is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"lyrics": ["taata", "taatatata", "zukkyun"]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(lyrics_tail=nw.col("lyrics").str.tail()).to_native() + pyarrow.Table + lyrics: string + lyrics_tail: string + ---- + lyrics: [["taata","taatatata","zukkyun"]] + lyrics_tail: [["taata","atata","kkyun"]] + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=-n, length=None) + ) + + def to_datetime(self, format: str | None = None) -> ExprT: + """Convert to Datetime dtype. + + Notes: + - pandas defaults to nanosecond time unit, Polars to microsecond. + Prior to pandas 2.0, nanoseconds were the only time unit supported + in pandas, with no ability to set any other one. The ability to + set the time unit in pandas, if the version permits, will arrive. + - timezone-aware strings are all converted to and parsed as UTC. + + Warning: + As different backends auto-infer format in different ways, if `format=None` + there is no guarantee that the result will be equal. + + Arguments: + format: Format to use for conversion. If set to None (default), the format is + inferred from the data. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": ["2020-01-01", "2020-01-02"]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").str.to_datetime(format="%Y-%m-%d")) + ┌───────────────────────┐ + | Narwhals DataFrame | + |-----------------------| + |shape: (2, 1) | + |┌─────────────────────┐| + |│ a │| + |│ --- │| + |│ datetime[μs] │| + |╞═════════════════════╡| + |│ 2020-01-01 00:00:00 │| + |│ 2020-01-02 00:00:00 │| + |└─────────────────────┘| + └───────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.to_datetime", format=format) + ) + + def to_date(self, format: str | None = None) -> ExprT: + """Convert to date dtype. + + Warning: + As different backends auto-infer format in different ways, if `format=None` + there is no guarantee that the result will be equal. + + Arguments: + format: Format to use for conversion. If set to None (default), the format is inferred from the data. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> df_native = pa.table({"a": ["2020-01-01", "2020-01-02"]}) + >>> df = nw.from_native(df_native) + >>> df.select(nw.col("a").str.to_date(format="%Y-%m-%d")) + ┌────────────────────────────┐ + | Narwhals DataFrame | + |----------------------------| + |pyarrow.Table | + |a: date32[day] | + |---- | + |a: [[2020-01-01,2020-01-02]]| + └────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.to_date", format=format) + ) + + def to_uppercase(self) -> ExprT: + r"""Transform string to uppercase variant. + + Notes: + The PyArrow backend will convert 'ß' to 'ẞ' instead of 'SS'. + For more info see [the related issue](https://github.com/apache/arrow/issues/34599). + There may be other unicode-edge-case-related variations across implementations. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["apple", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(upper_col=nw.col("fruits").str.to_uppercase()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | fruits upper_col| + |0 apple APPLE| + |1 NaN NaN| + └──────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_uppercase")) + + def to_lowercase(self) -> ExprT: + r"""Transform string to lowercase variant. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"fruits": ["APPLE", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(lower_col=nw.col("fruits").str.to_lowercase()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | fruits lower_col| + |0 APPLE apple| + |1 NaN NaN| + └──────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_lowercase")) + + def to_titlecase(self) -> ExprT: + """Modify strings to their titlecase equivalent. + + Notes: + This is a form of case transform where the first letter of each word is + capitalized, with the rest of the word in lowercase. + + Word boundaries are defined by non-**alphabetic** characters, matching the + behavior of [`str.title`](https://docs.python.org/3/library/stdtypes.html#str.title) + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... { + ... "quotes": [ + ... "'e.t. phone home'", + ... "you talkin' to me?", + ... "to infinity,and BEYOND!", + ... ] + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(quotes_title=nw.col("quotes").str.to_titlecase()) + ┌─────────────────────────────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------------------------------| + |shape: (3, 2) | + |┌─────────────────────────┬─────────────────────────┐| + |│ quotes ┆ quotes_title │| + |│ --- ┆ --- │| + |│ str ┆ str │| + |╞═════════════════════════╪═════════════════════════╡| + |│ 'e.t. phone home' ┆ 'E.T. Phone Home' │| + |│ you talkin' to me? ┆ You Talkin' To Me? │| + |│ to infinity,and BEYOND! ┆ To Infinity,And Beyond! │| + |└─────────────────────────┴─────────────────────────┘| + └─────────────────────────────────────────────────────┘ + """ + return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_titlecase")) + + def zfill(self, width: int) -> ExprT: + """Transform string to zero-padded variant. + + Arguments: + width: The desired length of the string after padding. If the length of the + string is greater than `width`, no padding is applied. + If `width` is less than 0, no padding is applied. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"digits": ["+1", "-1", "1", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(zfill_col=nw.col("digits").str.zfill(3)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | digits zfill_col| + |0 +1 +01| + |1 -1 -01| + |2 1 001| + |3 NaN NaN| + └──────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "str.zfill", width=width) + ) + + def pad_start(self, length: int, fill_char: str = " ") -> ExprT: + """Pad the start of the string until it reaches the given length. + + Arguments: + length: Pad the string until it reaches this length. Strings with + length equal to or greater than this value are returned as-is. + fill_char: The character to pad the string with. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(padded=nw.col("a").str.pad_start(8, "*")) + ┌─────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------| + | a padded| + |0 cow *****cow| + |1 monkey **monkey| + |2 hippopotamus hippopotamus| + |3 NaN NaN| + └─────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, "str.pad_start", length=length, fill_char=fill_char + ) + ) + + def pad_end(self, length: int, fill_char: str = " ") -> ExprT: + """Pad the end of the string until it reaches the given length. + + Arguments: + length: Pad the string until it reaches this length. Strings with + length equal to or greater than this value are returned as-is. + fill_char: The character to pad the string with. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]}) + >>> df = nw.from_native(df_native) + >>> df.with_columns(padded=nw.col("a").str.pad_end(8, "*")) + ┌─────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------| + | a padded| + |0 cow cow*****| + |1 monkey monkey**| + |2 hippopotamus hippopotamus| + |3 NaN NaN| + └─────────────────────────────┘ + """ + return self._expr._append_node( + ExprNode( + ExprKind.ELEMENTWISE, "str.pad_end", length=length, fill_char=fill_char + ) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_struct.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_struct.py new file mode 100644 index 0000000000000000000000000000000000000000..7d734732f9629ba3d2d91b63e24258fc5aba53d6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/expr_struct.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, TypeVar + +from narwhals._expression_parsing import ExprKind, ExprNode + +if TYPE_CHECKING: + from narwhals.expr import Expr + +ExprT = TypeVar("ExprT", bound="Expr") + + +class ExprStructNamespace(Generic[ExprT]): + def __init__(self, expr: ExprT) -> None: + self._expr = expr + + def field(self, name: str) -> ExprT: + r"""Retrieve a Struct field as a new expression. + + Arguments: + name: Name of the struct field to retrieve. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame( + ... {"user": [{"id": "0", "name": "john"}, {"id": "1", "name": "jane"}]} + ... ) + >>> df = nw.from_native(df_native) + >>> df.with_columns(name=nw.col("user").struct.field("name")) + ┌───────────────────────┐ + | Narwhals DataFrame | + |-----------------------| + |shape: (2, 2) | + |┌──────────────┬──────┐| + |│ user ┆ name │| + |│ --- ┆ --- │| + |│ struct[2] ┆ str │| + |╞══════════════╪══════╡| + |│ {"0","john"} ┆ john │| + |│ {"1","jane"} ┆ jane │| + |└──────────────┴──────┘| + └───────────────────────┘ + """ + return self._expr._append_node( + ExprNode(ExprKind.ELEMENTWISE, "struct.field", name=name) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/functions.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..f8420eb54d3674f916274e521dd8f09827542a55 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/functions.py @@ -0,0 +1,1829 @@ +from __future__ import annotations + +import platform +import sys +from collections.abc import Iterable, Mapping, Sequence +from typing import TYPE_CHECKING, Any + +from narwhals._expression_parsing import ExprKind, ExprNode, is_expr, is_series +from narwhals._utils import ( + Implementation, + Version, + deprecate_native_namespace, + flatten, + is_eager_allowed, + is_nested_literal, + is_sequence_but_not_str, + normalize_path, + supports_arrow_c_stream, + validate_laziness, +) +from narwhals.dependencies import ( + is_narwhals_series, + is_numpy_array, + is_numpy_array_2d, + is_pyarrow_table, +) +from narwhals.exceptions import InvalidOperationError +from narwhals.expr import Expr +from narwhals.translate import from_native, to_native + +if TYPE_CHECKING: + from types import ModuleType + + from typing_extensions import TypeAlias, TypeIs + + from narwhals._native import NativeDataFrame, NativeLazyFrame, NativeSeries + from narwhals._translate import IntoArrowTable + from narwhals._typing import Backend, EagerAllowed, IntoBackend + from narwhals.dataframe import DataFrame, LazyFrame + from narwhals.dtypes import DType + from narwhals.series import Series + from narwhals.typing import ( + ConcatMethod, + CorrelationMethod, + FileSource, + FrameT, + IntoDType, + IntoExpr, + IntoSchema, + NonNestedLiteral, + PythonLiteral, + _2DArray, + ) + + _IntoSchema: TypeAlias = "IntoSchema | Sequence[str] | None" + + +def concat(items: Iterable[FrameT], *, how: ConcatMethod = "vertical") -> FrameT: + """Concatenate multiple DataFrames, LazyFrames into a single entity. + + Arguments: + items: DataFrames, LazyFrames to concatenate. + how: concatenating strategy + + - vertical: Concatenate vertically. Column names must match. + - horizontal: Concatenate horizontally. If lengths don't match, then + missing rows are filled with null values. This is only supported + when all inputs are (eager) DataFrames. + - diagonal: Finds a union between the column schemas and fills missing column + values with null. + + Raises: + TypeError: The items to concatenate should either all be eager, or all lazy + + Examples: + Let's take an example of vertical concatenation: + + >>> import pandas as pd + >>> import polars as pl + >>> import pyarrow as pa + >>> import narwhals as nw + + Let's look at one case a for vertical concatenation (pandas backed): + + >>> df_pd_1 = nw.from_native(pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})) + >>> df_pd_2 = nw.from_native(pd.DataFrame({"a": [5, 2], "b": [1, 4]})) + >>> nw.concat([df_pd_1, df_pd_2], how="vertical") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 4 | + | 1 2 5 | + | 2 3 6 | + | 0 5 1 | + | 1 2 4 | + └──────────────────┘ + + Let's look at one case a for horizontal concatenation (polars backed): + + >>> df_pl_1 = nw.from_native(pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})) + >>> df_pl_2 = nw.from_native(pl.DataFrame({"c": [5, 2], "d": [1, 4]})) + >>> nw.concat([df_pl_1, df_pl_2], how="horizontal") + ┌───────────────────────────┐ + | Narwhals DataFrame | + |---------------------------| + |shape: (3, 4) | + |┌─────┬─────┬──────┬──────┐| + |│ a ┆ b ┆ c ┆ d │| + |│ --- ┆ --- ┆ --- ┆ --- │| + |│ i64 ┆ i64 ┆ i64 ┆ i64 │| + |╞═════╪═════╪══════╪══════╡| + |│ 1 ┆ 4 ┆ 5 ┆ 1 │| + |│ 2 ┆ 5 ┆ 2 ┆ 4 │| + |│ 3 ┆ 6 ┆ null ┆ null │| + |└─────┴─────┴──────┴──────┘| + └───────────────────────────┘ + + Let's look at one case a for diagonal concatenation (pyarrow backed): + + >>> df_pa_1 = nw.from_native(pa.table({"a": [1, 2], "b": [3.5, 4.5]})) + >>> df_pa_2 = nw.from_native(pa.table({"a": [3, 4], "z": ["x", "y"]})) + >>> nw.concat([df_pa_1, df_pa_2], how="diagonal") + ┌──────────────────────────┐ + | Narwhals DataFrame | + |--------------------------| + |pyarrow.Table | + |a: int64 | + |b: double | + |z: string | + |---- | + |a: [[1,2],[3,4]] | + |b: [[3.5,4.5],[null,null]]| + |z: [[null,null],["x","y"]]| + └──────────────────────────┘ + """ + from narwhals.dependencies import is_narwhals_lazyframe + + if not items: + msg = "No items to concatenate." + raise ValueError(msg) + items = tuple(items) + validate_laziness(items) + if how not in {"horizontal", "vertical", "diagonal"}: # pragma: no cover + msg = "Only vertical, horizontal and diagonal concatenations are supported." + raise NotImplementedError(msg) + first_item = items[0] + if is_narwhals_lazyframe(first_item) and how == "horizontal": + msg = ( + "Horizontal concatenation is not supported for LazyFrames.\n\n" + "Hint: you may want to use `join` instead." + ) + raise InvalidOperationError(msg) + plx = first_item.__narwhals_namespace__() + return first_item._with_compliant( + plx.concat([df._compliant_frame for df in items], how=how) + ) + + +def new_series( + name: str, + values: Any, + dtype: IntoDType | None = None, + *, + backend: IntoBackend[EagerAllowed], +) -> Series[Any]: + """Instantiate Narwhals Series from iterable (e.g. list or array). + + Arguments: + name: Name of resulting Series. + values: Values of make Series from. + dtype: (Narwhals) dtype. If not provided, the native library + may auto-infer it from `values`. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> values = [4, 1, 2, 3] + >>> nw.new_series(name="a", values=values, dtype=nw.Int32, backend=pd) + ┌─────────────────────┐ + | Narwhals Series | + |---------------------| + |0 4 | + |1 1 | + |2 2 | + |3 3 | + |Name: a, dtype: int32| + └─────────────────────┘ + """ + return _new_series_impl(name, values, dtype, backend=backend) + + +def _new_series_impl( + name: str, + values: Any, + dtype: IntoDType | None = None, + *, + backend: IntoBackend[EagerAllowed], +) -> Series[Any]: + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = Version.MAIN.namespace.from_backend(implementation).compliant + series = ns._series.from_iterable(values, name=name, context=ns, dtype=dtype) + return series.to_narwhals() + if implementation is Implementation.UNKNOWN: # pragma: no cover + _native_namespace = implementation.to_native_namespace() + try: + native_series: NativeSeries = _native_namespace.new_series( + name, values, dtype + ) + return from_native(native_series, series_only=True).alias(name) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `new_series` constructor." + raise AttributeError(msg) from e + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `new_series` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.new_series('a', [1,2,3], backend='pyarrow').to_frame().lazy('{implementation}')" + ) + raise ValueError(msg) + + +@deprecate_native_namespace(warn_version="1.26.0") +def from_dict( + data: Mapping[str, Any], + schema: IntoSchema | Mapping[str, DType | None] | None = None, + *, + backend: IntoBackend[EagerAllowed] | None = None, + native_namespace: ModuleType | None = None, # noqa: ARG001 +) -> DataFrame[Any]: + """Instantiate DataFrame from dictionary. + + Indexes (if present, for pandas-like backends) are aligned following + the [left-hand-rule](../concepts/pandas_index.md/). + + Notes: + For pandas-like dataframes, conversion to schema is applied after dataframe + creation. + + Arguments: + data: Dictionary to create DataFrame from. + schema: The DataFrame schema as Schema or dict of {name: type}. If not + specified, the schema will be inferred by the native library. If + any `dtype` is `None`, the data type for that column will be inferred + by the native library. + backend: specifies which eager backend instantiate to. Only + necessary if inputs are not Narwhals Series. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + native_namespace: deprecated, same as `backend`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> data = {"c": [5, 2], "d": [1, 4]} + >>> nw.from_dict(data, backend="pandas") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | c d | + | 0 5 1 | + | 1 2 4 | + └──────────────────┘ + """ + if backend is None: + data, backend = _from_dict_no_backend(data) + if schema and data and (diff := set(schema.keys()).symmetric_difference(data.keys())): + msg = f"Keys in `schema` and `data` are expected to match, found unmatched keys: {diff}" + raise InvalidOperationError(msg) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = Version.MAIN.namespace.from_backend(implementation).compliant + return ns._dataframe.from_dict(data, schema=schema, context=ns).to_narwhals() + if implementation is Implementation.UNKNOWN: # pragma: no cover + _native_namespace = implementation.to_native_namespace() + try: + # implementation is UNKNOWN, Narwhals extension using this feature should + # implement `from_dict` function in the top-level namespace. + native_frame: NativeDataFrame = _native_namespace.from_dict( + data, schema=schema + ) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `from_dict` function." + raise AttributeError(msg) from e + return from_native(native_frame, eager_only=True) + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `from_dict` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.from_dict({{'a': [1, 2]}}, backend='pyarrow').lazy('{implementation}')" + ) + raise ValueError(msg) + + +def _from_dict_no_backend( + data: Mapping[str, Series[Any] | Any], / +) -> tuple[dict[str, Series[Any] | Any], ModuleType]: + for val in data.values(): + if is_narwhals_series(val): + native_namespace = val.__native_namespace__() + break + else: + msg = "Calling `from_dict` without `backend` is only supported if all input values are already Narwhals Series" + raise TypeError(msg) + data = {key: to_native(value, pass_through=True) for key, value in data.items()} + return data, native_namespace + + +def from_dicts( + data: Sequence[Mapping[str, Any]], + schema: IntoSchema | Mapping[str, DType | None] | None = None, + *, + backend: IntoBackend[EagerAllowed], +) -> DataFrame[Any]: + """Instantiate DataFrame from a sequence of dictionaries representing rows. + + Notes: + For pandas-like dataframes, conversion to schema is applied after dataframe + creation. + + Arguments: + data: Sequence with dictionaries mapping column name to value. + schema: The DataFrame schema as Schema or dict of {name: type}. If not + specified, the schema will be inferred by the native library. If + any `dtype` is `None`, the data type for that column will be inferred + by the native library. + backend: Specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Tip: + If you expect non-uniform keys in `data`, consider passing `schema` for + more consistent results, as **inference varies between backends**: + + - pandas uses all rows + - polars uses the first 100 rows + - pyarrow uses only the first row + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> data = [ + ... {"item": "apple", "weight": 80, "price": 0.60}, + ... {"item": "egg", "weight": 55, "price": 0.40}, + ... ] + >>> nw.DataFrame.from_dicts(data, backend="polars") + ┌──────────────────────────┐ + | Narwhals DataFrame | + |--------------------------| + |shape: (2, 3) | + |┌───────┬────────┬───────┐| + |│ item ┆ weight ┆ price │| + |│ --- ┆ --- ┆ --- │| + |│ str ┆ i64 ┆ f64 │| + |╞═══════╪════════╪═══════╡| + |│ apple ┆ 80 ┆ 0.6 │| + |│ egg ┆ 55 ┆ 0.4 │| + |└───────┴────────┴───────┘| + └──────────────────────────┘ + """ + return Version.MAIN.dataframe.from_dicts(data, schema, backend=backend) + + +def from_numpy( + data: _2DArray, + schema: IntoSchema | Sequence[str] | None = None, + *, + backend: IntoBackend[EagerAllowed], +) -> DataFrame[Any]: + """Construct a DataFrame from a NumPy ndarray. + + Notes: + Only row orientation is currently supported. + + For pandas-like dataframes, conversion to schema is applied after dataframe + creation. + + Arguments: + data: Two-dimensional data represented as a NumPy ndarray. + schema: The DataFrame schema as Schema, dict of {name: type}, or a sequence of str. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import numpy as np + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> arr = np.array([[5, 2, 1], [1, 4, 3]]) + >>> schema = {"c": nw.Int16(), "d": nw.Float32(), "e": nw.Int8()} + >>> nw.from_numpy(arr, schema=schema, backend="pyarrow") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | c: int16 | + | d: float | + | e: int8 | + | ---- | + | c: [[5,1]] | + | d: [[2,4]] | + | e: [[1,3]] | + └──────────────────┘ + """ + if not is_numpy_array_2d(data): + msg = "`from_numpy` only accepts 2D numpy arrays" + raise ValueError(msg) + if not _is_into_schema(schema): + msg = ( + "`schema` is expected to be one of the following types: " + "IntoSchema | Sequence[str]. " + f"Got {type(schema)}." + ) + raise TypeError(msg) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = Version.MAIN.namespace.from_backend(implementation).compliant + return ns.from_numpy(data, schema).to_narwhals() + if implementation is Implementation.UNKNOWN: # pragma: no cover + _native_namespace = implementation.to_native_namespace() + try: + # implementation is UNKNOWN, Narwhals extension using this feature should + # implement `from_numpy` function in the top-level namespace. + native_frame: NativeDataFrame = _native_namespace.from_numpy( + data, schema=schema + ) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `from_numpy` function." + raise AttributeError(msg) from e + return from_native(native_frame, eager_only=True) + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `from_numpy` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.from_numpy(arr, backend='pyarrow').lazy('{implementation}')" + ) + raise ValueError(msg) + + +def _is_into_schema(obj: Any) -> TypeIs[_IntoSchema]: + from narwhals.schema import Schema + + return ( + obj is None or isinstance(obj, (Mapping, Schema)) or is_sequence_but_not_str(obj) + ) + + +def from_arrow( + native_frame: IntoArrowTable, *, backend: IntoBackend[EagerAllowed] +) -> DataFrame[Any]: # pragma: no cover + """Construct a DataFrame from an object which supports the PyCapsule Interface. + + Arguments: + native_frame: Object which implements `__arrow_c_stream__`. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [4.2, 5.1]}) + >>> nw.from_arrow(df_native, backend="polars") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (2, 2) | + | ┌─────┬─────┐ | + | │ a ┆ b │ | + | │ --- ┆ --- │ | + | │ i64 ┆ f64 │ | + | ╞═════╪═════╡ | + | │ 1 ┆ 4.2 │ | + | │ 2 ┆ 5.1 │ | + | └─────┴─────┘ | + └──────────────────┘ + """ + if not (supports_arrow_c_stream(native_frame) or is_pyarrow_table(native_frame)): + msg = f"Given object of type {type(native_frame)} does not support PyCapsule interface" + raise TypeError(msg) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = Version.MAIN.namespace.from_backend(implementation).compliant + return ns._dataframe.from_arrow(native_frame, context=ns).to_narwhals() + if implementation is Implementation.UNKNOWN: # pragma: no cover + _native_namespace = implementation.to_native_namespace() + try: + # implementation is UNKNOWN, Narwhals extension using this feature should + # implement PyCapsule support + native: NativeDataFrame = _native_namespace.DataFrame(native_frame) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `DataFrame` class which accepts object which supports PyCapsule Interface." + raise AttributeError(msg) from e + return from_native(native, eager_only=True) + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `from_arrow` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.from_arrow(df, backend='pyarrow').lazy('{implementation}')" + ) + raise ValueError(msg) + + +def _get_sys_info() -> dict[str, str]: + """System information. + + Returns system and Python version information + + Copied from sklearn + + Returns: + Dictionary with system info. + """ + python = sys.version.replace("\n", " ") + + blob = ( + ("python", python), + ("executable", sys.executable), + ("machine", platform.platform()), + ) + + return dict(blob) + + +def _get_deps_info() -> dict[str, str]: + """Overview of the installed version of main dependencies. + + This function does not import the modules to collect the version numbers + but instead relies on standard Python package metadata. + + Returns version information on relevant Python libraries + + This function and show_versions were copied from sklearn and adapted + + Returns: + Mapping from dependency to version. + """ + from importlib.metadata import distributions + + extra_names = ("narwhals", "numpy") + member_names = Implementation._member_names_ + exclude = {"PYSPARK_CONNECT", "UNKNOWN"} + target_names = tuple( + name.lower() for name in (*extra_names, *member_names) if name not in exclude + ) + result = dict.fromkeys(target_names, "") # Initialize with empty strings + + for dist in distributions(): + dist_name, dist_version = dist.name.lower(), dist.version + + if dist_name in result: # exact match + result[dist_name] = dist_version + else: # prefix match + for target in target_names: + if not result[target] and dist_name.startswith( + target + ): # pragma: no cover + result[target] = dist_version + break + + return result + + +def show_versions() -> None: + """Print useful debugging information. + + Examples: + >>> from narwhals import show_versions + >>> show_versions() # doctest: +SKIP + """ + sys_info = _get_sys_info() + deps_info = _get_deps_info() + + print("\nSystem:") # noqa: T201 + for k, stat in sys_info.items(): + print(f"{k:>10}: {stat}") # noqa: T201 + + print("\nPython dependencies:") # noqa: T201 + for k, stat in deps_info.items(): + print(f"{k:>13}: {stat}") # noqa: T201 + + +def _validate_separators( + separator: str, native_separators: tuple[str, ...], **kwargs: Any +) -> None: + for native_separator in native_separators: + if native_separator in kwargs and kwargs[native_separator] != separator: + msg = ( + f"`separator` and `{native_separator}` do not match: " + f"`separator`={separator} and `{native_separator}`={kwargs[native_separator]}." + ) + raise TypeError(msg) + + +def _validate_separator_pyarrow(separator: str, **kwargs: Any) -> Any: + if "parse_options" in kwargs: + parse_options = kwargs.pop("parse_options") + if parse_options.delimiter != separator: + msg = ( + "`separator` and `parse_options.delimiter` do not match: " + f"`separator`={separator} and `delimiter`={parse_options.delimiter}." + ) + raise TypeError(msg) + return kwargs + from pyarrow import csv # ignore-banned-import + + return {"parse_options": csv.ParseOptions(delimiter=separator)} + + +def read_csv( + source: FileSource, + *, + backend: IntoBackend[EagerAllowed], + separator: str = ",", + **kwargs: Any, +) -> DataFrame[Any]: + """Read a CSV file into a DataFrame. + + Arguments: + source: Path to a file. + backend: The eager backend for DataFrame creation. + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + separator: Single byte character to use as separator in the file. + kwargs: Extra keyword arguments which are passed to the native CSV reader. + For example, you could use + `nw.read_csv('file.csv', backend='pandas', engine='pyarrow')`. + + Examples: + >>> import narwhals as nw + >>> nw.read_csv("file.csv", backend="pandas") # doctest:+SKIP + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 4 | + | 1 2 5 | + └──────────────────┘ + """ + impl = Implementation.from_backend(backend) + native_namespace = impl.to_native_namespace() + native_frame: NativeDataFrame + if impl in {Implementation.PANDAS, Implementation.MODIN, Implementation.CUDF}: + _validate_separators(separator, ("sep",), **kwargs) + native_frame = native_namespace.read_csv( + normalize_path(source), sep=separator, **kwargs + ) + elif impl is Implementation.POLARS: + native_frame = native_namespace.read_csv( + normalize_path(source), separator=separator, **kwargs + ) + elif impl is Implementation.PYARROW: + kwargs = _validate_separator_pyarrow(separator, **kwargs) + from pyarrow import csv # ignore-banned-import + + native_frame = csv.read_csv(source, **kwargs) + elif impl in { + Implementation.PYSPARK, + Implementation.DASK, + Implementation.DUCKDB, + Implementation.IBIS, + Implementation.SQLFRAME, + Implementation.PYSPARK_CONNECT, + }: + msg = ( + f"Expected eager backend, found {impl}.\n\n" + f"Hint: use nw.scan_csv(source={source}, backend={backend})" + ) + raise ValueError(msg) + else: # pragma: no cover + try: + # implementation is UNKNOWN, Narwhals extension using this feature should + # implement `read_csv` function in the top-level namespace. + native_frame = native_namespace.read_csv(source=source, **kwargs) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `read_csv` function." + raise AttributeError(msg) from e + return from_native(native_frame, eager_only=True) + + +def scan_csv( + source: FileSource, + *, + backend: IntoBackend[Backend], + separator: str = ",", + **kwargs: Any, +) -> LazyFrame[Any]: + """Lazily read from a CSV file. + + For the libraries that do not support lazy dataframes, the function reads + a csv file eagerly and then converts the resulting dataframe to a lazyframe. + + Arguments: + source: Path to a file. + backend: The eager backend for DataFrame creation. + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + separator: Single byte character to use as separator in the file. + kwargs: Extra keyword arguments which are passed to the native CSV reader. + For example, you could use + `nw.scan_csv('file.csv', backend=pd, engine='pyarrow')`. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> + >>> nw.scan_csv("file.csv", backend="duckdb").to_native() # doctest:+SKIP + ┌─────────┬───────┐ + │ a │ b │ + │ varchar │ int32 │ + ├─────────┼───────┤ + │ x │ 1 │ + │ y │ 2 │ + │ z │ 3 │ + └─────────┴───────┘ + """ + implementation = Implementation.from_backend(backend) + native_namespace = implementation.to_native_namespace() + native_frame: NativeDataFrame | NativeLazyFrame + source = normalize_path(source) + if implementation is Implementation.POLARS: + native_frame = native_namespace.scan_csv(source, separator=separator, **kwargs) + elif implementation in { + Implementation.PANDAS, + Implementation.MODIN, + Implementation.CUDF, + Implementation.DASK, + Implementation.IBIS, + }: + _validate_separators(separator, ("sep",), **kwargs) + native_frame = native_namespace.read_csv(source, sep=separator, **kwargs) + elif implementation is Implementation.DUCKDB: + _validate_separators(separator, ("delimiter", "delim", "sep"), **kwargs) + native_frame = native_namespace.read_csv(source, delimiter=separator, **kwargs) + elif implementation is Implementation.PYARROW: + kwargs = _validate_separator_pyarrow(separator, **kwargs) + from pyarrow import csv # ignore-banned-import + + native_frame = csv.read_csv(source, **kwargs) + elif implementation.is_spark_like(): + _validate_separators(separator, ("sep", "delimiter"), **kwargs) + if (session := kwargs.pop("session", None)) is None: + msg = "Spark like backends require a session object to be passed in `kwargs`." + raise ValueError(msg) + csv_reader = session.read.format("csv") + native_frame = ( + csv_reader.load(source, sep=separator) + if ( + implementation is Implementation.SQLFRAME + and implementation._backend_version() < (3, 27, 0) + ) + else csv_reader.options(sep=separator, **kwargs).load(source) + ) + else: # pragma: no cover + try: + # implementation is UNKNOWN, Narwhals extension using this feature should + # implement `scan_csv` function in the top-level namespace. + native_frame = native_namespace.scan_csv(source=source, **kwargs) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `scan_csv` function." + raise AttributeError(msg) from e + return from_native(native_frame).lazy() + + +def read_parquet( + source: FileSource, *, backend: IntoBackend[EagerAllowed], **kwargs: Any +) -> DataFrame[Any]: + """Read into a DataFrame from a parquet file. + + Arguments: + source: Path to a file. + backend: The eager backend for DataFrame creation. + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + kwargs: Extra keyword arguments which are passed to the native parquet reader. + For example, you could use + `nw.read_parquet('file.parquet', backend=pd, engine='pyarrow')`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> nw.read_parquet("file.parquet", backend="pyarrow") # doctest:+SKIP + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |pyarrow.Table | + |a: int64 | + |c: double | + |---- | + |a: [[1,2]] | + |c: [[0.2,0.1]] | + └──────────────────┘ + """ + impl = Implementation.from_backend(backend) + native_namespace = impl.to_native_namespace() + native_frame: NativeDataFrame + if impl in { + Implementation.POLARS, + Implementation.PANDAS, + Implementation.MODIN, + Implementation.CUDF, + }: + source = normalize_path(source) + native_frame = native_namespace.read_parquet(source, **kwargs) + elif impl is Implementation.PYARROW: + import pyarrow.parquet as pq # ignore-banned-import + + native_frame = pq.read_table(source, **kwargs) # type: ignore[arg-type] + elif impl in { + Implementation.PYSPARK, + Implementation.DASK, + Implementation.DUCKDB, + Implementation.IBIS, + Implementation.SQLFRAME, + Implementation.PYSPARK_CONNECT, + }: + msg = ( + f"Expected eager backend, found {impl}.\n\n" + f"Hint: use nw.scan_parquet(source={source}, backend={backend})" + ) + raise ValueError(msg) + else: # pragma: no cover + try: + # implementation is UNKNOWN, Narwhals extension using this feature should + # implement `read_parquet` function in the top-level namespace. + native_frame = native_namespace.read_parquet(source=source, **kwargs) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `read_parquet` function." + raise AttributeError(msg) from e + return from_native(native_frame, eager_only=True) + + +def scan_parquet( + source: FileSource, *, backend: IntoBackend[Backend], **kwargs: Any +) -> LazyFrame[Any]: + """Lazily read from a parquet file. + + For the libraries that do not support lazy dataframes, the function reads + a parquet file eagerly and then converts the resulting dataframe to a lazyframe. + + Note: + Spark like backends require a session object to be passed in `kwargs`. + + For instance: + + ```py + import narwhals as nw + from sqlframe.duckdb import DuckDBSession + + nw.scan_parquet(source, backend="sqlframe", session=DuckDBSession()) + ``` + + Arguments: + source: Path to a file. + backend: The eager backend for DataFrame creation. + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN`, `CUDF`, `PYSPARK` or `SQLFRAME`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"`, `"cudf"`, + `"pyspark"` or `"sqlframe"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin`, `cudf`, + `pyspark.sql` or `sqlframe`. + kwargs: Extra keyword arguments which are passed to the native parquet reader. + For example, you could use + `nw.scan_parquet('file.parquet', backend=pd, engine='pyarrow')`. + + Examples: + >>> import dask.dataframe as dd + >>> from sqlframe.duckdb import DuckDBSession + >>> import narwhals as nw + >>> + >>> nw.scan_parquet("file.parquet", backend="dask").collect() # doctest:+SKIP + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 1 4 | + | 1 2 5 | + └──────────────────┘ + >>> nw.scan_parquet( + ... "file.parquet", backend="sqlframe", session=DuckDBSession() + ... ).collect() # doctest:+SKIP + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int64 | + | b: int64 | + | ---- | + | a: [[1,2]] | + | b: [[4,5]] | + └──────────────────┘ + """ + implementation = Implementation.from_backend(backend) + native_namespace = implementation.to_native_namespace() + native_frame: NativeDataFrame | NativeLazyFrame + source = normalize_path(source) + if implementation is Implementation.POLARS: + native_frame = native_namespace.scan_parquet(source, **kwargs) + elif implementation in { + Implementation.PANDAS, + Implementation.MODIN, + Implementation.CUDF, + Implementation.DASK, + Implementation.DUCKDB, + Implementation.IBIS, + }: + native_frame = native_namespace.read_parquet(source, **kwargs) + elif implementation is Implementation.PYARROW: + import pyarrow.parquet as pq # ignore-banned-import + + native_frame = pq.read_table(source, **kwargs) + elif implementation.is_spark_like(): + if (session := kwargs.pop("session", None)) is None: + msg = "Spark like backends require a session object to be passed in `kwargs`." + raise ValueError(msg) + pq_reader = session.read.format("parquet") + native_frame = ( + pq_reader.load(source) + if ( + implementation is Implementation.SQLFRAME + and implementation._backend_version() < (3, 27, 0) + ) + else pq_reader.options(**kwargs).load(source) + ) + + else: # pragma: no cover + try: + # implementation is UNKNOWN, Narwhals extension using this feature should + # implement `scan_parquet` function in the top-level namespace. + native_frame = native_namespace.scan_parquet(source=source, **kwargs) + except AttributeError as e: + msg = "Unknown namespace is expected to implement `scan_parquet` function." + raise AttributeError(msg) from e + return from_native(native_frame).lazy() + + +def col(*names: str | Iterable[str]) -> Expr: + """Creates an expression that references one or more columns by their name(s). + + Arguments: + names: Name(s) of the columns to use. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pl.DataFrame({"a": [1, 2], "b": [3, 4], "c": ["x", "z"]}) + >>> nw.from_native(df_native).select(nw.col("a", "b") * nw.col("b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (2, 2) | + | ┌─────┬─────┐ | + | │ a ┆ b │ | + | │ --- ┆ --- │ | + | │ i64 ┆ i64 │ | + | ╞═════╪═════╡ | + | │ 3 ┆ 9 │ | + | │ 8 ┆ 16 │ | + | └─────┴─────┘ | + └──────────────────┘ + """ + flat_names = flatten(names) + return Expr(ExprNode(ExprKind.COL, "col", names=flat_names)) + + +def exclude(*names: str | Iterable[str]) -> Expr: + """Creates an expression that excludes columns by their name(s). + + Arguments: + names: Name(s) of the columns to exclude. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pl.DataFrame({"a": [1, 2], "b": [3, 4], "c": ["x", "z"]}) + >>> nw.from_native(df_native).select(nw.exclude("c", "a")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (2, 1) | + | ┌─────┐ | + | │ b │ | + | │ --- │ | + | │ i64 │ | + | ╞═════╡ | + | │ 3 │ | + | │ 4 │ | + | └─────┘ | + └──────────────────┘ + """ + return Expr(ExprNode(ExprKind.EXCLUDE, "exclude", names=frozenset(flatten(names)))) + + +def nth(*indices: int | Sequence[int]) -> Expr: + """Creates an expression that references one or more columns by their index(es). + + Notes: + `nth` is not supported for Polars version<1.0.0. Please use + [`narwhals.col`][] instead. + + Arguments: + indices: One or more indices representing the columns to retrieve. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> df_native = pa.table({"a": [1, 2], "b": [3, 4], "c": [0.123, 3.14]}) + >>> nw.from_native(df_native).select(nw.nth(0, 2) * 2) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |pyarrow.Table | + |a: int64 | + |c: double | + |---- | + |a: [[2,4]] | + |c: [[0.246,6.28]] | + └──────────────────┘ + """ + flat_indices = flatten(indices) + return Expr(ExprNode(ExprKind.NTH, "nth", indices=flat_indices)) + + +# Add underscore so it doesn't conflict with builtin `all` +def all_() -> Expr: + """Instantiate an expression representing all columns. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [3.14, 0.123]}) + >>> nw.from_native(df_native).select(nw.all() * 2) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 2 6.280 | + | 1 4 0.246 | + └──────────────────┘ + """ + return Expr(ExprNode(ExprKind.ALL, "all")) + + +# Add underscore so it doesn't conflict with builtin `len` +def len_() -> Expr: + """Return the number of rows. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pl.DataFrame({"a": [1, 2], "b": [5, None]}) + >>> nw.from_native(df_native).select(nw.len()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (1, 1) | + | ┌─────┐ | + | │ len │ | + | │ --- │ | + | │ u32 │ | + | ╞═════╡ | + | │ 2 │ | + | └─────┘ | + └──────────────────┘ + """ + return Expr(ExprNode(ExprKind.AGGREGATION, "len")) + + +def sum(*columns: str) -> Expr: + """Sum all values. + + Note: + Syntactic sugar for ``nw.col(columns).sum()`` + + Arguments: + columns: Name(s) of the columns to use in the aggregation function + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [-1.4, 6.2]}) + >>> nw.from_native(df_native).select(nw.sum("a", "b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 3 4.8 | + └──────────────────┘ + """ + return col(*columns).sum() + + +def mean(*columns: str) -> Expr: + """Get the mean value. + + Note: + Syntactic sugar for ``nw.col(columns).mean()`` + + Arguments: + columns: Name(s) of the columns to use in the aggregation function + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> df_native = pa.table({"a": [1, 8, 3], "b": [3.14, 6.28, 42.1]}) + >>> nw.from_native(df_native).select(nw.mean("a", "b")) + ┌─────────────────────────┐ + | Narwhals DataFrame | + |-------------------------| + |pyarrow.Table | + |a: double | + |b: double | + |---- | + |a: [[4]] | + |b: [[17.173333333333336]]| + └─────────────────────────┘ + """ + return col(*columns).mean() + + +def median(*columns: str) -> Expr: + """Get the median value. + + Notes: + - Syntactic sugar for ``nw.col(columns).median()`` + - Results might slightly differ across backends due to differences in the + underlying algorithms used to compute the median. + + Arguments: + columns: Name(s) of the columns to use in the aggregation function + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pl.DataFrame({"a": [4, 5, 2]}) + >>> nw.from_native(df_native).select(nw.median("a")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (1, 1) | + | ┌─────┐ | + | │ a │ | + | │ --- │ | + | │ f64 │ | + | ╞═════╡ | + | │ 4.0 │ | + | └─────┘ | + └──────────────────┘ + """ + return col(*columns).median() + + +def min(*columns: str) -> Expr: + """Return the minimum value. + + Note: + Syntactic sugar for ``nw.col(columns).min()``. + + Arguments: + columns: Name(s) of the columns to use in the aggregation function. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> df_native = pa.table({"a": [1, 2], "b": [5, 10]}) + >>> nw.from_native(df_native).select(nw.min("a", "b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int64 | + | b: int64 | + | ---- | + | a: [[1]] | + | b: [[5]] | + └──────────────────┘ + """ + return col(*columns).min() + + +def max(*columns: str) -> Expr: + """Return the maximum value. + + Note: + Syntactic sugar for ``nw.col(columns).max()``. + + Arguments: + columns: Name(s) of the columns to use in the aggregation function. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> df_native = pd.DataFrame({"a": [1, 2], "b": [5, 10]}) + >>> nw.from_native(df_native).select(nw.max("a", "b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 2 10 | + └──────────────────┘ + """ + return col(*columns).max() + + +def _expr_with_horizontal_op(name: str, *exprs: IntoExpr, **kwargs: Any) -> Expr: + if not exprs: + msg = f"At least one expression must be passed to `{name}`" + raise ValueError(msg) + return Expr( + ExprNode( + ExprKind.ELEMENTWISE, name, exprs=exprs, **kwargs, allow_multi_output=True + ) + ) + + +def corr(a: IntoExpr, b: IntoExpr, method: CorrelationMethod = "pearson") -> Expr: + """Compute the Pearson's or Spearman rank correlation between two columns. + + Arguments: + a: Column name or Expression + b: Column name or Expression + method: Correlation method ('pearson' or 'spearman') + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pl.DataFrame({"a": [1, 2, 3], "b": [0, 3, 2]}) + >>> nw.from_native(df_native).select( + ... pearson=nw.corr("a", "b", method="pearson"), + ... spearman=nw.corr("a", "b", method="spearman"), + ... ) + ┌───────────────────────┐ + | Narwhals DataFrame | + |-----------------------| + |shape: (1, 2) | + |┌──────────┬──────────┐| + |│ pearson ┆ spearman │| + |│ --- ┆ --- │| + |│ f64 ┆ f64 │| + |╞══════════╪══════════╡| + |│ 0.654654 ┆ 0.5 │| + |└──────────┴──────────┘| + └───────────────────────┘ + """ + return Expr(ExprNode(ExprKind.AGGREGATION, "corr", exprs=(a, b), method=method)) + + +def sum_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr: + """Sum all values horizontally across columns. + + Warning: + Unlike Polars, we support horizontal sum over numeric columns only. + + Arguments: + exprs: Name(s) of the columns to use in the aggregation function. Accepts + expression input. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pl.DataFrame({"a": [1, 2, 3], "b": [5, 10, None]}) + >>> nw.from_native(df_native).with_columns(sum=nw.sum_horizontal("a", "b")) + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + |shape: (3, 3) | + |┌─────┬──────┬─────┐| + |│ a ┆ b ┆ sum │| + |│ --- ┆ --- ┆ --- │| + |│ i64 ┆ i64 ┆ i64 │| + |╞═════╪══════╪═════╡| + |│ 1 ┆ 5 ┆ 6 │| + |│ 2 ┆ 10 ┆ 12 │| + |│ 3 ┆ null ┆ 3 │| + |└─────┴──────┴─────┘| + └────────────────────┘ + """ + return _expr_with_horizontal_op("sum_horizontal", *flatten(exprs)) + + +def min_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr: + """Get the minimum value horizontally across columns. + + Notes: + We support `min_horizontal` over numeric columns only. + + Arguments: + exprs: Name(s) of the columns to use in the aggregation function. Accepts + expression input. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> df_native = pa.table({"a": [1, 8, 3], "b": [4, 5, None]}) + >>> nw.from_native(df_native).with_columns(h_min=nw.min_horizontal("a", "b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int64 | + | b: int64 | + | h_min: int64 | + | ---- | + | a: [[1,8,3]] | + | b: [[4,5,null]] | + | h_min: [[1,5,3]] | + └──────────────────┘ + """ + return _expr_with_horizontal_op("min_horizontal", *flatten(exprs)) + + +def max_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr: + """Get the maximum value horizontally across columns. + + Notes: + We support `max_horizontal` over numeric columns only. + + Arguments: + exprs: Name(s) of the columns to use in the aggregation function. Accepts + expression input. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> df_native = pl.DataFrame({"a": [1, 8, 3], "b": [4, 5, None]}) + >>> nw.from_native(df_native).with_columns(h_max=nw.max_horizontal("a", "b")) + ┌──────────────────────┐ + | Narwhals DataFrame | + |----------------------| + |shape: (3, 3) | + |┌─────┬──────┬───────┐| + |│ a ┆ b ┆ h_max │| + |│ --- ┆ --- ┆ --- │| + |│ i64 ┆ i64 ┆ i64 │| + |╞═════╪══════╪═══════╡| + |│ 1 ┆ 4 ┆ 4 │| + |│ 8 ┆ 5 ┆ 8 │| + |│ 3 ┆ null ┆ 3 │| + |└─────┴──────┴───────┘| + └──────────────────────┘ + """ + return _expr_with_horizontal_op("max_horizontal", *flatten(exprs)) + + +class When: + def __init__(self, *predicates: IntoExpr | Iterable[IntoExpr]) -> None: + self._predicate = all_horizontal(*flatten(predicates), ignore_nulls=False) + + def then(self, value: IntoExpr | NonNestedLiteral) -> Then: + return Then( + ExprNode( + ExprKind.ELEMENTWISE, + "when_then", + exprs=(self._predicate, value), + allow_multi_output=False, + ) + ) + + +class Then(Expr): + def otherwise(self, value: IntoExpr | NonNestedLiteral) -> Expr: + node = self._nodes[0] + return Expr( + ExprNode(ExprKind.ELEMENTWISE, "when_then", exprs=(*node.exprs, value)) + ) + + +def when(*predicates: IntoExpr | Iterable[IntoExpr]) -> When: + """Start a `when-then-otherwise` expression. + + Expression similar to an `if-else` statement in Python. Always initiated by a + `pl.when().then()`, and optionally followed by a + `.otherwise()` can be appended at the end. If not + appended, and the condition is not `True`, `None` will be returned. + + Info: + Chaining multiple `.when().then()` statements is currently + not supported. + See [Narwhals#668](https://github.com/narwhals-dev/narwhals/issues/668). + + Arguments: + predicates: Condition(s) that must be met in order to apply the subsequent + statement. Accepts one or more boolean expressions, which are implicitly + combined with `&`. String input is parsed as a column name. + + Returns: + A "when" object, which `.then` can be called on. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> data = {"a": [1, 2, 3], "b": [5, 10, 15]} + >>> df_native = pd.DataFrame(data) + >>> nw.from_native(df_native).with_columns( + ... nw.when(nw.col("a") < 3).then(5).otherwise(6).alias("a_when") + ... ) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b a_when | + | 0 1 5 5 | + | 1 2 10 5 | + | 2 3 15 6 | + └──────────────────┘ + """ + return When(*predicates) + + +def all_horizontal(*exprs: IntoExpr | Iterable[IntoExpr], ignore_nulls: bool) -> Expr: + r"""Compute the bitwise AND horizontally across columns. + + Arguments: + exprs: Name(s) of the columns to use in the aggregation function. Accepts + expression input. + ignore_nulls: Whether to ignore nulls: + + - If `True`, null values are ignored. If there are no elements, the result + is `True`. + - If `False`, Kleene logic is followed. Note that this is not allowed for + pandas with classical NumPy dtypes when null values are present. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> data = { + ... "a": [False, False, True, True, False, None], + ... "b": [False, True, True, None, None, None], + ... } + >>> df_native = pa.table(data) + >>> nw.from_native(df_native).select( + ... "a", "b", all=nw.all_horizontal("a", "b", ignore_nulls=False) + ... ) + ┌─────────────────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------------------| + |pyarrow.Table | + |a: bool | + |b: bool | + |all: bool | + |---- | + |a: [[false,false,true,true,false,null]] | + |b: [[false,true,true,null,null,null]] | + |all: [[false,false,true,null,false,null]]| + └─────────────────────────────────────────┘ + """ + return _expr_with_horizontal_op( + "all_horizontal", *flatten(exprs), ignore_nulls=ignore_nulls + ) + + +def lit(value: PythonLiteral, dtype: IntoDType | None = None) -> Expr: + """Return an expression representing a literal value. + + Arguments: + value: The value to use as literal. Can be a scalar value, list, tuple, or dict. + Lists and tuples are converted to `List` dtype, dicts to `Struct` dtype. + dtype: The data type of the literal value. If not provided, the data type will + be inferred by the native library. For empty lists/dicts, dtype must be + specified explicitly. + + Examples: + Scalar literals: + + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> df_nw = nw.from_native(pa.table({"a": [1, 2]})) + >>> df_nw.with_columns(nw.lit(3)) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: int64 | + | literal: int64 | + | ---- | + | a: [[1,2]] | + | literal: [[3,3]] | + └──────────────────┘ + + List literals (creates a List column): + + >>> df_nw.with_columns(nw.lit([1, 2, 3]).alias("list_col")) + ┌─────────────────────────────┐ + | Narwhals DataFrame | + |-----------------------------| + |pyarrow.Table | + |a: int64 | + |list_col: list | + | child 0, item: int64 | + |---- | + |a: [[1,2]] | + |list_col: [[[1,2,3],[1,2,3]]]| + └─────────────────────────────┘ + + Dict literals (creates a Struct column): + + >>> df_nw.with_columns(nw.lit({"x": 1, "y": 2}).alias("struct_col")) + ┌──────────────────────────────────────┐ + | Narwhals DataFrame | + |--------------------------------------| + |pyarrow.Table | + |a: int64 | + |struct_col: struct| + | child 0, x: int64 | + | child 1, y: int64 | + |---- | + |a: [[1,2]] | + |struct_col: [ | + | -- is_valid: all not null | + | -- child 0 type: int64 | + |[1,1] | + | -- child 1 type: int64 | + |[2,2]] | + └──────────────────────────────────────┘ + """ + if is_numpy_array(value): + msg = ( + "numpy arrays are not supported as literal values. " + "Consider using `with_columns` to create a new column from the array." + ) + raise ValueError(msg) + if is_nested_literal(value): + if not value: + if not dtype: + msg = "Cannot infer dtype for empty nested structure. Please provide an explicit dtype parameter." + raise ValueError(msg) + elif isinstance(value, dict): + if any(is_nested_literal(v) for v in value.values()): + msg = "Nested structures with nested values are not supported." + raise NotImplementedError(msg) + elif is_nested_literal(value[0]): + msg = "Nested structures with nested values are not supported." + raise NotImplementedError(msg) + return Expr(ExprNode(ExprKind.LITERAL, "lit", value=value, dtype=dtype)) + + +def any_horizontal(*exprs: IntoExpr | Iterable[IntoExpr], ignore_nulls: bool) -> Expr: + r"""Compute the bitwise OR horizontally across columns. + + Arguments: + exprs: Name(s) of the columns to use in the aggregation function. Accepts + expression input. + ignore_nulls: Whether to ignore nulls: + + - If `True`, null values are ignored. If there are no elements, the result + is `False`. + - If `False`, Kleene logic is followed. Note that this is not allowed for + pandas with classical NumPy dtypes when null values are present. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> data = { + ... "a": [False, False, True, True, False, None], + ... "b": [False, True, True, None, None, None], + ... } + >>> df_native = pl.DataFrame(data) + >>> nw.from_native(df_native).select( + ... "a", "b", any=nw.any_horizontal("a", "b", ignore_nulls=False) + ... ) + ┌─────────────────────────┐ + | Narwhals DataFrame | + |-------------------------| + |shape: (6, 3) | + |┌───────┬───────┬───────┐| + |│ a ┆ b ┆ any │| + |│ --- ┆ --- ┆ --- │| + |│ bool ┆ bool ┆ bool │| + |╞═══════╪═══════╪═══════╡| + |│ false ┆ false ┆ false │| + |│ false ┆ true ┆ true │| + |│ true ┆ true ┆ true │| + |│ true ┆ null ┆ true │| + |│ false ┆ null ┆ null │| + |│ null ┆ null ┆ null │| + |└───────┴───────┴───────┘| + └─────────────────────────┘ + """ + return _expr_with_horizontal_op( + "any_horizontal", *flatten(exprs), ignore_nulls=ignore_nulls + ) + + +def mean_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr: + """Compute the mean of all values horizontally across columns. + + Arguments: + exprs: Name(s) of the columns to use in the aggregation function. Accepts + expression input. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> data = {"a": [1, 8, 3], "b": [4, 5, None], "c": ["x", "y", "z"]} + >>> df_native = pa.table(data) + + We define a dataframe-agnostic function that computes the horizontal mean of "a" + and "b" columns: + + >>> nw.from_native(df_native).select(nw.mean_horizontal("a", "b")) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | pyarrow.Table | + | a: double | + | ---- | + | a: [[2.5,6.5,3]] | + └──────────────────┘ + """ + return _expr_with_horizontal_op("mean_horizontal", *flatten(exprs)) + + +def concat_str( + exprs: IntoExpr | Iterable[IntoExpr], + *more_exprs: IntoExpr, + separator: str = "", + ignore_nulls: bool = False, +) -> Expr: + r"""Horizontally concatenate columns into a single string column. + + Arguments: + exprs: Columns to concatenate into a single string column. Accepts expression + input. Strings are parsed as column names, other non-expression inputs are + parsed as literals. Non-`String` columns are cast to `String`. + *more_exprs: Additional columns to concatenate into a single string column, + specified as positional arguments. + separator: String that will be used to separate the values of each column. + ignore_nulls: Ignore null values (default is `False`). + If set to `False`, null values will be propagated and if the row contains any + null values, the output is null. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> data = { + ... "a": [1, 2, 3], + ... "b": ["dogs", "cats", None], + ... "c": ["play", "swim", "walk"], + ... } + >>> df_native = pd.DataFrame(data) + >>> ( + ... nw.from_native(df_native).select( + ... nw.concat_str( + ... [nw.col("a") * 2, nw.col("b"), nw.col("c")], separator=" " + ... ).alias("full_sentence") + ... ) + ... ) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | full_sentence | + | 0 2 dogs play | + | 1 4 cats swim | + | 2 NaN | + └──────────────────┘ + """ + flat_exprs = flatten([*flatten([exprs]), *more_exprs]) + return _expr_with_horizontal_op( + "concat_str", *flat_exprs, separator=separator, ignore_nulls=ignore_nulls + ) + + +def coalesce( + exprs: IntoExpr | Iterable[IntoExpr], *more_exprs: IntoExpr | NonNestedLiteral +) -> Expr: + """Folds the columns from left to right, keeping the first non-null value. + + Arguments: + exprs: Columns to coalesce, must be a str, nw.Expr, or nw.Series + where strings are parsed as column names and both nw.Expr/nw.Series + are passed through as-is. Scalar values must be wrapped in `nw.lit`. + + *more_exprs: Additional columns to coalesce, specified as positional arguments. + + Raises: + TypeError: If any of the inputs are not a str, nw.Expr, or nw.Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> data = [ + ... (1, 5, None), + ... (None, 6, None), + ... (None, None, 9), + ... (4, 8, 10), + ... (None, None, None), + ... ] + >>> df = pl.DataFrame(data, schema=["a", "b", "c"], orient="row") + >>> nw.from_native(df).select(nw.coalesce("a", "b", "c", nw.lit(-1))) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (5, 1) | + | ┌─────┐ | + | │ a │ | + | │ --- │ | + | │ i64 │ | + | ╞═════╡ | + | │ 1 │ | + | │ 6 │ | + | │ 9 │ | + | │ 4 │ | + | │ -1 │ | + | └─────┘ | + └──────────────────┘ + """ + flat_exprs = flatten([*flatten([exprs]), *more_exprs]) + + non_exprs = [ + expr + for expr in flat_exprs + if not (isinstance(expr, str) or is_expr(expr) or is_series(expr)) + ] + if non_exprs: + msg = ( + f"All arguments to `coalesce` must be of type {str!r}, Expr, or Series." + "\nGot the following invalid arguments (type, value):" + f"\n {', '.join(repr((type(e), e)) for e in non_exprs)}" + ) + raise TypeError(msg) + + return Expr( + ExprNode( + ExprKind.ELEMENTWISE, "coalesce", exprs=flat_exprs, allow_multi_output=True + ) + ) + + +def format(f_string: str, *args: IntoExpr) -> Expr: + """Format expressions as a string. + + Arguments: + f_string: A string that with placeholders. + args: Expression(s) that fill the placeholders. + + Examples: + >>> import duckdb + >>> import narwhals as nw + >>> rel = duckdb.sql("select * from values ('a', 1), ('b', 2), ('c', 3) df(a, b)") + >>> df = nw.from_native(rel) + >>> df.with_columns(formatted=nw.format("foo_{}_bar_{}", nw.col("a"), "b")) + ┌─────────────────────────────────┐ + | Narwhals LazyFrame | + |---------------------------------| + |┌─────────┬───────┬─────────────┐| + |│ a │ b │ formatted │| + |│ varchar │ int32 │ varchar │| + |├─────────┼───────┼─────────────┤| + |│ a │ 1 │ foo_a_bar_1 │| + |│ b │ 2 │ foo_b_bar_2 │| + |│ c │ 3 │ foo_c_bar_3 │| + |└─────────┴───────┴─────────────┘| + └─────────────────────────────────┘ + """ + if (n_placeholders := f_string.count("{}")) != len(args): + msg = f"number of placeholders should equal the number of arguments. Expected {n_placeholders} arguments, got {len(args)}." + raise ValueError(msg) + + exprs = [] + it = iter(args) + for i, s in enumerate(f_string.split("{}")): + if i > 0: + exprs.append(next(it)) + if len(s) > 0: + exprs.append(lit(s)) + return concat_str(exprs, separator="") diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/group_by.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/group_by.py new file mode 100644 index 0000000000000000000000000000000000000000..65b9a9b48b1d0f95dc81da94148e34bcb28cd8b8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/group_by.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Generic, TypeVar + +from narwhals._expression_parsing import is_scalar_like +from narwhals._utils import tupleify +from narwhals.exceptions import InvalidOperationError +from narwhals.typing import DataFrameT + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + from narwhals._compliant.typing import CompliantExprAny + from narwhals.dataframe import LazyFrame + from narwhals.expr import Expr + +LazyFrameT = TypeVar("LazyFrameT", bound="LazyFrame[Any]") + + +class GroupBy(Generic[DataFrameT]): + def __init__( + self, + df: DataFrameT, + keys: Sequence[str] | Sequence[CompliantExprAny], + /, + *, + drop_null_keys: bool, + ) -> None: + self._df: DataFrameT = df + self._keys = keys + self._grouped = self._df._compliant_frame.group_by( + self._keys, drop_null_keys=drop_null_keys + ) + + def agg(self, *aggs: Expr | Iterable[Expr], **named_aggs: Expr) -> DataFrameT: + """Compute aggregations for each group of a group by operation. + + Arguments: + aggs: Aggregations to compute for each group of the group by operation, + specified as positional arguments. + named_aggs: Additional aggregations, specified as keyword arguments. + + Examples: + Group by one column or by multiple columns and call `agg` to compute + the grouped sum of another column. + + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame( + ... { + ... "a": ["a", "b", "a", "b", "c"], + ... "b": [1, 2, 1, 3, 3], + ... "c": [5, 4, 3, 2, 1], + ... } + ... ) + >>> df = nw.from_native(df_native) + >>> + >>> df.group_by("a").agg(nw.col("b").sum()).sort("a") + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | a b | + | 0 a 2 | + | 1 b 5 | + | 2 c 3 | + └──────────────────┘ + >>> + >>> df.group_by("a", "b").agg(nw.col("c").sum()).sort("a", "b").to_native() + a b c + 0 a 1 8 + 1 b 2 4 + 2 b 3 2 + 3 c 3 1 + """ + compliant_aggs = self._df._flatten_and_extract(*aggs, **named_aggs) + if not all(is_scalar_like(x) for x in compliant_aggs): + msg = ( + "Found expression which does not aggregate.\n\n" + "All expressions passed to GroupBy.agg must aggregate.\n" + "For example, `df.group_by('a').agg(nw.col('b').sum())` is valid,\n" + "but `df.group_by('a').agg(nw.col('b'))` is not." + ) + raise InvalidOperationError(msg) + return self._df._with_compliant(self._grouped.agg(*compliant_aggs)) + + def __iter__(self) -> Iterator[tuple[Any, DataFrameT]]: + yield from ( + (tupleify(key), self._df._with_compliant(df)) + for (key, df) in self._grouped.__iter__() + ) + + +class LazyGroupBy(Generic[LazyFrameT]): + def __init__( + self, + df: LazyFrameT, + keys: Sequence[str] | Sequence[CompliantExprAny], + /, + *, + drop_null_keys: bool, + ) -> None: + self._df: LazyFrameT = df + self._keys = keys + self._grouped = self._df._compliant_frame.group_by( + self._keys, drop_null_keys=drop_null_keys + ) + + def agg(self, *aggs: Expr | Iterable[Expr], **named_aggs: Expr) -> LazyFrameT: + """Compute aggregations for each group of a group by operation. + + Arguments: + aggs: Aggregations to compute for each group of the group by operation, + specified as positional arguments. + named_aggs: Additional aggregations, specified as keyword arguments. + + Examples: + Group by one column or by multiple columns and call `agg` to compute + the grouped sum of another column. + + >>> import polars as pl + >>> import narwhals as nw + >>> from narwhals.typing import IntoFrameT + >>> lf_native = pl.LazyFrame( + ... { + ... "a": ["a", "b", "a", "b", "c"], + ... "b": [1, 2, 1, 3, 3], + ... "c": [5, 4, 3, 2, 1], + ... } + ... ) + >>> lf = nw.from_native(lf_native) + >>> + >>> nw.to_native(lf.group_by("a").agg(nw.col("b").sum()).sort("a")).collect() + shape: (3, 2) + ┌─────┬─────┐ + │ a ┆ b │ + │ --- ┆ --- │ + │ str ┆ i64 │ + ╞═════╪═════╡ + │ a ┆ 2 │ + │ b ┆ 5 │ + │ c ┆ 3 │ + └─────┴─────┘ + >>> + >>> lf.group_by("a", "b").agg(nw.sum("c")).sort("a", "b").collect() + ┌───────────────────┐ + |Narwhals DataFrame | + |-------------------| + |shape: (4, 3) | + |┌─────┬─────┬─────┐| + |│ a ┆ b ┆ c │| + |│ --- ┆ --- ┆ --- │| + |│ str ┆ i64 ┆ i64 │| + |╞═════╪═════╪═════╡| + |│ a ┆ 1 ┆ 8 │| + |│ b ┆ 2 ┆ 4 │| + |│ b ┆ 3 ┆ 2 │| + |│ c ┆ 3 ┆ 1 │| + |└─────┴─────┴─────┘| + └───────────────────┘ + """ + compliant_aggs = self._df._flatten_and_extract(*aggs, **named_aggs) + if not all(is_scalar_like(x) for x in compliant_aggs): + msg = ( + "Found expression which does not aggregate.\n\n" + "All expressions passed to GroupBy.agg must aggregate.\n" + "For example, `df.group_by('a').agg(nw.col('b').sum())` is valid,\n" + "but `df.group_by('a').agg(nw.col('b'))` is not." + ) + raise InvalidOperationError(msg) + return self._df._with_compliant(self._grouped.agg(*compliant_aggs)) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/plugins.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..982f9fe986abcf8fa665c3a6a9e3f91d73917c80 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/plugins.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import sys +from functools import cache +from typing import TYPE_CHECKING, Any, Protocol, cast + +from narwhals._compliant import CompliantNamespace +from narwhals._typing_compat import TypeVar + +if TYPE_CHECKING: + from collections.abc import Iterator + from importlib.metadata import EntryPoints + + from typing_extensions import LiteralString, TypeAlias + + from narwhals._compliant.typing import ( + CompliantDataFrameAny, + CompliantFrameAny, + CompliantLazyFrameAny, + CompliantSeriesAny, + ) + from narwhals.utils import Version + + +__all__ = ["Plugin", "from_native"] + +CompliantAny: TypeAlias = ( + "CompliantDataFrameAny | CompliantLazyFrameAny | CompliantSeriesAny" +) +"""A statically-unknown, Compliant object originating from a plugin.""" + +FrameT = TypeVar( + "FrameT", + bound="CompliantFrameAny", + default="CompliantDataFrameAny | CompliantLazyFrameAny", +) +FromNativeR_co = TypeVar( + "FromNativeR_co", bound=CompliantAny, covariant=True, default=CompliantAny +) + + +@cache +def _discover_entrypoints() -> EntryPoints: + from importlib.metadata import entry_points as eps + + group = "narwhals.plugins" + if sys.version_info < (3, 10): + return cast("EntryPoints", eps().get(group, ())) + return eps(group=group) + + +class PluginNamespace(CompliantNamespace[FrameT, Any], Protocol[FrameT, FromNativeR_co]): + def from_native(self, data: Any, /) -> FromNativeR_co: ... + + +class Plugin(Protocol[FrameT, FromNativeR_co]): + @property + def NATIVE_PACKAGE(self) -> LiteralString: ... # noqa: N802 + + def __narwhals_namespace__( + self, version: Version + ) -> PluginNamespace[FrameT, FromNativeR_co]: ... + def is_native(self, native_object: object, /) -> bool: ... + + +@cache +def _might_be(cls: type, type_: str) -> bool: # pragma: no cover + try: + return any(type_ in o.__module__.split(".") for o in cls.mro()) + except TypeError: + return False + + +def _is_native_plugin(native_object: Any, plugin: Plugin) -> bool: + pkg = plugin.NATIVE_PACKAGE + return ( + sys.modules.get(pkg) is not None + and _might_be(type(native_object), pkg) # type: ignore[arg-type] + and plugin.is_native(native_object) + ) + + +def _iter_from_native(native_object: Any, version: Version) -> Iterator[CompliantAny]: + for entry_point in _discover_entrypoints(): + plugin: Plugin = entry_point.load() + if _is_native_plugin(native_object, plugin): + compliant_namespace = plugin.__narwhals_namespace__(version=version) + yield compliant_namespace.from_native(native_object) + + +def from_native(native_object: Any, version: Version) -> CompliantAny | None: + """Attempt to convert `native_object` to a Compliant object, using any available plugin(s). + + Arguments: + native_object: Raw object from user. + version: Narwhals API version. + + Returns: + If the following conditions are met + - at least 1 plugin is installed + - at least 1 installed plugin supports `type(native_object)` + + Then for the **first matching plugin**, the result of the call below. + This *should* be an object accepted by a Narwhals Dataframe, Lazyframe, or Series: + + plugin: Plugin + plugin.__narwhals_namespace__(version).from_native(native_object) + + In all other cases, `None` is returned instead. + """ + return next(_iter_from_native(native_object, version), None) + + +def _show_suggestions(native_object_type: type) -> str | None: + if _might_be(native_object_type, "daft"): # pragma: no cover + return ( + "Hint: it looks like you passed a `daft.DataFrame` but don't have `narwhals-daft` installed.\n" + "Please refer to https://github.com/narwhals-dev/narwhals-daft for installation instructions." + ) + return None diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/py.typed b/.venv_haddock/lib/python3.12/site-packages/narwhals/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/schema.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..b459be68fa4491e25e18a7499c02ecb4c74331f7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/schema.py @@ -0,0 +1,365 @@ +"""Schema. + +Adapted from Polars implementation at: +https://github.com/pola-rs/polars/blob/main/py-polars/polars/schema.py. +""" + +from __future__ import annotations + +from collections import OrderedDict +from collections.abc import Mapping +from functools import partial +from typing import TYPE_CHECKING, cast + +from narwhals._utils import Implementation, Version, qualified_type_name, zip_strict +from narwhals.dependencies import ( + get_cudf, + is_cudf_dtype, + is_pandas_like_dtype, + is_polars_data_type, + is_polars_schema, + is_pyarrow_data_type, + is_pyarrow_schema, +) + +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import Any, ClassVar + + import polars as pl + import pyarrow as pa + from typing_extensions import Self + + from narwhals.dtypes import DType + from narwhals.typing import ( + DTypeBackend, + IntoArrowSchema, + IntoPandasSchema, + IntoPolarsSchema, + ) + + +__all__ = ["Schema"] + + +class Schema(OrderedDict[str, "DType"]): + """Ordered mapping of column names to their data type. + + Arguments: + schema: The schema definition given by column names and their associated + *instantiated* Narwhals data type. Accepts a mapping or an iterable of tuples. + + Examples: + Define a schema by passing *instantiated* data types. + + >>> import narwhals as nw + >>> schema = nw.Schema({"foo": nw.Int8(), "bar": nw.String()}) + >>> schema + Schema({'foo': Int8, 'bar': String}) + + Access the data type associated with a specific column name. + + >>> schema["foo"] + Int8 + + Access various schema properties using the `names`, `dtypes`, and `len` methods. + + >>> schema.names() + ['foo', 'bar'] + >>> schema.dtypes() + [Int8, String] + >>> schema.len() + 2 + """ + + _version: ClassVar[Version] = Version.MAIN + + def __init__( + self, schema: Mapping[str, DType] | Iterable[tuple[str, DType]] | None = None + ) -> None: + schema = schema or {} + super().__init__(schema) + + def names(self) -> list[str]: + """Get the column names of the schema.""" + return list(self.keys()) + + def dtypes(self) -> list[DType]: + """Get the data types of the schema.""" + return list(self.values()) + + def len(self) -> int: + """Get the number of columns in the schema.""" + return len(self) + + @classmethod + def from_arrow(cls, schema: IntoArrowSchema, /) -> Self: + """Construct a Schema from a pyarrow Schema. + + Arguments: + schema: A pyarrow Schema or mapping of column names to pyarrow data types. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> mapping = { + ... "a": pa.timestamp("us", "UTC"), + ... "b": pa.date32(), + ... "c": pa.string(), + ... "d": pa.uint8(), + ... } + >>> native = pa.schema(mapping) + >>> + >>> nw.Schema.from_arrow(native) + Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8}) + + >>> nw.Schema.from_arrow(mapping) == nw.Schema.from_arrow(native) + True + """ + if isinstance(schema, Mapping): + if not schema: + return cls() + import pyarrow as pa # ignore-banned-import + + schema = pa.schema(schema) + from narwhals._arrow.utils import native_to_narwhals_dtype + + return cls( + (field.name, native_to_narwhals_dtype(field.type, cls._version)) + for field in schema + ) + + @classmethod + def from_pandas_like(cls, schema: IntoPandasSchema, /) -> Self: + """Construct a Schema from a pandas-like schema representation. + + Arguments: + schema: A mapping of column names to pandas-like data types. + + Examples: + >>> import numpy as np + >>> import pandas as pd + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> data = {"a": [1], "b": ["a"], "c": [False], "d": [9.2]} + >>> native = pd.DataFrame(data).convert_dtypes().dtypes.to_dict() + >>> + >>> nw.Schema.from_pandas_like(native) + Schema({'a': Int64, 'b': String, 'c': Boolean, 'd': Float64}) + >>> + >>> mapping = { + ... "a": pd.DatetimeTZDtype("us", "UTC"), + ... "b": pd.ArrowDtype(pa.date32()), + ... "c": pd.StringDtype("python"), + ... "d": np.dtype("uint8"), + ... } + >>> + >>> nw.Schema.from_pandas_like(mapping) + Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8}) + """ + if not schema: + return cls() + impl = ( + Implementation.CUDF + if get_cudf() and any(is_cudf_dtype(dtype) for dtype in schema.values()) + else Implementation.PANDAS + ) + return cls._from_pandas_like(schema, impl) + + @classmethod + def from_native( + cls, schema: IntoArrowSchema | IntoPolarsSchema | IntoPandasSchema, / + ) -> Self: + """Construct a Schema from a native schema representation. + + Arguments: + schema: A native schema object, or mapping of column names to + *instantiated* native data types. + + Examples: + >>> import datetime as dt + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> data = {"a": [1], "b": ["a"], "c": [dt.time(1, 2, 3)], "d": [[2]]} + >>> native = pa.table(data).schema + >>> + >>> nw.Schema.from_native(native) + Schema({'a': Int64, 'b': String, 'c': Time, 'd': List(Int64)}) + """ + if is_pyarrow_schema(schema): + return cls.from_arrow(schema) + if is_polars_schema(schema): + return cls.from_polars(schema) + if isinstance(schema, Mapping): + return cls._from_native_mapping(schema) if schema else cls() + msg = ( + f"Expected an arrow, polars, or pandas schema, but got " + f"{qualified_type_name(schema)!r}\n\n{schema!r}" + ) + raise TypeError(msg) + + @classmethod + def from_polars(cls, schema: IntoPolarsSchema, /) -> Self: + """Construct a Schema from a polars Schema. + + Arguments: + schema: A polars Schema or mapping of column names to *instantiated* + polars data types. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> mapping = { + ... "a": pl.Datetime(time_zone="UTC"), + ... "b": pl.Date(), + ... "c": pl.String(), + ... "d": pl.UInt8(), + ... } + >>> native = pl.Schema(mapping) + >>> + >>> nw.Schema.from_polars(native) + Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8}) + + >>> nw.Schema.from_polars(mapping) == nw.Schema.from_polars(native) + True + """ + if not schema: + return cls() + from narwhals._polars.utils import native_to_narwhals_dtype + + return cls( + (name, native_to_narwhals_dtype(dtype, cls._version)) + for name, dtype in schema.items() + ) + + def to_arrow(self) -> pa.Schema: + """Convert Schema to a pyarrow Schema. + + Examples: + >>> import narwhals as nw + >>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")}) + >>> schema.to_arrow() + a: int64 + b: timestamp[ns] + """ + import pyarrow as pa # ignore-banned-import + + from narwhals._arrow.utils import narwhals_to_native_dtype + + return pa.schema( + (name, narwhals_to_native_dtype(dtype, self._version)) + for name, dtype in self.items() + ) + + def to_pandas( + self, dtype_backend: DTypeBackend | Iterable[DTypeBackend] = None + ) -> dict[str, Any]: + """Convert Schema to an ordered mapping of column names to their pandas data type. + + Arguments: + dtype_backend: Backend(s) used for the native types. When providing more than + one, the length of the iterable must be equal to the length of the schema. + + Examples: + >>> import narwhals as nw + >>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")}) + >>> schema.to_pandas() + {'a': 'int64', 'b': 'datetime64[ns]'} + + >>> schema.to_pandas("pyarrow") + {'a': 'Int64[pyarrow]', 'b': 'timestamp[ns][pyarrow]'} + """ + from narwhals._pandas_like.utils import narwhals_to_native_dtype + + to_native_dtype = partial( + narwhals_to_native_dtype, + implementation=Implementation.PANDAS, + version=self._version, + ) + if dtype_backend is None or isinstance(dtype_backend, str): + return { + name: to_native_dtype(dtype=dtype, dtype_backend=dtype_backend) + for name, dtype in self.items() + } + backends = tuple(dtype_backend) + if len(backends) != len(self): + from itertools import chain, islice, repeat + + n_user, n_actual = len(backends), len(self) + suggestion = tuple( + islice(chain.from_iterable(islice(repeat(backends), n_actual)), n_actual) + ) + msg = ( + f"Provided {n_user!r} `dtype_backend`(s), but schema contains {n_actual!r} field(s).\n" + "Hint: instead of\n" + f" schema.to_pandas({backends})\n" + "you may want to use\n" + f" schema.to_pandas({backends[0]})\n" + f"or\n" + f" schema.to_pandas({suggestion})" + ) + raise ValueError(msg) + return { + name: to_native_dtype(dtype=dtype, dtype_backend=backend) + for name, dtype, backend in zip_strict(self.keys(), self.values(), backends) + } + + def to_polars(self) -> pl.Schema: + """Convert Schema to a polars Schema. + + Examples: + >>> import narwhals as nw + >>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")}) + >>> schema.to_polars() + Schema({'a': Int64, 'b': Datetime(time_unit='ns', time_zone=None)}) + """ + import polars as pl # ignore-banned-import + + from narwhals._polars.utils import narwhals_to_native_dtype + + pl_version = Implementation.POLARS._backend_version() + schema = ( + (name, narwhals_to_native_dtype(dtype, self._version)) + for name, dtype in self.items() + ) + return ( + pl.Schema(schema) + if pl_version >= (1, 0, 0) + else cast("pl.Schema", dict(schema)) + ) + + @classmethod + def _from_native_mapping( + cls, + native: Mapping[str, pa.DataType] | Mapping[str, pl.DataType] | IntoPandasSchema, + /, + ) -> Self: + first_item = next(iter(native.items())) + first_key, first_dtype = first_item + if is_polars_data_type(first_dtype): + return cls.from_polars(cast("IntoPolarsSchema", native)) + if is_pandas_like_dtype(first_dtype): + return cls.from_pandas_like(cast("IntoPandasSchema", native)) + if is_pyarrow_data_type(first_dtype): + return cls.from_arrow(cast("IntoArrowSchema", native)) + msg = ( + f"Expected an arrow, polars, or pandas dtype, but found " + f"`{first_key}: {qualified_type_name(first_dtype)}`\n\n{native!r}" + ) + raise TypeError(msg) + + @classmethod + def _from_pandas_like( + cls, schema: IntoPandasSchema, implementation: Implementation, / + ) -> Self: + from narwhals._pandas_like.utils import native_to_narwhals_dtype + + impl = implementation + return cls( + (name, native_to_narwhals_dtype(dtype, cls._version, impl, allow_object=True)) + for name, dtype in schema.items() + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/selectors.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/selectors.py new file mode 100644 index 0000000000000000000000000000000000000000..67c7e3abfc8258ffcdf10672a20a728d17fdf405 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/selectors.py @@ -0,0 +1,322 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, NoReturn + +from narwhals._expression_parsing import ExprKind, ExprNode +from narwhals._utils import flatten +from narwhals.expr import Expr + +if TYPE_CHECKING: + from collections.abc import Iterable + from datetime import timezone + + from narwhals.dtypes import DType + from narwhals.typing import TimeUnit + + +class Selector(Expr): + def _to_expr(self) -> Expr: + return Expr(*self._nodes) + + def __add__(self, other: Any) -> Expr: # type: ignore[override] + if isinstance(other, Selector): + msg = "unsupported operand type(s) for op: ('Selector' + 'Selector')" + raise TypeError(msg) + return self._to_expr()._append_node( + ExprNode(ExprKind.ELEMENTWISE, "__add__", exprs=(other,), str_as_lit=True) + ) + + def __or__(self, other: Any) -> Expr: # type: ignore[override] + if isinstance(other, Selector): + return self._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "__or__", + exprs=(other,), + str_as_lit=True, + allow_multi_output=True, + ) + ) + return self._to_expr()._append_node( + ExprNode(ExprKind.ELEMENTWISE, "__or__", exprs=(other,), str_as_lit=True) + ) + + def __and__(self, other: Any) -> Expr: # type: ignore[override] + if isinstance(other, Selector): + return self._append_node( + ExprNode( + ExprKind.ELEMENTWISE, + "__and__", + exprs=(other,), + str_as_lit=True, + allow_multi_output=True, + ) + ) + return self._to_expr()._append_node( + ExprNode(ExprKind.ELEMENTWISE, "__and__", exprs=(other,), str_as_lit=True) + ) + + def __rsub__(self, other: Any) -> NoReturn: + raise NotImplementedError + + def __rand__(self, other: Any) -> NoReturn: + raise NotImplementedError + + def __ror__(self, other: Any) -> NoReturn: + raise NotImplementedError + + +def by_dtype(*dtypes: DType | type[DType] | Iterable[DType | type[DType]]) -> Selector: + """Select columns based on their dtype. + + Arguments: + dtypes: one or data types to select + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> df_native = pa.table({"a": [1, 2], "b": ["x", "y"], "c": [4.1, 2.3]}) + >>> df = nw.from_native(df_native) + + Let's select int64 and float64 dtypes and multiply each value by 2: + + >>> df.select(ncs.by_dtype(nw.Int64, nw.Float64) * 2).to_native() + pyarrow.Table + a: int64 + c: double + ---- + a: [[2,4]] + c: [[8.2,4.6]] + """ + flattened = flatten(dtypes) + return Selector(ExprNode(ExprKind.SELECTOR, "selectors.by_dtype", dtypes=flattened)) + + +def matches(pattern: str) -> Selector: + """Select all columns that match the given regex pattern. + + Arguments: + pattern: A valid regular expression pattern. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> df_native = pd.DataFrame( + ... {"bar": [123, 456], "baz": [2.0, 5.5], "zap": [0, 1]} + ... ) + >>> df = nw.from_native(df_native) + + Let's select column names containing an 'a', preceded by a character that is not 'z': + + >>> df.select(ncs.matches("[^z]a")).to_native() + bar baz + 0 123 2.0 + 1 456 5.5 + """ + return Selector(ExprNode(ExprKind.SELECTOR, "selectors.matches", pattern=pattern)) + + +def numeric() -> Selector: + """Select numeric columns. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [4.1, 2.3]}) + >>> df = nw.from_native(df_native) + + Let's select numeric dtypes and multiply each value by 2: + + >>> df.select(ncs.numeric() * 2).to_native() + shape: (2, 2) + ┌─────┬─────┐ + │ a ┆ c │ + │ --- ┆ --- │ + │ i64 ┆ f64 │ + ╞═════╪═════╡ + │ 2 ┆ 8.2 │ + │ 4 ┆ 4.6 │ + └─────┴─────┘ + """ + return Selector(ExprNode(ExprKind.SELECTOR, "selectors.numeric")) + + +def boolean() -> Selector: + """Select boolean columns. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]}) + >>> df = nw.from_native(df_native) + + Let's select boolean dtypes: + + >>> df.select(ncs.boolean()) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + | shape: (2, 1) | + | ┌───────┐ | + | │ c │ | + | │ --- │ | + | │ bool │ | + | ╞═══════╡ | + | │ false │ | + | │ true │ | + | └───────┘ | + └──────────────────┘ + """ + return Selector(ExprNode(ExprKind.SELECTOR, "selectors.boolean")) + + +def string() -> Selector: + """Select string columns. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]}) + >>> df = nw.from_native(df_native) + + Let's select string dtypes: + + >>> df.select(ncs.string()).to_native() + shape: (2, 1) + ┌─────┐ + │ b │ + │ --- │ + │ str │ + ╞═════╡ + │ x │ + │ y │ + └─────┘ + """ + return Selector(ExprNode(ExprKind.SELECTOR, "selectors.string")) + + +def categorical() -> Selector: + """Select categorical columns. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]}) + + Let's convert column "b" to categorical, and then select categorical dtypes: + + >>> df = nw.from_native(df_native).with_columns( + ... b=nw.col("b").cast(nw.Categorical()) + ... ) + >>> df.select(ncs.categorical()).to_native() + shape: (2, 1) + ┌─────┐ + │ b │ + │ --- │ + │ cat │ + ╞═════╡ + │ x │ + │ y │ + └─────┘ + """ + return Selector(ExprNode(ExprKind.SELECTOR, "selectors.categorical")) + + +def all() -> Selector: + """Select all columns. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> df_native = pd.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]}) + >>> df = nw.from_native(df_native) + + Let's select all dtypes: + + >>> df.select(ncs.all()).to_native() + a b c + 0 1 x False + 1 2 y True + """ + return Selector(ExprNode(ExprKind.SELECTOR, "selectors.all")) + + +def datetime( + time_unit: TimeUnit | Iterable[TimeUnit] | None = None, + time_zone: str | timezone | Iterable[str | timezone | None] | None = ("*", None), +) -> Selector: + """Select all datetime columns, optionally filtering by time unit/zone. + + Arguments: + time_unit: One (or more) of the allowed timeunit precision strings, "ms", "us", + "ns" and "s". Omit to select columns with any valid timeunit. + time_zone: Specify which timezone(s) to select + + * One or more timezone strings, as defined in zoneinfo (to see valid options + run `import zoneinfo; zoneinfo.available_timezones()` for a full list). + * Set `None` to select Datetime columns that do not have a timezone. + * Set `"*"` to select Datetime columns that have *any* timezone. + + Examples: + >>> from datetime import datetime, timezone + >>> import pyarrow as pa + >>> import narwhals as nw + >>> import narwhals.selectors as ncs + >>> + >>> utc_tz = timezone.utc + >>> data = { + ... "tstamp_utc": [ + ... datetime(2023, 4, 10, 12, 14, 16, 999000, tzinfo=utc_tz), + ... datetime(2025, 8, 25, 14, 18, 22, 666000, tzinfo=utc_tz), + ... ], + ... "tstamp": [ + ... datetime(2000, 11, 20, 18, 12, 16, 600000), + ... datetime(2020, 10, 30, 10, 20, 25, 123000), + ... ], + ... "numeric": [3.14, 6.28], + ... } + >>> df_native = pa.table(data) + >>> df_nw = nw.from_native(df_native) + >>> df_nw.select(ncs.datetime()).to_native() + pyarrow.Table + tstamp_utc: timestamp[us, tz=UTC] + tstamp: timestamp[us] + ---- + tstamp_utc: [[2023-04-10 12:14:16.999000Z,2025-08-25 14:18:22.666000Z]] + tstamp: [[2000-11-20 18:12:16.600000,2020-10-30 10:20:25.123000]] + + Select only datetime columns that have any time_zone specification: + + >>> df_nw.select(ncs.datetime(time_zone="*")).to_native() + pyarrow.Table + tstamp_utc: timestamp[us, tz=UTC] + ---- + tstamp_utc: [[2023-04-10 12:14:16.999000Z,2025-08-25 14:18:22.666000Z]] + """ + return Selector( + ExprNode( + ExprKind.SELECTOR, + "selectors.datetime", + time_unit=time_unit, + time_zone=time_zone, + ) + ) + + +__all__ = [ + "all", + "boolean", + "by_dtype", + "categorical", + "datetime", + "matches", + "numeric", + "string", +] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/series.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/series.py new file mode 100644 index 0000000000000000000000000000000000000000..6acc47624568c34a641c09eb40dcf0120f696693 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/series.py @@ -0,0 +1,2950 @@ +from __future__ import annotations + +import math +from collections.abc import Iterable, Iterator, Mapping, Sequence +from functools import partial +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Generic, + Literal, + cast, + overload, +) + +from narwhals._expression_parsing import ExprKind, ExprNode +from narwhals._utils import ( + Implementation, + Version, + _Implementation, + _validate_rolling_arguments, + ensure_type, + generate_repr, + is_compliant_series, + is_eager_allowed, + is_index_selector, + no_default, + qualified_type_name, + supports_arrow_c_stream, + unstable, +) +from narwhals.dependencies import is_numpy_array, is_numpy_array_1d, is_numpy_scalar +from narwhals.dtypes import _validate_dtype, _validate_into_dtype +from narwhals.exceptions import ComputeError, InvalidOperationError +from narwhals.expr import Expr +from narwhals.functions import col +from narwhals.series_cat import SeriesCatNamespace +from narwhals.series_dt import SeriesDateTimeNamespace +from narwhals.series_list import SeriesListNamespace +from narwhals.series_str import SeriesStringNamespace +from narwhals.series_struct import SeriesStructNamespace +from narwhals.translate import to_native +from narwhals.typing import IntoSeriesT + +if TYPE_CHECKING: + from types import ModuleType + from typing import NoReturn + + import pandas as pd + import polars as pl + import pyarrow as pa + from typing_extensions import Self + + from narwhals._compliant import CompliantSeries + from narwhals._typing import EagerAllowed, IntoBackend, NoDefault + from narwhals.dataframe import DataFrame, MultiIndexSelector + from narwhals.dtypes import DType + from narwhals.typing import ( + ClosedInterval, + FillNullStrategy, + IntoDType, + ModeKeepStrategy, + NonNestedLiteral, + NumericLiteral, + PythonLiteral, + RankMethod, + RollingInterpolationMethod, + SingleIndexSelector, + TemporalLiteral, + _1DArray, + ) + + +class Series(Generic[IntoSeriesT]): + """Narwhals Series, backed by a native series. + + Warning: + This class is not meant to be instantiated directly - instead: + + - If the native object is a series from one of the supported backend (e.g. + pandas.Series, polars.Series, pyarrow.ChunkedArray), you can use + [`narwhals.from_native`][]: + ```py + narwhals.from_native(native_series, allow_series=True) + narwhals.from_native(native_series, series_only=True) + ``` + + - If the object is a generic sequence (e.g. a list or a tuple of values), you can + create a series via [`narwhals.new_series`][], e.g.: + ```py + narwhals.new_series(name="price", values=[10.5, 9.4, 1.2], backend="pandas") + ``` + """ + + _version: ClassVar[Version] = Version.MAIN + + @property + def _compliant(self) -> CompliantSeries[IntoSeriesT]: + return self._compliant_series + + @property + def _dataframe(self) -> type[DataFrame[Any]]: + from narwhals.dataframe import DataFrame + + return DataFrame + + def _to_expr(self) -> Expr: + return Expr( + ExprNode(ExprKind.SERIES, "_expr._from_series", series=self._compliant) + ) + + def __init__( + self, series: Any, *, level: Literal["full", "lazy", "interchange"] + ) -> None: + self._level: Literal["full", "lazy", "interchange"] = level + if is_compliant_series(series): + self._compliant_series: CompliantSeries[IntoSeriesT] = ( + series.__narwhals_series__() + ) + else: # pragma: no cover + msg = f"Expected Polars Series or an object which implements `__narwhals_series__`, got: {type(series)}." + raise AssertionError(msg) + + @classmethod + def from_numpy( + cls, + name: str, + values: _1DArray, + dtype: IntoDType | None = None, + *, + backend: IntoBackend[EagerAllowed], + ) -> Series[Any]: + """Construct a Series from a NumPy ndarray. + + Arguments: + name: Name of resulting Series. + values: One-dimensional data represented as a NumPy ndarray. + dtype: (Narwhals) dtype. If not provided, the native library + may auto-infer it from `values`. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import numpy as np + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> arr = np.arange(5, 10) + >>> nw.Series.from_numpy("arr", arr, dtype=nw.Int8, backend="polars") + ┌──────────────────┐ + | Narwhals Series | + |------------------| + |shape: (5,) | + |Series: 'arr' [i8]| + |[ | + | 5 | + | 6 | + | 7 | + | 8 | + | 9 | + |] | + └──────────────────┘ + """ + if not is_numpy_array_1d(values): + msg = "`from_numpy` only accepts 1D numpy arrays" + raise ValueError(msg) + if dtype: + _validate_into_dtype(dtype) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + compliant = ns.from_numpy(values).alias(name) + if dtype: + return cls(compliant.cast(dtype), level="full") + return cls(compliant, level="full") + msg = ( # pragma: no cover + f"{implementation} support in Narwhals is lazy-only, but `Series.from_numpy` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.Series.from_numpy(arr, backend='pyarrow').to_frame().lazy('{implementation}')" + ) + raise ValueError(msg) # pragma: no cover + + @classmethod + def from_iterable( + cls, + name: str, + values: Iterable[Any], + dtype: IntoDType | None = None, + *, + backend: IntoBackend[EagerAllowed], + ) -> Series[Any]: + """Construct a Series from an iterable. + + Arguments: + name: Name of resulting Series. + values: One-dimensional data represented as an iterable. + dtype: (Narwhals) dtype. If not provided, the native library + may auto-infer it from `values`. + backend: specifies which eager backend instantiate to. + + `backend` can be specified in various ways + + - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, + `POLARS`, `MODIN` or `CUDF`. + - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. + - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> values = [4, 1, 3, 2] + >>> nw.Series.from_iterable("a", values, dtype=nw.UInt32, backend="pandas") + ┌──────────────────────┐ + | Narwhals Series | + |----------------------| + |0 4 | + |1 1 | + |2 3 | + |3 2 | + |Name: a, dtype: uint32| + └──────────────────────┘ + """ + if is_numpy_array(values): + return cls.from_numpy(name, values, dtype, backend=backend) + if dtype: + _validate_into_dtype(dtype) + if not isinstance(values, Iterable): + msg = f"Expected values to be an iterable, got: {qualified_type_name(values)!r}." + raise TypeError(msg) + implementation = Implementation.from_backend(backend) + if is_eager_allowed(implementation): + ns = cls._version.namespace.from_backend(implementation).compliant + compliant = ns._series.from_iterable( + values, context=ns, name=name, dtype=dtype + ) + return cls(compliant, level="full") + msg = ( + f"{implementation} support in Narwhals is lazy-only, but `Series.from_iterable` is an eager-only function.\n\n" + "Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n" + f" nw.Series.from_iterable('a', [1,2,3], backend='pyarrow').to_frame().lazy('{implementation}')" + ) + raise ValueError(msg) + + implementation: _Implementation = _Implementation() + """Return [`narwhals.Implementation`][] of native Series. + + This can be useful when you need to use special-casing for features outside of + Narwhals' scope - for example, when dealing with pandas' Period Dtype. + + Examples: + >>> import narwhals as nw + >>> import pandas as pd + >>> s_native = pd.Series([1, 2, 3]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.implementation + + >>> s.implementation.is_pandas() + True + >>> s.implementation.is_pandas_like() + True + >>> s.implementation.is_polars() + False + """ + + def __bool__(self) -> NoReturn: + msg = ( + "the truth value of a Series is ambiguous" + "\n\n" + "Here are some things you might want to try:\n" + "- instead of `if s`, use `if not s.is_empty()`\n" + "- instead of `s1 and s2`, use `s1 & s2`\n" + "- instead of `s1 or s2`, use `s1 | s2`\n" + "- instead of `s in [y, z]`, use `s.is_in([y, z])`\n" + ) + raise TypeError(msg) + + def __array__(self, dtype: Any = None, copy: bool | None = None) -> _1DArray: # noqa: FBT001 + return self._compliant_series.__array__(dtype=dtype, copy=copy) + + @overload + def __getitem__(self, idx: SingleIndexSelector) -> Any: ... + + @overload + def __getitem__(self, idx: MultiIndexSelector) -> Self: ... + + def __getitem__(self, idx: SingleIndexSelector | MultiIndexSelector) -> Any | Self: + """Retrieve elements from the object using integer indexing or slicing. + + Arguments: + idx: The index, slice, or sequence of indices to retrieve. + + - If `idx` is an integer, a single element is returned. + - If `idx` is a slice, a sequence of integers, or another Series + (with integer values) a subset of the Series is returned. + + Returns: + A single element if `idx` is an integer, else a subset of the Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True)[0] + 1 + + >>> nw.from_native(s_native, series_only=True)[ + ... :2 + ... ].to_native() # doctest:+ELLIPSIS + + [ + [ + 1, + 2 + ] + ] + """ + if isinstance(idx, int) or ( + is_numpy_scalar(idx) and idx.dtype.kind in {"i", "u"} + ): + idx = int(idx) if not isinstance(idx, int) else idx + return self._compliant_series.item(idx) + + if isinstance(idx, self.to_native().__class__): + idx = self._with_compliant(self._compliant_series._with_native(idx)) + + if not is_index_selector(idx): + msg = ( + f"Unexpected type for `Series.__getitem__`: {type(idx)}.\n\n" + "Hints:\n" + "- use `s.item` to select a single item.\n" + "- Use `s[indices]` to select rows positionally.\n" + "- Use `s.filter(mask)` to filter rows based on a boolean mask." + ) + raise TypeError(msg) + if isinstance(idx, Series): + return self._with_compliant(self._compliant_series[idx._compliant_series]) + assert not isinstance(idx, int) # noqa: S101 # help mypy + return self._with_compliant(self._compliant_series[idx]) + + def __native_namespace__(self) -> ModuleType: + return self._compliant_series.__native_namespace__() + + def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: + """Export a Series via the Arrow PyCapsule Interface. + + Narwhals doesn't implement anything itself here: + + - if the underlying series implements the interface, it'll return that + - else, it'll call `to_arrow` and then defer to PyArrow's implementation + + See [PyCapsule Interface](https://arrow.apache.org/docs/dev/format/CDataInterface/PyCapsuleInterface.html) + for more. + """ + native_series = self._compliant_series.native + if supports_arrow_c_stream(native_series): + return native_series.__arrow_c_stream__(requested_schema=requested_schema) + try: + pa_version = Implementation.PYARROW._backend_version() + except ModuleNotFoundError as exc: + msg = f"'pyarrow>=16.0.0' is required for `Series.__arrow_c_stream__` for object of type {type(native_series)}" + raise ModuleNotFoundError(msg) from exc + if pa_version < (16, 0): # pragma: no cover + msg = f"'pyarrow>=16.0.0' is required for `Series.__arrow_c_stream__` for object of type {type(native_series)}" + raise ModuleNotFoundError(msg) + from narwhals._arrow.utils import chunked_array + + ca = chunked_array(self.to_arrow()) + return ca.__arrow_c_stream__(requested_schema=requested_schema) + + def to_native(self) -> IntoSeriesT: + """Convert Narwhals series to native series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 1 + 2 + ] + """ + return self._compliant_series.native + + def scatter( + self, + indices: Self | Iterable[int] | int, + values: Self | Iterable[PythonLiteral] | PythonLiteral, + ) -> Self: + """Set value(s) at the given index location(s). + + Arguments: + indices: Integer(s) representing the index location(s). + values: Replacement values. + + Note: + This method always returns a new Series, without modifying the original one. + Using this function in a for-loop is an anti-pattern, we recommend building + up your positions and values beforehand and doing an update in one go. + + For example, instead of + + ```python + for i in [1, 3, 2]: + value = some_function(i) + s = s.scatter(i, value) + ``` + + prefer + + ```python + positions = [1, 3, 2] + values = [some_function(x) for x in positions] + s = s.scatter(positions, values) + ``` + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> df_native = pa.table({"a": [1, 2, 3], "b": [4, 5, 6]}) + >>> df_nw = nw.from_native(df_native) + >>> df_nw.with_columns(df_nw["a"].scatter([0, 1], [999, 888])).to_native() + pyarrow.Table + a: int64 + b: int64 + ---- + a: [[999,888,3]] + b: [[4,5,6]] + """ + into_series = partial( + type(self).from_iterable, name="", backend=self.implementation + ) + + if not isinstance(indices, Series): + if not isinstance(indices, Iterable): + indices = [indices] + dtypes = self._version.dtypes + indices = into_series(values=indices, dtype=dtypes.Int64) + + if indices.is_empty(): + return self + + if not isinstance(values, Series): + if not isinstance(values, Iterable) or isinstance(values, str): + values = [values] + values = into_series(values=values) + + result = self._compliant.scatter(indices._compliant, values._compliant) + return self._with_compliant(result) + + @property + def shape(self) -> tuple[int]: + """Get the shape of the Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).shape + (3,) + """ + return (self._compliant_series.len(),) + + def _extract_native(self, arg: Any) -> Any: + if isinstance(arg, Series): + return arg._compliant_series + return arg + + def _with_compliant(self, series: Any) -> Self: + return self.__class__(series, level=self._level) + + def pipe(self, function: Callable[[Any], Self], *args: Any, **kwargs: Any) -> Self: + """Pipe function call. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([1, 2, 3]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.pipe(lambda x: x + 2).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [i64] + [ + 3 + 4 + 5 + ] + """ + return function(self, *args, **kwargs) + + def __repr__(self) -> str: # pragma: no cover + return generate_repr("Narwhals Series", self.to_native().__repr__()) + + def __len__(self) -> int: + return len(self._compliant_series) + + def len(self) -> int: + r"""Return the number of elements in the Series. + + Null values count towards the total. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> nw.from_native(s_native, series_only=True).len() + 3 + """ + return len(self._compliant_series) + + @property + def dtype(self) -> DType: + """Get the data type of the Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).dtype + Int64 + """ + return self._compliant_series.dtype + + @property + def name(self) -> str: + """Get the name of the Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("foo", [1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).name + 'foo' + """ + return self._compliant_series.name + + def ewm_mean( + self, + *, + com: float | None = None, + span: float | None = None, + half_life: float | None = None, + alpha: float | None = None, + adjust: bool = True, + min_samples: int = 1, + ignore_nulls: bool = False, + ) -> Self: + r"""Compute exponentially-weighted moving average. + + Arguments: + com: Specify decay in terms of center of mass, $\gamma$, with
$\alpha = \frac{1}{1+\gamma}\forall\gamma\geq0$ + span: Specify decay in terms of span, $\theta$, with
$\alpha = \frac{2}{\theta + 1} \forall \theta \geq 1$ + half_life: Specify decay in terms of half-life, $\tau$, with
$\alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \tau } \right\} \forall \tau > 0$ + alpha: Specify smoothing factor alpha directly, $0 < \alpha \leq 1$. + adjust: Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings + + - When `adjust=True` (the default) the EW function is calculated + using weights $w_i = (1 - \alpha)^i$ + - When `adjust=False` the EW function is calculated recursively by + $$ + y_0=x_0 + $$ + $$ + y_t = (1 - \alpha)y_{t - 1} + \alpha x_t + $$ + min_samples: Minimum number of observations in window required to have a value (otherwise result is null). + ignore_nulls: Ignore missing values when calculating weights. + + - When `ignore_nulls=False` (default), weights are based on absolute + positions. + For example, the weights of $x_0$ and $x_2$ used in + calculating the final weighted average of $[x_0, None, x_2]$ are + $(1-\alpha)^2$ and $1$ if `adjust=True`, and + $(1-\alpha)^2$ and $\alpha$ if `adjust=False`. + - When `ignore_nulls=True`, weights are based + on relative positions. For example, the weights of + $x_0$ and $x_2$ used in calculating the final weighted + average of $[x_0, None, x_2]$ are + $1-\alpha$ and $1$ if `adjust=True`, + and $1-\alpha$ and $\alpha$ if `adjust=False`. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series(name="a", data=[1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).ewm_mean( + ... com=1, ignore_nulls=False + ... ).to_native() + 0 1.000000 + 1 1.666667 + 2 2.428571 + Name: a, dtype: float64 + """ + return self._with_compliant( + self._compliant_series.ewm_mean( + com=com, + span=span, + half_life=half_life, + alpha=alpha, + adjust=adjust, + min_samples=min_samples, + ignore_nulls=ignore_nulls, + ) + ) + + def cast(self, dtype: IntoDType) -> Self: + """Cast between data types. + + Arguments: + dtype: Data type that the object will be cast into. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[True, False, True]]) + >>> nw.from_native(s_native, series_only=True).cast(nw.Int64).to_native() + + [ + [ + 1, + 0, + 1 + ] + ] + """ + _validate_dtype(dtype) + return self._with_compliant(self._compliant_series.cast(dtype)) + + def to_frame(self) -> DataFrame[Any]: + """Convert to dataframe. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("a", [1, 2]) + >>> nw.from_native(s_native, series_only=True).to_frame().to_native() + shape: (2, 1) + ┌─────┐ + │ a │ + │ --- │ + │ i64 │ + ╞═════╡ + │ 1 │ + │ 2 │ + └─────┘ + """ + return self._dataframe(self._compliant_series.to_frame(), level=self._level) + + def to_list(self) -> list[Any]: + """Convert to list. + + Notes: + This function converts to Python scalars. It's typically + more efficient to keep your data in the format native to + your original dataframe, so we recommend only calling this + when you absolutely need to. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).to_list() + [1, 2, 3] + """ + return self._compliant_series.to_list() + + def mean(self) -> float: + """Reduce this Series to the mean value. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1.2, 4.2]) + >>> nw.from_native(s_native, series_only=True).mean() + np.float64(2.7) + """ + return self._compliant_series.mean() + + def median(self) -> float: + """Reduce this Series to the median value. + + Notes: + Results might slightly differ across backends due to differences in the underlying algorithms used to compute the median. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[5, 3, 8]]) + >>> nw.from_native(s_native, series_only=True).median() + 5.0 + """ + return self._compliant_series.median() + + def skew(self) -> float | None: + """Calculate the sample skewness of the Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 1, 2, 10, 100]) + >>> nw.from_native(s_native, series_only=True).skew() + 1.4724267269058975 + + Notes: + The skewness is a measure of the asymmetry of the probability distribution. + A perfectly symmetric distribution has a skewness of 0. + """ + return self._compliant_series.skew() + + def kurtosis(self) -> float | None: + """Compute the kurtosis (Fisher's definition) without bias correction. + + Kurtosis is the fourth central moment divided by the square of the variance. + The Fisher's definition is used where 3.0 is subtracted from the result to give 0.0 for a normal distribution. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 1, 2, 10, 100]) + >>> nw.from_native(s_native, series_only=True).kurtosis() + 0.2106571340718002 + """ + return self._compliant_series.kurtosis() + + def count(self) -> int: + """Returns the number of non-null elements in the Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> nw.from_native(s_native, series_only=True).count() + 2 + """ + return self._compliant_series.count() + + def any(self) -> bool: + """Return whether any of the values in the Series are True. + + If there are no non-null elements, the result is `False`. + + Notes: + Only works on Series of data type Boolean. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([False, True, False]) + >>> nw.from_native(s_native, series_only=True).any() + np.True_ + """ + return self._compliant_series.any() + + def all(self) -> bool: + """Return whether all values in the Series are True. + + If there are no non-null elements, the result is `True`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[False, True, False]]) + >>> nw.from_native(s_native, series_only=True).all() + False + """ + return self._compliant_series.all() + + def min(self) -> Any: + """Get the minimal value in this Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).min() + 1 + """ + return self._compliant_series.min() + + def max(self) -> Any: + """Get the maximum value in this Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).max() + np.int64(3) + """ + return self._compliant_series.max() + + def arg_min(self) -> int: + """Returns the index of the minimum value. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).arg_min() + 0 + """ + return self._compliant_series.arg_min() + + def arg_max(self) -> int: + """Returns the index of the maximum value. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).arg_max() + 2 + """ + return self._compliant_series.arg_max() + + def sum(self) -> float: + """Reduce this Series to the sum value. + + If there are no non-null elements, the result is zero. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).sum() + 6 + """ + return self._compliant_series.sum() + + def std(self, *, ddof: int = 1) -> float: + """Get the standard deviation of this Series. + + Arguments: + ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, + where N represents the number of elements. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).std() + 1.0 + """ + return self._compliant_series.std(ddof=ddof) + + def var(self, *, ddof: int = 1) -> float: + """Get the variance of this Series. + + Arguments: + ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, + where N represents the number of elements. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native(s_native, series_only=True).var() + 1.0 + """ + return self._compliant_series.var(ddof=ddof) + + def clip( + self, + lower_bound: Self | NumericLiteral | TemporalLiteral | None = None, + upper_bound: Self | NumericLiteral | TemporalLiteral | None = None, + ) -> Self: + r"""Clip values in the Series. + + Arguments: + lower_bound: Lower bound value. + upper_bound: Upper bound value. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([-1, 1, -3, 3, -5, 5]) + >>> nw.from_native(s_native, series_only=True).clip(-1, 3).to_native() + 0 -1 + 1 1 + 2 -1 + 3 3 + 4 -1 + 5 3 + dtype: int64 + """ + if lower_bound is None: + return self._with_compliant( + self._compliant_series.clip_upper( + upper_bound=self._extract_native(upper_bound) + ) + ) + if upper_bound is None: + return self._with_compliant( + self._compliant_series.clip_lower( + lower_bound=self._extract_native(lower_bound) + ) + ) + return self._with_compliant( + self._compliant_series.clip( + lower_bound=self._extract_native(lower_bound), + upper_bound=self._extract_native(upper_bound), + ) + ) + + def first(self) -> PythonLiteral: + """Get the first element of the Series. + + Returns: + A scalar value or `None` if the Series is empty. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> s_nw.first() + 1 + >>> s_nw.filter(s_nw > 5).first() is None + True + """ + return self._compliant_series.first() + + def last(self) -> PythonLiteral: + """Get the last element of the Series. + + Returns: + A scalar value or `None` if the Series is empty. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> s_nw.last() + 3 + >>> s_nw.filter(s_nw > 5).last() is None + True + """ + return self._compliant_series.last() + + def is_in(self, other: Any) -> Self: + """Check if the elements of this Series are in the other sequence. + + Arguments: + other: Sequence of primitive type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.is_in([3, 2, 8]).to_native() # doctest: +ELLIPSIS + + [ + [ + false, + true, + true + ] + ] + """ + return self._with_compliant( + self._compliant_series.is_in(to_native(other, pass_through=True)) + ) + + def arg_true(self) -> Self: + """Find elements where boolean Series is True. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, None, None, 2]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_null().arg_true().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [u32] + [ + 1 + 2 + ] + """ + return self._with_compliant(self._compliant_series.arg_true()) + + def drop_nulls(self) -> Self: + """Drop null values. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([2, 4, None, 3, 5]) + >>> nw.from_native(s_native, series_only=True).drop_nulls().to_native() + 0 2.0 + 1 4.0 + 3 3.0 + 4 5.0 + dtype: float64 + """ + return self._with_compliant(self._compliant_series.drop_nulls()) + + def abs(self) -> Self: + """Calculate the absolute value of each element. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[2, -4, 3]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).abs().to_native() # doctest: +ELLIPSIS + + [ + [ + 2, + 4, + 3 + ] + ] + """ + return self._with_compliant(self._compliant_series.abs()) + + def cum_sum(self, *, reverse: bool = False) -> Self: + """Calculate the cumulative sum. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([2, 4, 3]) + >>> nw.from_native(s_native, series_only=True).cum_sum().to_native() + 0 2 + 1 6 + 2 9 + dtype: int64 + """ + return self._with_compliant(self._compliant_series.cum_sum(reverse=reverse)) + + def unique(self, *, maintain_order: bool = False) -> Self: + """Returns unique values of the series. + + Arguments: + maintain_order: Keep the same order as the original series. This may be more + expensive to compute. Settings this to `True` blocks the possibility + to run on the streaming engine for Polars. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([2, 4, 4, 6]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.unique( + ... maintain_order=True + ... ).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [i64] + [ + 2 + 4 + 6 + ] + """ + return self._with_compliant( + self._compliant_series.unique(maintain_order=maintain_order) + ) + + def diff(self) -> Self: + """Calculate the difference with the previous element, for each element. + + Notes: + pandas may change the dtype here, for example when introducing missing + values in an integer column. To ensure, that the dtype doesn't change, + you may want to use `fill_null` and `cast`. For example, to calculate + the diff and fill missing values with `0` in a Int64 column, you could + do: + + s.diff().fill_null(0).cast(nw.Int64) + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[2, 4, 3]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).diff().to_native() # doctest: +ELLIPSIS + + [ + [ + null, + 2, + -1 + ] + ] + """ + return self._with_compliant(self._compliant_series.diff()) + + def shift(self, n: int) -> Self: + """Shift values by `n` positions. + + Arguments: + n: Number of indices to shift forward. If a negative value is passed, + values are shifted in the opposite direction instead. + + Notes: + pandas may change the dtype here, for example when introducing missing + values in an integer column. To ensure, that the dtype doesn't change, + you may want to use `fill_null` and `cast`. For example, to shift + and fill missing values with `0` in a Int64 column, you could + do: + + s.shift(1).fill_null(0).cast(nw.Int64) + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([2, 4, 3]) + >>> nw.from_native(s_native, series_only=True).shift(1).to_native() + 0 NaN + 1 2.0 + 2 4.0 + dtype: float64 + """ + ensure_type(n, int, param_name="n") + + return self._with_compliant(self._compliant_series.shift(n)) + + def sample( + self, + n: int | None = None, + *, + fraction: float | None = None, + with_replacement: bool = False, + seed: int | None = None, + ) -> Self: + """Sample randomly from this Series. + + Arguments: + n: Number of items to return. Cannot be used with fraction. + fraction: Fraction of items to return. Cannot be used with n. + with_replacement: Allow values to be sampled more than once. + seed: Seed for the random number generator. If set to None (default), a random + seed is generated for each sample operation. + + Notes: + The `sample` method returns a Series with a specified number of + randomly selected items chosen from this Series. + The results are not consistent across libraries. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3, 4]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sample( + ... fraction=1.0, with_replacement=True + ... ).to_native() # doctest: +SKIP + shape: (4,) + Series: '' [i64] + [ + 1 + 4 + 3 + 4 + ] + """ + return self._with_compliant( + self._compliant_series.sample( + n=n, fraction=fraction, with_replacement=with_replacement, seed=seed + ) + ) + + def alias(self, name: str) -> Self: + """Rename the Series. + + Notes: + This method is very cheap, but does not guarantee that data + will be copied. For example: + + ```python + s1: nw.Series + s2 = s1.alias("foo") + arr = s2.to_numpy() + arr[0] = 999 + ``` + + may (depending on the backend, and on the version) result in + `s1`'s data being modified. We recommend: + + - if you need to alias an object and don't need the original + one around any more, just use `alias` without worrying about it. + - if you were expecting `alias` to copy data, then explicitly call + `.clone` before calling `alias`. + + Arguments: + name: The new name. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3], name="foo") + >>> nw.from_native(s_native, series_only=True).alias("bar").to_native() + 0 1 + 1 2 + 2 3 + Name: bar, dtype: int64 + """ + return self._with_compliant(self._compliant_series.alias(name=name)) + + def rename(self, name: str) -> Self: + """Rename the Series. + + Alias for `Series.alias()`. + + Notes: + This method is very cheap, but does not guarantee that data + will be copied. For example: + + ```python + s1: nw.Series + s2 = s1.rename("foo") + arr = s2.to_numpy() + arr[0] = 999 + ``` + + may (depending on the backend, and on the version) result in + `s1`'s data being modified. We recommend: + + - if you need to rename an object and don't need the original + one around any more, just use `rename` without worrying about it. + - if you were expecting `rename` to copy data, then explicitly call + `.clone` before calling `rename`. + + Arguments: + name: The new name. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("foo", [1, 2, 3]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.rename("bar").to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: 'bar' [i64] + [ + 1 + 2 + 3 + ] + """ + return self.alias(name=name) + + def replace_strict( + self, + old: Sequence[Any] | Mapping[Any, Any], + new: Sequence[Any] | None = None, + *, + default: Any | NoDefault = no_default, + return_dtype: IntoDType | None = None, + ) -> Self: + """Replace all values by different values. + + Arguments: + old: Sequence of values to replace. It also accepts a mapping of values to + their replacement as syntactic sugar for + `replace_strict(old=list(mapping.keys()), new=list(mapping.values()))`. + new: Sequence of values to replace by. Length must match the length of `old`. + default: Set values that were not replaced to this value. If no default is + specified, (default), an error is raised if any values were not replaced. + Accepts expression input. Non-expression inputs are parsed as literals. + return_dtype: The data type of the resulting expression. If set to `None` + (default), the data type is determined automatically based on the other + inputs. + + Raises: + InvalidOperationError: If any non-null values in the original column were not + replaced, and no default was specified. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([3, 0, 1, 2], name="a") + >>> nw.from_native(s_native, series_only=True).replace_strict( + ... [0, 1, 2, 3], ["zero", "one", "two", "three"], return_dtype=nw.String + ... ).to_native() + 0 three + 1 zero + 2 one + 3 two + Name: a, dtype: str + + Replace values and set a default for values not in the mapping: + + >>> s_native = pd.Series([1, 2, 3, 4], name="a") + >>> s_default = pd.Series(["beluga", "narwhal", "orca", "vaquita"]) + >>> nw.from_native(s_native, series_only=True).replace_strict( + ... {1: "one", 2: "two"}, + ... default=nw.from_native(s_default, series_only=True), + ... return_dtype=nw.String, + ... ).to_native() + 0 one + 1 two + 2 orca + 3 vaquita + Name: a, dtype: str + """ + if new is None: + if not isinstance(old, Mapping): + msg = "`new` argument is required if `old` argument is not a Mapping type" + raise TypeError(msg) + + new = list(old.values()) + old = list(old.keys()) + + assert isinstance(new, Sequence) # noqa: S101, help mypy + assert isinstance(old, Sequence) # noqa: S101, help mypy + + return self._with_compliant( + self._compliant_series.replace_strict( + old=old, + new=new, + default=self._extract_native(default), + return_dtype=return_dtype, + ) + ) + + def sort(self, *, descending: bool = False, nulls_last: bool = False) -> Self: + """Sort this Series. Place null values first. + + Arguments: + descending: Sort in descending order. + nulls_last: Place null values last instead of first. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([5, None, 1, 2]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sort(descending=True).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [i64] + [ + null + 5 + 2 + 1 + ] + """ + return self._with_compliant( + self._compliant_series.sort(descending=descending, nulls_last=nulls_last) + ) + + def is_null(self) -> Self: + """Returns a boolean Series indicating which values are null. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_null().to_native() # doctest:+ELLIPSIS + + [ + [ + false, + false, + true + ] + ] + """ + return self._with_compliant(self._compliant_series.is_null()) + + def is_nan(self) -> Self: + """Returns a boolean Series indicating which values are NaN. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([0.0, None, 2.0], dtype="Float64") + >>> nw.from_native(s_native, series_only=True).is_nan().to_native() + 0 False + 1 + 2 False + dtype: boolean + """ + return self._with_compliant(self._compliant_series.is_nan()) + + def fill_null( + self, + value: Self | NonNestedLiteral = None, + strategy: FillNullStrategy | None = None, + limit: int | None = None, + ) -> Self: + """Fill null values using the specified value. + + Arguments: + value: Value used to fill null values. + strategy: Strategy used to fill null values. + limit: Number of consecutive null values to fill when using the 'forward' or 'backward' strategy. + + Notes: + - pandas handles null values differently from other libraries. + See [null_handling](../concepts/null_handling.md/) + for reference. + - For pandas Series of `object` dtype, `fill_null` will not automatically change the + Series' dtype as pandas used to do. Explicitly call `cast` if you want the dtype to change. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, None]) + >>> + >>> nw.from_native(s_native, series_only=True).fill_null(5).to_native() + 0 1.0 + 1 2.0 + 2 5.0 + dtype: float64 + + Or using a strategy: + + >>> nw.from_native(s_native, series_only=True).fill_null( + ... strategy="forward", limit=1 + ... ).to_native() + 0 1.0 + 1 2.0 + 2 2.0 + dtype: float64 + """ + if value is not None and strategy is not None: + msg = "cannot specify both `value` and `strategy`" + raise ValueError(msg) + if value is None and strategy is None: + msg = "must specify either a fill `value` or `strategy`" + raise ValueError(msg) + if strategy is not None and strategy not in {"forward", "backward"}: + msg = f"strategy not supported: {strategy}" + raise ValueError(msg) + return self._with_compliant( + self._compliant_series.fill_null( + value=self._extract_native(value), strategy=strategy, limit=limit + ) + ) + + def fill_nan(self, value: float | None) -> Self: + """Fill floating point NaN values with given value. + + Arguments: + value: Value used to fill NaN values. + + Notes: + This function only fills `'NaN'` values, not null ones, except for pandas + which doesn't distinguish between them. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([1.0, 2.0, float("nan"), None]) + >>> result = nw.from_native(s_native, series_only=True).fill_nan(0) + >>> result.to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [f64] + [ + 1.0 + 2.0 + 0.0 + null + ] + """ + return self._with_compliant( + self._compliant_series.fill_nan(value=self._extract_native(value)) + ) + + def is_between( + self, + lower_bound: Any | Self, + upper_bound: Any | Self, + closed: ClosedInterval = "both", + ) -> Self: + """Get a boolean mask of the values that are between the given lower/upper bounds. + + Arguments: + lower_bound: Lower bound value. + upper_bound: Upper bound value. + closed: Define which sides of the interval are closed (inclusive). Options are {"left", "right", "none", "both"}. + + Notes: + If the value of the `lower_bound` is greater than that of the `upper_bound`, + then the values will be False, as no value can satisfy the condition. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3, 4, 5]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.is_between(2, 4, "right").to_native() # doctest: +ELLIPSIS + + [ + [ + false, + false, + true, + true, + false + ] + ] + """ + return self._with_compliant( + self._compliant_series.is_between( + self._extract_native(lower_bound), + self._extract_native(upper_bound), + closed=closed, + ) + ) + + def n_unique(self) -> int: + """Count the number of unique values. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 2, 3]) + >>> nw.from_native(s_native, series_only=True).n_unique() + 3 + """ + return self._compliant_series.n_unique() + + def to_numpy(self) -> _1DArray: + """Convert to numpy. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3], name="a") + >>> nw.from_native(s_native, series_only=True).to_numpy() + array([1, 2, 3]...) + """ + return self._compliant_series.to_numpy(None, copy=None) + + def to_pandas(self) -> pd.Series[Any]: + """Convert to pandas Series. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series("a", [1, 2, 3]) + >>> nw.from_native(s_native, series_only=True).to_pandas() + 0 1 + 1 2 + 2 3 + Name: a, dtype: int64 + """ + return self._compliant_series.to_pandas() + + def to_polars(self) -> pl.Series: + """Convert to polars Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).to_polars() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [i64] + [ + 1 + 2 + 3 + ] + """ + return self._compliant_series.to_polars() + + def __add__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__add__(self._extract_native(other)) + ) + + def __radd__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__radd__(self._extract_native(other)) + ) + + def __sub__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__sub__(self._extract_native(other)) + ) + + def __rsub__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rsub__(self._extract_native(other)) + ) + + def __mul__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__mul__(self._extract_native(other)) + ) + + def __rmul__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rmul__(self._extract_native(other)) + ) + + def __truediv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__truediv__(self._extract_native(other)) + ) + + def __rtruediv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rtruediv__(self._extract_native(other)) + ) + + def __floordiv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__floordiv__(self._extract_native(other)) + ) + + def __rfloordiv__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rfloordiv__(self._extract_native(other)) + ) + + def __pow__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__pow__(self._extract_native(other)) + ) + + def __rpow__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rpow__(self._extract_native(other)) + ) + + def __mod__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__mod__(self._extract_native(other)) + ) + + def __rmod__(self, other: object) -> Self: + return self._with_compliant( + self._compliant_series.__rmod__(self._extract_native(other)) + ) + + def __eq__(self, other: object) -> Self: # type: ignore[override] + return self._with_compliant( + self._compliant_series.__eq__(self._extract_native(other)) + ) + + def __ne__(self, other: object) -> Self: # type: ignore[override] + return self._with_compliant( + self._compliant_series.__ne__(self._extract_native(other)) + ) + + def __gt__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__gt__(self._extract_native(other)) + ) + + def __ge__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__ge__(self._extract_native(other)) + ) + + def __lt__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__lt__(self._extract_native(other)) + ) + + def __le__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__le__(self._extract_native(other)) + ) + + def __and__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__and__(self._extract_native(other)) + ) + + def __rand__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__rand__(self._extract_native(other)) + ) + + def __or__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__or__(self._extract_native(other)) + ) + + def __ror__(self, other: Any) -> Self: + return self._with_compliant( + self._compliant_series.__ror__(self._extract_native(other)) + ) + + # unary + def __invert__(self) -> Self: + return self._with_compliant(self._compliant_series.__invert__()) + + def filter(self, predicate: Any) -> Self: + """Filter elements in the Series based on a condition. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([4, 10, 15, 34, 50]) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> s_nw.filter(s_nw > 10).to_native() + 2 15 + 3 34 + 4 50 + dtype: int64 + """ + return self._with_compliant( + self._compliant_series.filter(self._extract_native(predicate)) + ) + + # --- descriptive --- + def is_duplicated(self) -> Self: + r"""Get a mask of all duplicated rows in the Series. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3, 1]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_duplicated().to_native() # doctest: +ELLIPSIS + + [ + [ + true, + false, + false, + true + ] + ] + """ + return self._with_compliant(self._compliant_series.is_duplicated()) + + def is_empty(self) -> bool: + r"""Check if the series is empty. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3]) + >>> s_nw = nw.from_native(s_native, series_only=True) + + >>> s_nw.is_empty() + False + >>> s_nw.filter(s_nw > 10).is_empty() + True + """ + return self._compliant_series.is_empty() + + def is_unique(self) -> Self: + r"""Get a mask of all unique rows in the Series. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3, 1]) + >>> nw.from_native(s_native, series_only=True).is_unique().to_native() + 0 False + 1 True + 2 True + 3 False + dtype: bool + """ + return self._with_compliant(self._compliant_series.is_unique()) + + def null_count(self) -> int: + r"""Count the number of null values. + + Notes: + pandas handles null values differently from Polars and PyArrow. + See [null_handling](../concepts/null_handling.md/) for reference. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, None, None]]) + >>> nw.from_native(s_native, series_only=True).null_count() + 2 + """ + return self._compliant_series.null_count() + + def is_first_distinct(self) -> Self: + r"""Return a boolean mask indicating the first occurrence of each distinct value. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 1, 2, 3, 2]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_first_distinct().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (5,) + Series: '' [bool] + [ + true + false + true + true + false + ] + """ + return self._with_compliant(self._compliant_series.is_first_distinct()) + + def is_last_distinct(self) -> Self: + r"""Return a boolean mask indicating the last occurrence of each distinct value. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 1, 2, 3, 2]) + >>> nw.from_native(s_native, series_only=True).is_last_distinct().to_native() + 0 False + 1 True + 2 False + 3 True + 4 True + dtype: bool + """ + return self._with_compliant(self._compliant_series.is_last_distinct()) + + def is_sorted(self, *, descending: bool = False) -> bool: + r"""Check if the Series is sorted. + + Arguments: + descending: Check if the Series is sorted in descending order. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[3, 2, 1]]) + >>> s_nw = nw.from_native(s_native, series_only=True) + + >>> s_nw.is_sorted(descending=False) + False + + >>> s_nw.is_sorted(descending=True) + True + """ + return self._compliant_series.is_sorted(descending=descending) + + def value_counts( + self, + *, + sort: bool = False, + parallel: bool = False, + name: str | None = None, + normalize: bool = False, + ) -> DataFrame[Any]: + r"""Count the occurrences of unique values. + + Arguments: + sort: Sort the output by count in descending order. If set to False (default), + the order of the output is random. + parallel: Execute the computation in parallel. Used for Polars only. + name: Give the resulting count column a specific name; if `normalize` is True + defaults to "proportion", otherwise defaults to "count". + normalize: If true gives relative frequencies of the unique values + + - The original values as first column + - Either count or proportion as second column, depending on normalize parameter. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 1, 2, 3, 2], name="s") + >>> nw.from_native(s_native, series_only=True).value_counts( + ... sort=True + ... ).to_native() + s count + 0 1 2 + 1 2 2 + 2 3 1 + """ + return self._dataframe( + self._compliant_series.value_counts( + sort=sort, parallel=parallel, name=name, normalize=normalize + ), + level=self._level, + ) + + def quantile( + self, quantile: float, interpolation: RollingInterpolationMethod + ) -> float: + """Get quantile value of the series. + + Note: + pandas and Polars may have implementation differences for a given interpolation method. + + Arguments: + quantile: Quantile between 0.0 and 1.0. + interpolation: Interpolation method. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series(list(range(50))) + >>> s_nw = nw.from_native(s_native, series_only=True) + >>> [ + ... s_nw.quantile(quantile=q, interpolation="nearest") + ... for q in (0.1, 0.25, 0.5, 0.75, 0.9) + ... ] + [5.0, 12.0, 25.0, 37.0, 44.0] + """ + return self._compliant_series.quantile( + quantile=quantile, interpolation=interpolation + ) + + def zip_with(self, mask: Self, other: Self) -> Self: + """Take values from self or other based on the given mask. + + Where mask evaluates true, take values from self. Where mask evaluates false, + take values from other. + + Arguments: + mask: Boolean Series + other: Series of same type. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> data_native = pa.chunked_array([[1, 2, 3, 4, 5]]) + >>> other_native = pa.chunked_array([[5, 4, 3, 2, 1]]) + >>> mask_native = pa.chunked_array([[True, False, True, False, True]]) + >>> + >>> data_nw = nw.from_native(data_native, series_only=True) + >>> other_nw = nw.from_native(other_native, series_only=True) + >>> mask_nw = nw.from_native(mask_native, series_only=True) + >>> + >>> data_nw.zip_with(mask_nw, other_nw).to_native() # doctest: +ELLIPSIS + + [ + [ + 1, + 4, + 3, + 2, + 5 + ] + ] + """ + return self._with_compliant( + self._compliant_series.zip_with( + self._extract_native(mask), self._extract_native(other) + ) + ) + + def item(self, index: int | None = None) -> Any: + r"""Return the Series as a scalar, or return the element at the given index. + + If no index is provided, this is equivalent to `s[0]`, with a check + that the shape is (1,). With an index, this is equivalent to `s[index]`. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> nw.from_native(pl.Series("a", [1]), series_only=True).item() + 1 + + >>> nw.from_native(pl.Series("a", [9, 8, 7]), series_only=True).item(-1) + 7 + """ + if index is not None and index >= len(self): + msg = f"index {index} out of range for series of length {len(self)}" + raise IndexError(msg) + return self._compliant_series.item(index=index) + + def head(self, n: int = 10) -> Self: + r"""Get the first `n` rows. + + Arguments: + n: Number of rows to return. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series(list(range(10))) + >>> nw.from_native(s_native, series_only=True).head(3).to_native() + 0 0 + 1 1 + 2 2 + dtype: int64 + """ + return self._with_compliant(self._compliant_series.head(n)) + + def tail(self, n: int = 10) -> Self: + r"""Get the last `n` rows. + + Arguments: + n: Number of rows to return. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([list(range(10))]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.tail(3).to_native() # doctest: +ELLIPSIS + + [ + [ + 7, + 8, + 9 + ] + ] + """ + return self._with_compliant(self._compliant_series.tail(n)) + + def round(self, decimals: int = 0) -> Self: + r"""Round underlying floating point data by `decimals` digits. + + Arguments: + decimals: Number of decimals to round by. + + Notes: + For values exactly halfway between rounded decimal values pandas behaves differently than Polars and Arrow. + + pandas rounds to the nearest even value (e.g. -0.5 and 0.5 round to 0.0, 1.5 and 2.5 round to 2.0, 3.5 and + 4.5 to 4.0, etc..). + + Polars and Arrow round away from 0 (e.g. -0.5 to -1.0, 0.5 to 1.0, 1.5 to 2.0, 2.5 to 3.0, etc..). + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1.12345, 2.56789, 3.901234]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.round(1).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [f64] + [ + 1.1 + 2.6 + 3.9 + ] + """ + return self._with_compliant(self._compliant_series.round(decimals)) + + def floor(self) -> Self: + r"""Compute the numerical floor. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[1.1, 4.3, -1.3]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.floor().to_native() # doctest:+ELLIPSIS + + [ + [ + 1, + 4, + -2 + ] + ] + """ + return self._with_compliant(self._compliant_series.floor()) + + def ceil(self) -> Self: + r"""Compute the numerical ceiling. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[1.1, 4.3, -1.3]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.ceil().to_native() # doctest:+ELLIPSIS + + [ + [ + 2, + 5, + -1 + ] + ] + """ + return self._with_compliant(self._compliant_series.ceil()) + + def to_dummies( + self, *, separator: str = "_", drop_first: bool = False + ) -> DataFrame[Any]: + r"""Get dummy/indicator variables. + + Arguments: + separator: Separator/delimiter used when generating column names. + drop_first: Remove the first category from the variable being encoded. + + Notes: + pandas and Polars handle null values differently. Polars distinguishes + between NaN and Null, whereas pandas doesn't. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1, 2, 3], name="a") + >>> s_nw = nw.from_native(s_native, series_only=True) + + >>> s_nw.to_dummies(drop_first=False).to_native() + a_1 a_2 a_3 + 0 1 0 0 + 1 0 1 0 + 2 0 0 1 + + >>> s_nw.to_dummies(drop_first=True).to_native() + a_2 a_3 + 0 0 0 + 1 1 0 + 2 0 1 + """ + return self._dataframe( + self._compliant_series.to_dummies(separator=separator, drop_first=drop_first), + level=self._level, + ) + + def gather_every(self, n: int, offset: int = 0) -> Self: + r"""Take every nth value in the Series and return as new Series. + + Arguments: + n: Gather every *n*-th row. + offset: Starting index. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 2, 3, 4]]) + >>> nw.from_native(s_native, series_only=True).gather_every( + ... n=2, offset=1 + ... ).to_native() # doctest:+ELLIPSIS + + [ + [ + 2, + 4 + ] + ] + """ + return self._with_compliant( + self._compliant_series.gather_every(n=n, offset=offset) + ) + + def to_arrow(self) -> pa.Array[Any]: + r"""Convert to arrow. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 2, 3, 4]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).to_arrow() # doctest:+NORMALIZE_WHITESPACE + + [ + 1, + 2, + 3, + 4 + ] + """ + return self._compliant_series.to_arrow() + + @overload + def mode(self, *, keep: Literal["all"] = "all") -> Self: ... + + @overload + def mode(self, *, keep: Literal["any"]) -> NonNestedLiteral: ... + + def mode(self, *, keep: ModeKeepStrategy = "all") -> Self | NonNestedLiteral: + r"""Compute the most occurring value(s). + + Can return multiple values. + + Note: + For `keep="any"` a scalar is returned, while for `keep="all"` a Series in + returned even in the case of unimodal values. + + Arguments: + keep: Whether to keep all modes or any mode found. Remark that `keep='any'` + is not deterministic for multimodal values. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 1, 2, 2, 3]) + >>> nw.from_native(s_native, series_only=True).mode().sort().to_native() + 0 1 + 1 2 + dtype: int64 + """ + _supported_keep_values = ("all", "any") + if keep not in _supported_keep_values: # pragma: no cover + msg = f"`keep` must be one of {_supported_keep_values}, found '{keep}'" + raise ValueError(msg) + + result = self._with_compliant(self._compliant_series.mode(keep=keep)) + return result.item(0) if keep == "any" else result + + def is_finite(self) -> Self: + """Returns a boolean Series indicating which values are finite. + + Warning: + Different backend handle null values differently. `is_finite` will return + False for NaN and Null's in the Dask and pandas non-nullable backend, while + for Polars, PyArrow and pandas nullable backends null values are kept as such. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[float("nan"), float("inf"), 2.0, None]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).is_finite().to_native() # doctest: +ELLIPSIS + + [ + [ + false, + false, + true, + null + ] + ] + """ + return self._with_compliant(self._compliant_series.is_finite()) + + def cum_count(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative count of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series(["x", "k", None, "d"]) + >>> nw.from_native(s_native, series_only=True).cum_count( + ... reverse=True + ... ).to_native() # doctest:+NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [u32] + [ + 3 + 2 + 1 + 1 + ] + """ + return self._with_compliant(self._compliant_series.cum_count(reverse=reverse)) + + def cum_min(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative min of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([3, 1, None, 2]) + >>> nw.from_native(s_native, series_only=True).cum_min().to_native() + 0 3.0 + 1 1.0 + 2 NaN + 3 1.0 + dtype: float64 + """ + return self._with_compliant(self._compliant_series.cum_min(reverse=reverse)) + + def cum_max(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative max of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1, 3, None, 2]]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).cum_max().to_native() # doctest:+ELLIPSIS + + [ + [ + 1, + 3, + null, + 3 + ] + ] + """ + return self._with_compliant(self._compliant_series.cum_max(reverse=reverse)) + + def cum_prod(self, *, reverse: bool = False) -> Self: + r"""Return the cumulative product of the non-null values in the series. + + Arguments: + reverse: reverse the operation + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1, 3, None, 2]) + >>> nw.from_native( + ... s_native, series_only=True + ... ).cum_prod().to_native() # doctest:+NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [i64] + [ + 1 + 3 + null + 6 + ] + """ + return self._with_compliant(self._compliant_series.cum_prod(reverse=reverse)) + + def rolling_sum( + self, window_size: int, *, min_samples: int | None = None, center: bool = False + ) -> Self: + """Apply a rolling sum (moving sum) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their sum. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size` + center: Set the labels at the center of the window. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1.0, 2.0, 3.0, 4.0]) + >>> nw.from_native(s_native, series_only=True).rolling_sum( + ... window_size=2 + ... ).to_native() + 0 NaN + 1 3.0 + 2 5.0 + 3 7.0 + dtype: float64 + """ + window_size, min_samples_int = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_sum( + window_size=window_size, min_samples=min_samples_int, center=center + ) + ) + + def rolling_mean( + self, window_size: int, *, min_samples: int | None = None, center: bool = False + ) -> Self: + """Apply a rolling mean (moving mean) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their mean. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size` + center: Set the labels at the center of the window. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[1.0, 2.0, 3.0, 4.0]]) + >>> nw.from_native(s_native, series_only=True).rolling_mean( + ... window_size=2 + ... ).to_native() # doctest:+ELLIPSIS + + [ + [ + null, + 1.5, + 2.5, + 3.5 + ] + ] + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_mean( + window_size=window_size, min_samples=min_samples, center=center + ) + ) + + def rolling_var( + self, + window_size: int, + *, + min_samples: int | None = None, + center: bool = False, + ddof: int = 1, + ) -> Self: + """Apply a rolling variance (moving variance) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their variance. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size`. + center: Set the labels at the center of the window. + ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> + >>> s_native = pl.Series([1.0, 3.0, 1.0, 4.0]) + >>> nw.from_native(s_native, series_only=True).rolling_var( + ... window_size=2, min_samples=1 + ... ).to_native() # doctest:+NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [f64] + [ + null + 2.0 + 2.0 + 4.5 + ] + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_var( + window_size=window_size, min_samples=min_samples, center=center, ddof=ddof + ) + ) + + def rolling_std( + self, + window_size: int, + *, + min_samples: int | None = None, + center: bool = False, + ddof: int = 1, + ) -> Self: + """Apply a rolling standard deviation (moving standard deviation) over the values. + + A window of length `window_size` will traverse the values. The resulting values + will be aggregated to their standard deviation. + + The window at a given row will include the row itself and the `window_size - 1` + elements before it. + + Arguments: + window_size: The length of the window in number of elements. It must be a + strictly positive integer. + min_samples: The number of values in the window that should be non-null before + computing a result. If set to `None` (default), it will be set equal to + `window_size`. If provided, it must be a strictly positive integer, and + less than or equal to `window_size`. + center: Set the labels at the center of the window. + ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> + >>> s_native = pd.Series([1.0, 3.0, 1.0, 4.0]) + >>> nw.from_native(s_native, series_only=True).rolling_std( + ... window_size=2, min_samples=1 + ... ).to_native() + 0 NaN + 1 1.414214 + 2 1.414214 + 3 2.121320 + dtype: float64 + """ + window_size, min_samples = _validate_rolling_arguments( + window_size=window_size, min_samples=min_samples + ) + + if len(self) == 0: # pragma: no cover + return self + + return self._with_compliant( + self._compliant_series.rolling_std( + window_size=window_size, min_samples=min_samples, center=center, ddof=ddof + ) + ) + + def __iter__(self) -> Iterator[Any]: + yield from self._compliant_series.__iter__() + + def __contains__(self, other: Any) -> bool: + return self._compliant_series.__contains__(other) + + def rank(self, method: RankMethod = "average", *, descending: bool = False) -> Self: + """Assign ranks to data, dealing with ties appropriately. + + Notes: + The resulting dtype may differ between backends. + + Arguments: + method: The method used to assign ranks to tied elements. + The following methods are available (default is 'average') + + - *"average"*: The average of the ranks that would have been assigned to + all the tied values is assigned to each value. + - *"min"*: The minimum of the ranks that would have been assigned to all + the tied values is assigned to each value. (This is also referred to + as "competition" ranking.) + - *"max"*: The maximum of the ranks that would have been assigned to all + the tied values is assigned to each value. + - *"dense"*: Like "min", but the rank of the next highest element is + assigned the rank immediately after those assigned to the tied elements. + - *"ordinal"*: All values are given a distinct rank, corresponding to the + order that the values occur in the Series. + + descending: Rank in descending order. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> s_native = pa.chunked_array([[3, 6, 1, 1, 6]]) + >>> nw.from_native(s_native, series_only=True).rank( + ... method="dense" + ... ).to_native() # doctest:+ELLIPSIS + + [ + [ + 2, + 3, + 1, + 1, + 3 + ] + ] + """ + supported_rank_methods = {"average", "min", "max", "dense", "ordinal"} + if method not in supported_rank_methods: + msg = ( + "Ranking method must be one of {'average', 'min', 'max', 'dense', 'ordinal'}. " + f"Found '{method}'" + ) + raise ValueError(msg) + + return self._with_compliant( + self._compliant_series.rank(method=method, descending=descending) + ) + + def hist( + self, + bins: list[float] | None = None, + *, + bin_count: int | None = None, + include_breakpoint: bool = True, + ) -> DataFrame[Any]: + """Bin values into buckets and count their occurrences. + + Warning: + This functionality is considered **unstable**. It may be changed at any point + without it being considered a breaking change. + + Arguments: + bins: A monotonically increasing sequence of values. + bin_count: If no bins provided, this will be used to determine the distance of the bins. + include_breakpoint: Include a column that shows the intervals as categories. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 3, 8, 8, 2, 1, 3], name="a") + >>> nw.from_native(s_native, series_only=True).hist(bin_count=4) + ┌────────────────────┐ + | Narwhals DataFrame | + |--------------------| + | breakpoint count| + |0 2.75 3| + |1 4.50 2| + |2 6.25 0| + |3 8.00 2| + └────────────────────┘ + """ + if bins is not None: + if any(bins[i - 1] >= bins[i] for i in range(1, len(bins))): + msg = "bins must increase monotonically" + raise ComputeError(msg) + if bin_count is not None: + msg = f"can only provide one of `bin_count` or `bins`, got: {bin_count=}, {bins=}" + raise ComputeError(msg) + result = self._compliant_series.hist_from_bins( + bins=bins, include_breakpoint=include_breakpoint + ) + else: + # polars (v1.20) sets bin=10 if neither are provided. + default = 10 + bin_count = default if bin_count is None else bin_count + result = self._compliant_series.hist_from_bin_count( + bin_count=bin_count, include_breakpoint=include_breakpoint + ) + + return self._dataframe(result, level=self._level) + + def log(self, base: float = math.e) -> Self: + r"""Compute the logarithm to a given base. + + Arguments: + base: Given base, defaults to `e` + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 2, 4], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.log(base=2) + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 0.0 | + |1 1.0 | + |2 2.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.log(base=base)) + + def exp(self) -> Self: + r"""Compute the exponent. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([-1, 0, 1], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.exp() + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 0.367879 | + |1 1.000000 | + |2 2.718282 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.exp()) + + def sin(self) -> Self: + r"""Compute the element-wise value for the sine. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> from math import pi + >>> s_native = pd.Series([0, pi / 2, 3 * pi / 2], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sin() + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 0.0 | + |1 1.0 | + |2 -1.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.sin()) + + def cos(self) -> Self: + r"""Compute the element-wise value for the cosine. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> from math import pi + >>> s_native = pd.Series([0, pi / 2, 3 * pi / 2], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cos().round(4) + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 1.0 | + |1 0.0 | + |2 -0.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.cos()) + + def sqrt(self) -> Self: + r"""Compute the square root. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([1, 4, 9], name="a") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.sqrt() + ┌───────────────────────┐ + | Narwhals Series | + |-----------------------| + |0 1.0 | + |1 2.0 | + |2 3.0 | + |Name: a, dtype: float64| + └───────────────────────┘ + """ + return self._with_compliant(self._compliant_series.sqrt()) + + def is_close( + self, + other: Self | NumericLiteral, + *, + abs_tol: float = 0.0, + rel_tol: float = 1e-09, + nans_equal: bool = False, + ) -> Self: + r"""Get a boolean mask of the values being close to the other values. + + Two values `a` and `b` are considered close if the following condition holds: + + $$ + |a-b| \le max \{ \text{rel\_tol} \cdot max \{ |a|, |b| \}, \text{abs\_tol} \} + $$ + + Arguments: + other: Values to compare with. + abs_tol: Absolute tolerance. This is the maximum allowed absolute difference + between two values. Must be non-negative. + rel_tol: Relative tolerance. This is the maximum allowed difference between + two values, relative to the larger absolute value. Must be in the range + [0, 1). + nans_equal: Whether NaN values should be considered equal. + + Notes: + The implementation of this method is symmetric and mirrors the behavior of + `math.isclose`. Specifically note that this behavior is different to + `numpy.isclose`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> + >>> data = [1.0, float("inf"), 1.41, None, float("nan")] + >>> s_native = pa.chunked_array([data]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.is_close(1.4, abs_tol=0.1).to_native() # doctest:+ELLIPSIS + + [ + [ + false, + false, + true, + null, + false + ] + ] + """ + if not self.dtype.is_numeric(): + msg = ( + f"`is_close` operation not supported for dtype `{self.dtype}`\n\n" + "Hint: `is_close` is only supported for numeric types" + ) + raise InvalidOperationError(msg) + # Creating a temporary name if series is unnamed (possible in pandas-like scenario) + # as `select`-ing a column named `None` would break otherwise + orig_name = self.name + name_is_none = orig_name is None + tmp_name = "__nw_is_close__" if name_is_none else orig_name + expr = col(tmp_name).is_close( + other, abs_tol=abs_tol, rel_tol=rel_tol, nans_equal=nans_equal + ) + series = self.rename(tmp_name) if name_is_none else self + result = series.to_frame().select(expr).get_column(tmp_name) + result = result.rename(orig_name) if name_is_none else result + return cast("Self", result) + + @unstable + def any_value(self, *, ignore_nulls: bool = False) -> PythonLiteral: + """Get a random value from the column. + + Warning: + This functionality is considered **unstable** as it diverges from the polars API. + It may be changed at any point without it being considered a breaking change. + + Arguments: + ignore_nulls: Whether to ignore null values or not. + If `True` and there are no not-null elements, then `None` is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[1, 2, None]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.any_value(ignore_nulls=True) + 1 + """ + return self._compliant_series.any_value(ignore_nulls=ignore_nulls) + + @property + def str(self) -> SeriesStringNamespace[Self]: + return SeriesStringNamespace(self) + + @property + def dt(self) -> SeriesDateTimeNamespace[Self]: + return SeriesDateTimeNamespace(self) + + @property + def cat(self) -> SeriesCatNamespace[Self]: + return SeriesCatNamespace(self) + + @property + def list(self) -> SeriesListNamespace[Self]: + return SeriesListNamespace(self) + + @property + def struct(self) -> SeriesStructNamespace[Self]: + return SeriesStructNamespace(self) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/series_cat.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_cat.py new file mode 100644 index 0000000000000000000000000000000000000000..525d4eb1ff8762495b5ea49af6ddf6a0e3ea04d1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_cat.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from typing import Generic + +from narwhals.typing import SeriesT + + +class SeriesCatNamespace(Generic[SeriesT]): + def __init__(self, series: SeriesT) -> None: + self._narwhals_series = series + + def get_categories(self) -> SeriesT: + """Get unique categories from column. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["apple", "mango", "mango"], dtype="category") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.cat.get_categories().to_native() + 0 apple + 1 mango + dtype: str + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.cat.get_categories() + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/series_dt.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_dt.py new file mode 100644 index 0000000000000000000000000000000000000000..f808894c1a99ec0855cac22a80c2507f583fe570 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_dt.py @@ -0,0 +1,647 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic + +from narwhals.typing import SeriesT + +if TYPE_CHECKING: + from narwhals.typing import TimeUnit + + +class SeriesDateTimeNamespace(Generic[SeriesT]): + def __init__(self, series: SeriesT) -> None: + self._narwhals_series = series + + def date(self) -> SeriesT: + """Get the date in a datetime series. + + Raises: + NotImplementedError: If pandas default backend is being used. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [datetime(2012, 1, 7, 10, 20), datetime(2023, 3, 10, 11, 32)] + ... ).convert_dtypes(dtype_backend="pyarrow") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.date().to_native() + 0 2012-01-07 + 1 2023-03-10 + dtype: date32[day][pyarrow] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.date() + ) + + def year(self) -> SeriesT: + """Get the year in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([datetime(2012, 1, 7), datetime(2023, 3, 10)]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.year().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i32] + [ + 2012 + 2023 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.year() + ) + + def month(self) -> SeriesT: + """Gets the month in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([datetime(2012, 1, 7), datetime(2023, 3, 10)]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.month().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i8] + [ + 1 + 3 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.month() + ) + + def day(self) -> SeriesT: + """Extracts the day in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [[datetime(2022, 1, 1), datetime(2022, 1, 5)]] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.day().to_native() # doctest: +ELLIPSIS + + [ + [ + 1, + 5 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.day() + ) + + def hour(self) -> SeriesT: + """Extracts the hour in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [[datetime(2022, 1, 1, 5, 3), datetime(2022, 1, 5, 9, 12)]] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.hour().to_native() # doctest: +ELLIPSIS + + [ + [ + 5, + 9 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.hour() + ) + + def minute(self) -> SeriesT: + """Extracts the minute in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [datetime(2022, 1, 1, 5, 3), datetime(2022, 1, 5, 9, 12)] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.minute().to_native() + 0 3 + 1 12 + dtype: int32 + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.minute() + ) + + def second(self) -> SeriesT: + """Extracts the seconds in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [datetime(2022, 1, 1, 5, 3, 10), datetime(2022, 1, 5, 9, 12, 4)] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.second().to_native() + 0 10 + 1 4 + dtype: int32 + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.second() + ) + + def millisecond(self) -> SeriesT: + """Extracts the milliseconds in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [ + ... datetime(2022, 1, 1, 5, 3, 7, 400000), + ... datetime(2022, 1, 1, 5, 3, 7, 0), + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.millisecond().alias("datetime").to_native() + 0 400 + 1 0 + Name: datetime, dtype: int32 + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.millisecond() + ) + + def microsecond(self) -> SeriesT: + """Extracts the microseconds in a datetime series. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [ + ... datetime(2022, 1, 1, 5, 3, 7, 400000), + ... datetime(2022, 1, 1, 5, 3, 7, 0), + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.microsecond().alias("datetime").to_native() + 0 400000 + 1 0 + Name: datetime, dtype: int32 + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.microsecond() + ) + + def nanosecond(self) -> SeriesT: + """Extract the nanoseconds in a date series. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [ + ... datetime(2022, 1, 1, 5, 3, 7, 400000), + ... datetime(2022, 1, 1, 5, 3, 7, 0), + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.nanosecond().alias("datetime").to_native() + 0 400000000 + 1 0 + Name: datetime, dtype: int32 + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.nanosecond() + ) + + def ordinal_day(self) -> SeriesT: + """Get ordinal day. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [[datetime(2020, 1, 1), datetime(2020, 8, 3)]] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.ordinal_day().to_native() # doctest: +ELLIPSIS + + [ + [ + 1, + 216 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.ordinal_day() + ) + + def weekday(self) -> SeriesT: + """Extract the week day in a datetime series. + + Note that Monday = 1 and Sunday = 7. + + Examples: + >>> from datetime import datetime + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [[datetime(2020, 1, 1), datetime(2020, 8, 3)]] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.weekday().to_native() # doctest: +ELLIPSIS + + [ + [ + 3, + 1 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.weekday() + ) + + def total_minutes(self) -> SeriesT: + """Get total minutes. + + Notes: + The function outputs the total minutes in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series( + ... [timedelta(minutes=10), timedelta(minutes=20, seconds=40)] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.total_minutes().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 10 + 20 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.total_minutes() + ) + + def total_seconds(self) -> SeriesT: + """Get total seconds. + + Notes: + The function outputs the total seconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series( + ... [timedelta(minutes=10), timedelta(minutes=20, seconds=40)] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.total_seconds().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 600 + 1240 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.total_seconds() + ) + + def total_milliseconds(self) -> SeriesT: + """Get total milliseconds. + + Notes: + The function outputs the total milliseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series( + ... [ + ... timedelta(milliseconds=10), + ... timedelta(milliseconds=20, microseconds=40), + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.total_milliseconds().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 10 + 20 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.total_milliseconds() + ) + + def total_microseconds(self) -> SeriesT: + """Get total microseconds. + + Notes: + The function outputs the total microseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` in this case. + + Examples: + >>> from datetime import timedelta + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series( + ... [ + ... timedelta(microseconds=10), + ... timedelta(milliseconds=1, microseconds=200), + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.total_microseconds().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 10 + 1200 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.total_microseconds() + ) + + def total_nanoseconds(self) -> SeriesT: + """Get total nanoseconds. + + Notes: + The function outputs the total nanoseconds in the int dtype by default, + however, pandas may change the dtype to float when there are missing values, + consider using `fill_null()` in this case. + + Examples: + >>> from datetime import datetime + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series( + ... ["2024-01-01 00:00:00.000000001", "2024-01-01 00:00:00.000000002"] + ... ).str.to_datetime(time_unit="ns") + >>> s = nw.from_native(s_native, series_only=True) + >>> s.diff().dt.total_nanoseconds().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + null + 1 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.total_nanoseconds() + ) + + def to_string(self, format: str) -> SeriesT: + """Convert a Date/Time/Datetime series into a String series with the given format. + + Arguments: + format: Format string for converting the datetime to string. + + Notes: + Unfortunately, different libraries interpret format directives a bit + differently. + + - Chrono, the library used by Polars, uses `"%.f"` for fractional seconds, + whereas pandas and Python stdlib use `".%f"`. + - PyArrow interprets `"%S"` as "seconds, including fractional seconds" + whereas most other tools interpret it as "just seconds, as 2 digits". + --- + Therefore, we make the following adjustments. + + - for pandas-like libraries, we replace `"%S.%f"` with `"%S%.f"`. + - for PyArrow, we replace `"%S.%f"` with `"%S"`. + --- + Workarounds like these don't make us happy, and we try to avoid them as + much as possible, but here we feel like it's the best compromise. + + If you just want to format a date/datetime Series as a local datetime + string, and have it work as consistently as possible across libraries, + we suggest using: + + - `"%Y-%m-%dT%H:%M:%S%.f"` for datetimes + - `"%Y-%m-%d"` for dates + --- + Though note that, even then, different tools may return a different number + of trailing zeros. Nonetheless, this is probably consistent enough for + most applications. + + If you have an application where this is not enough, please open an issue + and let us know. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([datetime(2020, 3, 1), datetime(2020, 4, 1)]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.to_string("%Y/%m/%d") + ┌───────────────┐ + |Narwhals Series| + |---------------| + |0 2020/03/01| + |1 2020/04/01| + |dtype: str | + └───────────────┘ + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.to_string(format) + ) + + def replace_time_zone(self, time_zone: str | None) -> SeriesT: + """Replace time zone. + + Arguments: + time_zone: Target time zone. + + Examples: + >>> from datetime import datetime, timezone + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series( + ... [ + ... datetime(2024, 1, 1, tzinfo=timezone.utc), + ... datetime(2024, 1, 2, tzinfo=timezone.utc), + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.replace_time_zone( + ... "Asia/Kathmandu" + ... ).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [datetime[μs, Asia/Kathmandu]] + [ + 2024-01-01 00:00:00 +0545 + 2024-01-02 00:00:00 +0545 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.replace_time_zone(time_zone) + ) + + def convert_time_zone(self, time_zone: str) -> SeriesT: + """Convert time zone. + + If converting from a time-zone-naive column, then conversion happens + as if converting from UTC. + + Arguments: + time_zone: Target time zone. + + Examples: + >>> from datetime import datetime, timezone + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [ + ... datetime(2024, 1, 1, tzinfo=timezone.utc), + ... datetime(2024, 1, 2, tzinfo=timezone.utc), + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.convert_time_zone("Asia/Kathmandu").to_native() + 0 2024-01-01 05:45:00+05:45 + 1 2024-01-02 05:45:00+05:45 + dtype: datetime64[us, Asia/Kathmandu] + """ + if time_zone is None: + msg = "Target `time_zone` cannot be `None` in `convert_time_zone`. Please use `replace_time_zone(None)` if you want to remove the time zone." + raise TypeError(msg) + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.convert_time_zone(time_zone) + ) + + def timestamp(self, time_unit: TimeUnit) -> SeriesT: + """Return a timestamp in the given time unit. + + Arguments: + time_unit: One of + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + + Examples: + >>> from datetime import date + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series( + ... [date(2001, 1, 1), None, date(2001, 1, 3)], dtype="datetime64[ns]" + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.timestamp("ms").to_native() + 0 9.783072e+11 + 1 NaN + 2 9.784800e+11 + dtype: float64 + """ + if time_unit not in {"ns", "us", "ms"}: + msg = ( + "invalid `time_unit`" + f"\n\nExpected one of {{'ns', 'us', 'ms'}}, got {time_unit!r}." + ) + raise ValueError(msg) + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.timestamp(time_unit) + ) + + def truncate(self, every: str) -> SeriesT: + """Divide the date/datetime range into buckets. + + Arguments: + every: Length of bucket. Must be of form ``, + where `multiple` is a positive integer and `unit` is one of + + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + - 's': second. + - 'm': minute. + - 'h': hour. + - 'd': day. + - 'mo': month. + - 'q': quarter. + - 'y': year. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([datetime(2021, 3, 1, 12, 34)]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.truncate("1h").to_native() + 0 2021-03-01 12:00:00 + dtype: datetime64[us] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.truncate(every) + ) + + def offset_by(self, by: str) -> SeriesT: + """Offset this date by a relative time offset. + + Arguments: + by: The offset. Must be of form ``, + where `multiple` is a positive integer and `unit` is one of + + - 'ns': nanosecond. + - 'us': microsecond. + - 'ms': millisecond. + - 's': second. + - 'm': minute. + - 'h': hour. + - 'd': day. + - 'mo': month. + - 'q': quarter. + - 'y': year. + + Examples: + >>> from datetime import datetime + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series([datetime(2021, 3, 1, 12, 34)]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.dt.offset_by("1h").to_native() + 0 2021-03-01 13:34:00 + dtype: datetime64[us] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.dt.offset_by(by) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/series_list.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_list.py new file mode 100644 index 0000000000000000000000000000000000000000..d48dc2b18cb3fb6c0382aa4b18d20217494e3961 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_list.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic + +from narwhals.typing import SeriesT + +if TYPE_CHECKING: + from narwhals.typing import NonNestedLiteral + + +class SeriesListNamespace(Generic[SeriesT]): + def __init__(self, series: SeriesT) -> None: + self._narwhals_series = series + + def len(self) -> SeriesT: + """Return the number of elements in each list. + + Null values count towards the total. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[[1, 2], [3, 4, None], None, []]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.len().to_native() # doctest: +ELLIPSIS + + [ + [ + 2, + 3, + null, + 0 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.len() + ) + + def unique(self) -> SeriesT: + """Get the unique/distinct values in the list. + + Null values are included in the result. The order of unique values is not guaranteed. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[1, 1, 2], [3, 3, None], None, []]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.unique().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (4,) + Series: '' [list[i64]] + [ + [1, 2] + [null, 3] + null + [] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.unique() + ) + + def contains(self, item: NonNestedLiteral) -> SeriesT: + """Check if sublists contain the given item. + + Arguments: + item: Item that will be checked for membership. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[1, 2], None, []]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.contains(1).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [bool] + [ + true + null + false + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.contains(item) + ) + + def get(self, index: int) -> SeriesT: + """Return the value by index in each list. + + Negative indices are not accepted. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[1, 2], [3, 4, None], [None, 5]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.get(1).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [i64] + [ + 2 + 4 + 5 + ] + """ + if not isinstance(index, int): + msg = ( + f"Index must be of type 'int'. Got type '{type(index).__name__}' instead." + ) + raise TypeError(msg) + + if index < 0: + msg = f"Index {index} is out of bounds: should be greater than or equal to 0." + raise ValueError(msg) + + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.get(index) + ) + + def min(self) -> SeriesT: + """Compute the min value of the lists in the array. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[1], [3, 4, None]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.min().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 1 + 3 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.min() + ) + + def max(self) -> SeriesT: + """Compute the max value of the lists in the array. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[[1], [3, 4, None]]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.max().to_native() # doctest: +ELLIPSIS + + [ + [ + 1, + 4 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.max() + ) + + def mean(self) -> SeriesT: + """Compute the mean value of the lists in the array. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[1], [3, 4, None]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.mean().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [f64] + [ + 1.0 + 3.5 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.mean() + ) + + def median(self) -> SeriesT: + """Compute the median value of the lists in the array. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([[[1], [3, 4, None]]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.median().to_native() # doctest: +ELLIPSIS + + [ + [ + 1, + 3 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.median() + ) + + def sum(self) -> SeriesT: + """Compute the sum value of the lists in the array. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[1], [3, 4, None]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.sum().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [i64] + [ + 1 + 7 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.sum() + ) + + def sort(self, *, descending: bool = False, nulls_last: bool = False) -> SeriesT: + """Sort the lists of the series. + + Arguments: + descending: Sort in descending order. + nulls_last: Place null values last. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series([[2, -1, 1], [3, -4, None]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.list.sort().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [list[i64]] + [ + [-1, 1, 2] + [null, -4, 3] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.list.sort( + descending=descending, nulls_last=nulls_last + ) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/series_str.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_str.py new file mode 100644 index 0000000000000000000000000000000000000000..bd26fe682a26dd1a123d15458cbfa630dfc94719 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_str.py @@ -0,0 +1,519 @@ +from __future__ import annotations + +from typing import Any, Generic + +from narwhals.dependencies import is_narwhals_series +from narwhals.typing import SeriesT + + +class SeriesStringNamespace(Generic[SeriesT]): + def __init__(self, series: SeriesT) -> None: + self._narwhals_series = series + + def len_chars(self) -> SeriesT: + r"""Return the length of each string as the number of characters. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series(["foo", "345", None]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.len_chars().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (3,) + Series: '' [u32] + [ + 3 + 3 + null + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.len_chars() + ) + + def _extract_compliant(self, arg: Any) -> Any: + return arg._compliant_series if is_narwhals_series(arg) else arg + + def replace( + self, pattern: str, value: str | SeriesT, *, literal: bool = False, n: int = 1 + ) -> SeriesT: + r"""Replace first matching regex/literal substring with a new string value. + + Arguments: + pattern: A valid regular expression pattern. + value: String that will replace the matched substring. + literal: Treat `pattern` as a literal string. + n: Number of matches to replace. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["123abc", "abc abc123"]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.replace("abc", "").to_native() + 0 123 + 1 abc123 + dtype: str + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.replace( + self._extract_compliant(value), pattern=pattern, literal=literal, n=n + ) + ) + + def replace_all( + self, pattern: str, value: str | SeriesT, *, literal: bool = False + ) -> SeriesT: + r"""Replace all matching regex/literal substring with a new string value. + + Arguments: + pattern: A valid regular expression pattern. + value: String that will replace the matched substring. + literal: Treat `pattern` as a literal string. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["123abc", "abc abc123"]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.replace_all("abc", "").to_native() + 0 123 + 1 123 + dtype: str + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.replace_all( + self._extract_compliant(value), pattern, literal=literal + ) + ) + + def strip_chars(self, characters: str | None = None) -> SeriesT: + r"""Remove leading and trailing characters. + + Arguments: + characters: The set of characters to be removed. All combinations of this set of characters will be stripped from the start and end of the string. If set to None (default), all leading and trailing whitespace is removed instead. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series(["apple", "\nmango"]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.strip_chars().to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [str] + [ + "apple" + "mango" + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.strip_chars(characters) + ) + + def starts_with(self, prefix: str) -> SeriesT: + r"""Check if string values start with a substring. + + Arguments: + prefix: prefix substring + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["apple", "mango", None]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.starts_with("app").to_native() + 0 True + 1 False + 2 False + dtype: bool + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.starts_with(prefix) + ) + + def ends_with(self, suffix: str) -> SeriesT: + r"""Check if string values end with a substring. + + Arguments: + suffix: suffix substring + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["apple", "mango", None]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.ends_with("ngo").to_native() + 0 False + 1 True + 2 False + dtype: bool + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.ends_with(suffix) + ) + + def contains(self, pattern: str | SeriesT, *, literal: bool = False) -> SeriesT: + r"""Check if string contains a substring that matches a pattern. + + Arguments: + pattern: A Character sequence, valid regular expression pattern, or another + Series. + literal: If True, treats the pattern as a literal string. + If False, assumes the pattern is a regular expression. + + Warning: + Passing a Series as `pattern` is only supported by Polars. Other backends + will raise a `TypeError`. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([["cat", "dog", "rabbit and parrot"]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.contains("cat|parrot").to_native() # doctest: +ELLIPSIS + + [ + [ + true, + false, + true + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.contains( + self._extract_compliant(pattern), literal=literal + ) + ) + + def slice(self, offset: int, length: int | None = None) -> SeriesT: + r"""Create subslices of the string values of a Series. + + Arguments: + offset: Start index. Negative indexing is supported. + length: Length of the slice. If set to `None` (default), the slice is taken to the + end of the string. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["pear", None, "papaya"]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.slice(4, 3).to_native() # doctest: +NORMALIZE_WHITESPACE + 0 + 1 NaN + 2 ya + dtype: str + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.slice( + offset=offset, length=length + ) + ) + + def split(self, by: str) -> SeriesT: + r"""Split the string values of a Series by a substring. + + Arguments: + by: Substring to split by. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series(["foo bar", "foo_bar"]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.split("_").to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [list[str]] + [ + ["foo bar"] + ["foo", "bar"] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.split(by=by) + ) + + def head(self, n: int = 5) -> SeriesT: + r"""Take the first n elements of each string. + + Arguments: + n: Number of elements to take. Negative indexing is supported (see note (1.)) + + Notes: + 1. When the `n` input is negative, `head` returns characters up to the n-th from the end of the string. + For example, if `n = -3`, then all characters except the last three are returned. + 2. If the length of the string has fewer than `n` characters, the full string is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.head().to_native() # doctest: +ELLIPSIS + + [ + [ + "taata", + "taata", + "zukky" + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.slice(offset=0, length=n) + ) + + def tail(self, n: int = 5) -> SeriesT: + r"""Take the last n elements of each string. + + Arguments: + n: Number of elements to take. Negative indexing is supported (see note (1.)) + + Notes: + 1. When the `n` input is negative, `tail` returns characters starting from the n-th from the beginning of + the string. For example, if `n = -3`, then all characters except the first three are returned. + 2. If the length of the string has fewer than `n` characters, the full string is returned. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.tail().to_native() # doctest: +ELLIPSIS + + [ + [ + "taata", + "atata", + "kkyun" + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.slice(offset=-n, length=None) + ) + + def to_uppercase(self) -> SeriesT: + r"""Transform string to uppercase variant. + + Notes: + The PyArrow backend will convert 'ß' to 'ẞ' instead of 'SS'. + For more info see: https://github.com/apache/arrow/issues/34599 + There may be other unicode-edge-case-related variations across implementations. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["apple", None]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.to_uppercase().to_native() + 0 APPLE + 1 NaN + dtype: str + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.to_uppercase() + ) + + def to_lowercase(self) -> SeriesT: + r"""Transform string to lowercase variant. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["APPLE", None]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.to_lowercase().to_native() + 0 apple + 1 NaN + dtype: str + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.to_lowercase() + ) + + def to_datetime(self, format: str | None = None) -> SeriesT: + """Parse Series with strings to a Series with Datetime dtype. + + Notes: + - pandas defaults to nanosecond time unit, Polars to microsecond. + Prior to pandas 2.0, nanoseconds were the only time unit supported + in pandas, with no ability to set any other one. The ability to + set the time unit in pandas, if the version permits, will arrive. + - timezone-aware strings are all converted to and parsed as UTC. + + Warning: + As different backends auto-infer format in different ways, if `format=None` + there is no guarantee that the result will be equal. + + Arguments: + format: Format to use for conversion. If set to None (default), the format is + inferred from the data. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series(["2020-01-01", "2020-01-02"]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.to_datetime( + ... format="%Y-%m-%d" + ... ).to_native() # doctest: +NORMALIZE_WHITESPACE + shape: (2,) + Series: '' [datetime[μs]] + [ + 2020-01-01 00:00:00 + 2020-01-02 00:00:00 + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.to_datetime(format=format) + ) + + def to_date(self, format: str | None = None) -> SeriesT: + """Convert to date dtype. + + Warning: + As different backends auto-infer format in different ways, if `format=None` + there is no guarantee that the result will be equal. + + Arguments: + format: Format to use for conversion. If set to None (default), the format is + inferred from the data. + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array([["2020-01-01", "2020-01-02"]]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.to_date(format="%Y-%m-%d").to_native() # doctest: +ELLIPSIS + + [ + [ + 2020-01-01, + 2020-01-02 + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.to_date(format=format) + ) + + def to_titlecase(self) -> SeriesT: + """Modify strings to their titlecase equivalent. + + Notes: + This is a form of case transform where the first letter of each word is + capitalized, with the rest of the word in lowercase. + + Word boundaries are defined by non-**alphabetic** characters, matching the + behavior of [`str.title`](https://docs.python.org/3/library/stdtypes.html#str.title) + + Examples: + >>> import pyarrow as pa + >>> import narwhals as nw + >>> s_native = pa.chunked_array( + ... [ + ... [ + ... "'e.t. phone home'", + ... "you talkin' to me?", + ... "to infinity,and BEYOND!", + ... ] + ... ] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.to_titlecase().to_native() # doctest: +ELLIPSIS + + [ + [ + "'E.T. Phone Home'", + "You Talkin' To Me?", + "To Infinity,And Beyond!" + ] + ] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.to_titlecase() + ) + + def zfill(self, width: int) -> SeriesT: + r"""Pad strings with zeros on the left. + + Arguments: + width: The target width of the string. If the string is shorter than this width, it will be padded with zeros on the left. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> s_native = pd.Series(["+1", "-23", "456", "123456"]) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.str.zfill(5).to_native() + 0 +0001 + 1 -0023 + 2 00456 + 3 123456 + dtype: str + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.zfill(width) + ) + + def pad_start(self, length: int, fill_char: str = " ") -> SeriesT: + """Pad the start of the string until it reaches the given length. + + Arguments: + length: Pad the string until it reaches this length. Strings with + length equal to or greater than this value are returned as-is. + fill_char: The character to pad the string with. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]}) + >>> df = nw.from_native(df_native) + >>> df["a"].str.pad_start(8, "*") + ┌───────────────────┐ + | Narwhals Series | + |-------------------| + |0 *****cow | + |1 **monkey | + |2 hippopotamus | + |3 NaN | + |Name: a, dtype: str| + └───────────────────┘ + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.pad_start( + length=length, fill_char=fill_char + ) + ) + + def pad_end(self, length: int, fill_char: str = " ") -> SeriesT: + """Pad the end of the string until it reaches the given length. + + Arguments: + length: Pad the string until it reaches this length. Strings with + length equal to or greater than this value are returned as-is. + fill_char: The character to pad the string with. + + Examples: + >>> import pandas as pd + >>> import narwhals as nw + >>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]}) + >>> df = nw.from_native(df_native) + >>> df["a"].str.pad_end(8, "*") + ┌───────────────────┐ + | Narwhals Series | + |-------------------| + |0 cow***** | + |1 monkey** | + |2 hippopotamus | + |3 NaN | + |Name: a, dtype: str| + └───────────────────┘ + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.str.pad_end( + length=length, fill_char=fill_char + ) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/series_struct.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_struct.py new file mode 100644 index 0000000000000000000000000000000000000000..5a2851d6f08d620fcdab6d2b8d92ce1fddb78bfc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/series_struct.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import Generic + +from narwhals.typing import SeriesT + + +class SeriesStructNamespace(Generic[SeriesT]): + def __init__(self, series: SeriesT) -> None: + self._narwhals_series = series + + def field(self, name: str) -> SeriesT: + r"""Retrieve a Struct field as a new expression. + + Arguments: + name: Name of the struct field to retrieve. + + Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> s_native = pl.Series( + ... [{"id": "0", "name": "john"}, {"id": "1", "name": "jane"}] + ... ) + >>> s = nw.from_native(s_native, series_only=True) + >>> s.struct.field("name").to_list() + ['john', 'jane'] + """ + return self._narwhals_series._with_compliant( + self._narwhals_series._compliant_series.struct.field(name) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/sql.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/sql.py new file mode 100644 index 0000000000000000000000000000000000000000..cd503f0dcd9ac22cd70f823ee829bce797a88ede --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/sql.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +from narwhals._duckdb.utils import DeferredTimeZone, narwhals_to_native_dtype +from narwhals.dataframe import LazyFrame +from narwhals.translate import from_native +from narwhals.utils import Version + +if TYPE_CHECKING: + from narwhals._compliant.typing import CompliantLazyFrameAny + from narwhals.typing import IntoSchema + +try: + import duckdb # ignore-banned-import +except ImportError as _exc: # pragma: no cover + msg = ( + "`narwhals.sql` requires DuckDB to be installed.\n\n" + "Hint: run `pip install -U narwhals[sql]`" + ) + raise ModuleNotFoundError(msg) from _exc + +CONN = duckdb.connect() +TZ = DeferredTimeZone( + CONN.sql("select value from duckdb_settings() where name = 'TimeZone'") +) + + +class SQLTable(LazyFrame[duckdb.DuckDBPyRelation]): + """A LazyFrame with an additional `to_sql` method.""" + + def __init__( + self, df: CompliantLazyFrameAny, level: Literal["full", "interchange", "lazy"] + ) -> None: + super().__init__(df, level=level) + + def to_sql(self, *, pretty: bool = False) -> str: + """Convert to SQL query. + + Arguments: + pretty: Whether to pretty-print SQL query. If `True`, requires `sqlparse` + to be installed. + + Examples: + >>> import narwhals as nw + >>> from narwhals.sql import table + >>> schema = {"date": nw.Date, "price": nw.Int64, "symbol": nw.String} + >>> assets = table("assets", schema) + >>> result = assets.filter(nw.col("price") > 100) + >>> print(result.to_sql()) + SELECT * FROM main.assets WHERE (price > 100) + """ + sql_query = self.to_native().sql_query() + if not pretty: + return sql_query + try: + import sqlparse + except ImportError as _exc: # pragma: no cover + msg = ( + "`SQLTable.to_sql` with `pretty=True`" + "requires `sqlparse` to be installed.\n\n" + "Hint: run `pip install -U narwhals[sql]`" + ) + raise ModuleNotFoundError(msg) from _exc + return sqlparse.format(sql_query, reindent=True, keyword_case="upper") # type: ignore[no-any-return] + + +def table(name: str, schema: IntoSchema) -> SQLTable: + """Generate standalone LazyFrame which you can use to generate SQL. + + Note that this requires DuckDB to be installed. + + Parameters: + name: Table name. + schema: Table schema. + + Examples: + >>> import narwhals as nw + >>> from narwhals.sql import table + >>> schema = {"date": nw.Date, "price": nw.List(nw.Int64), "symbol": nw.String} + >>> table("t", schema) + ┌────────────────────────────┐ + | Narwhals LazyFrame | + |----------------------------| + |┌──────┬─────────┬─────────┐| + |│ date │ price │ symbol │| + |│ date │ int64[] │ varchar │| + |└──────┴─────────┴─────────┘| + | 0 rows | + └────────────────────────────┘ + """ + column_mapping = { + col: narwhals_to_native_dtype(dtype, Version.MAIN, TZ) + for col, dtype in schema.items() + } + dtypes = ", ".join(f'"{col}" {dtype}' for col, dtype in column_mapping.items()) + CONN.sql(f""" + CREATE TABLE "{name}" + ({dtypes}); + """) + lf = from_native(CONN.table(name)) + return SQLTable(lf._compliant_frame, level=lf._level) + + +__all__ = ["table"] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/this.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/this.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba7aa2617dc96d27eda1d30a969d50d9051fb74 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/this.py @@ -0,0 +1,17 @@ +# ruff: noqa +ZEN = """\ +⣿⣿⣿⣿⣿⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ THE ZEN OF NARWHALS +⣿⣿⣿⣿⣿⠠⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ Keep it simple +⣿⣿⣿⣿⣿⡀⡄⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ Move slowly and keep things working +⣿⣿⣿⣿⣿⡇⡼⡘⠛⠿⠿⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ A good API is an honest one +⣿⣿⣿⡿⣫⡄⠾⣣⠹⣿⣿⣿⣶⣮⣙⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ Yes, that needs documenting +⣿⣿⢋⣴⣿⣷⣬⣭⣾⣿⣿⣿⣿⣿⣿⣿⣦⡙⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ People learn better from examples +⣿⢃⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ than from explanations⠀ +⡏⠀⢰⠄⢻⣿⣿⣿⣿⡿⠋⢉⠻⣿⣿⣿⣿⣿⣿⡜⣿⣿⡿⢁⢻⣿⣿⣿⣿⣿ If in doubt, better to say 'no' +⡇⣌⣀⣠⣾⣿⣿⣿⣿⣇⠶⠉⢁⣿⣿⣿⣿⣿⣿⣧⡹⣿⡇⣿⣧⠻⠿⠿⠿⠿ than to risk causing a commotion⠀ +⡧⢹⣿⣿⣿⣜⣟⣸⣿⣿⣷⣶⣿⡿⣿⣿⣝⢿⣿⣿⣷⣬⣥⣿⣿⣿⣿⣿⡟⣰ Yes, we need a test for that +⢡⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⡙⣿⣿⡇⣿⣿⣿⣿⠟⣋⣭⣛⠻⣋⣴⣿ If you want users +⣶⣤⣤⣙⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣍⣡⣿⡿⢋⣴⣿⣿⣿⣿⣿⣿⣿⣿ you need good docs⠀ +⣿⣿⣿⣿⣿⣶⣬⣙⣛⠻⠿⠿⠿⠿⠿⠟⣛⣩⣥⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿ Our code is not irreplaceable""" + +print(ZEN) diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/translate.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/translate.py new file mode 100644 index 0000000000000000000000000000000000000000..9452111bdd6f5add33b36d522c886961075a5af0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/translate.py @@ -0,0 +1,692 @@ +from __future__ import annotations + +import datetime as dt +from decimal import Decimal +from functools import wraps +from typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar, overload + +from narwhals import plugins +from narwhals._constants import EPOCH, MS_PER_SECOND +from narwhals._native import ( + is_native_arrow, + is_native_pandas_like, + is_native_polars, + is_native_spark_like, +) +from narwhals._utils import ( + Implementation, + Version, + has_native_namespace, + is_compliant_dataframe, + is_compliant_lazyframe, + is_compliant_series, +) +from narwhals.dependencies import ( + get_dask_expr, + get_numpy, + get_pandas, + is_cupy_scalar, + is_dask_dataframe, + is_duckdb_relation, + is_ibis_table, + is_numpy_scalar, + is_pandas_like_dataframe, + is_polars_lazyframe, + is_polars_series, + is_pyarrow_scalar, + is_pyarrow_table, +) + +if TYPE_CHECKING: + from typing_extensions import Unpack + + from narwhals._translate import ( + AllowAny, + AllowLazy, + AllowSeries, + ExcludeSeries, + OnlySeries, + PassThroughUnknown, + ) + from narwhals.dataframe import DataFrame, LazyFrame + from narwhals.series import Series + from narwhals.typing import ( + DataFrameT, + Frame, + IntoDataFrameT, + IntoFrame, + IntoLazyFrameT, + IntoSeries, + IntoSeriesT, + LazyFrameT, + SeriesT, + ) + +T = TypeVar("T") + +NON_TEMPORAL_SCALAR_TYPES = (bool, bytes, str, int, float, complex, Decimal) +TEMPORAL_SCALAR_TYPES = (dt.date, dt.timedelta, dt.time) + + +@overload +def to_native( + narwhals_object: DataFrame[IntoDataFrameT], *, pass_through: Literal[False] = ... +) -> IntoDataFrameT: ... +@overload +def to_native( + narwhals_object: LazyFrame[IntoLazyFrameT], *, pass_through: Literal[False] = ... +) -> IntoLazyFrameT: ... +@overload +def to_native( + narwhals_object: Series[IntoSeriesT], *, pass_through: Literal[False] = ... +) -> IntoSeriesT: ... +@overload +def to_native(narwhals_object: Any, *, pass_through: bool) -> Any: ... + + +def to_native( + narwhals_object: DataFrame[IntoDataFrameT] + | LazyFrame[IntoLazyFrameT] + | Series[IntoSeriesT], + *, + pass_through: bool = False, +) -> IntoDataFrameT | IntoLazyFrameT | IntoSeriesT | Any: + """Convert Narwhals object to native one. + + Arguments: + narwhals_object: Narwhals object. + pass_through: Determine what happens if `narwhals_object` isn't a Narwhals class + + - `False` (default): raise an error + - `True`: pass object through as-is + + Returns: + Object of class that user started with. + """ + from narwhals.dataframe import BaseFrame + from narwhals.series import Series + + if isinstance(narwhals_object, BaseFrame): + return narwhals_object._compliant_frame._native_frame + if isinstance(narwhals_object, Series): + return narwhals_object._compliant_series.native + + if not pass_through: + msg = f"Expected Narwhals object, got {type(narwhals_object)}." + raise TypeError(msg) + return narwhals_object + + +@overload +def from_native(native_object: SeriesT, **kwds: Unpack[OnlySeries]) -> SeriesT: ... +@overload +def from_native(native_object: SeriesT, **kwds: Unpack[AllowSeries]) -> SeriesT: ... +@overload +def from_native( + native_object: DataFrameT, **kwds: Unpack[ExcludeSeries] +) -> DataFrameT: ... +# Closer to *intended* than https://github.com/narwhals-dev/narwhals/issues/3226 +@overload +def from_native(native_object: LazyFrameT, **kwds: Unpack[AllowLazy]) -> LazyFrameT: ... +@overload +def from_native( + native_object: IntoDataFrameT, **kwds: Unpack[ExcludeSeries] +) -> DataFrame[IntoDataFrameT]: ... +@overload +def from_native( + native_object: IntoSeriesT, **kwds: Unpack[OnlySeries] +) -> Series[IntoSeriesT]: ... +@overload +def from_native( + native_object: IntoSeriesT, **kwds: Unpack[AllowSeries] +) -> Series[IntoSeriesT]: ... +@overload +def from_native( + native_object: IntoLazyFrameT, **kwds: Unpack[AllowLazy] +) -> LazyFrame[IntoLazyFrameT]: ... +@overload +def from_native( + native_object: IntoDataFrameT | IntoSeriesT, **kwds: Unpack[AllowSeries] +) -> DataFrame[IntoDataFrameT] | Series[IntoSeriesT]: ... +@overload +def from_native( + native_object: IntoDataFrameT | IntoLazyFrameT | IntoSeriesT, **kwds: Unpack[AllowAny] +) -> DataFrame[IntoDataFrameT] | LazyFrame[IntoLazyFrameT] | Series[IntoSeriesT]: ... +@overload +def from_native(native_object: T, **kwds: Unpack[PassThroughUnknown]) -> T: ... +# All params passed in as variables +@overload +def from_native( + native_object: Any, + *, + pass_through: bool, + eager_only: bool, + series_only: bool, + allow_series: bool | None, +) -> Any: ... +def from_native( + native_object: IntoLazyFrameT + | IntoDataFrameT + | IntoSeriesT + | IntoFrame + | IntoSeries + | T, + *, + pass_through: bool = False, + eager_only: bool = False, + series_only: bool = False, + allow_series: bool | None = None, +) -> LazyFrame[IntoLazyFrameT] | DataFrame[IntoDataFrameT] | Series[IntoSeriesT] | T: + """Convert `native_object` to Narwhals Dataframe, Lazyframe, or Series. + + Arguments: + native_object: Raw object from user. + Depending on the other arguments, input object can be + + - a Dataframe / Lazyframe / Series supported by Narwhals (pandas, Polars, PyArrow, ...) + - an object which implements `__narwhals_dataframe__`, `__narwhals_lazyframe__`, + or `__narwhals_series__` + pass_through: Determine what happens if the object can't be converted to Narwhals + + - `False` (default): raise an error + - `True`: pass object through as-is + eager_only: Whether to only allow eager objects + + - `False` (default): don't require `native_object` to be eager + - `True`: only convert to Narwhals if `native_object` is eager + series_only: Whether to only allow Series + + - `False` (default): don't require `native_object` to be a Series + - `True`: only convert to Narwhals if `native_object` is a Series + allow_series: Whether to allow Series (default is only Dataframe / Lazyframe) + + - `False` or `None` (default): don't convert to Narwhals if `native_object` is a Series + - `True`: allow `native_object` to be a Series + + Returns: + DataFrame, LazyFrame, Series, or original object, depending + on which combination of parameters was passed. + """ + return _from_native_impl( # type: ignore[no-any-return] + native_object, + pass_through=pass_through, + eager_only=eager_only, + eager_or_interchange_only=False, + series_only=series_only, + allow_series=allow_series, + version=Version.MAIN, + ) + + +def _translate_if_compliant( # noqa: C901,PLR0911 + compliant_object: Any, + *, + pass_through: bool = False, + eager_only: bool = False, + # Interchange-level was removed after v1 + eager_or_interchange_only: bool, + series_only: bool, + allow_series: bool | None, + version: Version, +) -> Any: + if is_compliant_dataframe(compliant_object): + if series_only: + if not pass_through: + msg = "Cannot only use `series_only` with dataframe" + raise TypeError(msg) + return compliant_object + return version.dataframe( + compliant_object.__narwhals_dataframe__()._with_version(version), level="full" + ) + if is_compliant_lazyframe(compliant_object): + if series_only: + if not pass_through: + msg = "Cannot only use `series_only` with lazyframe" + raise TypeError(msg) + return compliant_object + if eager_only or eager_or_interchange_only: + if not pass_through: + msg = "Cannot only use `eager_only` or `eager_or_interchange_only` with lazyframe" + raise TypeError(msg) + return compliant_object + return version.lazyframe( + compliant_object.__narwhals_lazyframe__()._with_version(version), level="full" + ) + if is_compliant_series(compliant_object): + if not allow_series: + if not pass_through: + msg = "Please set `allow_series=True` or `series_only=True`" + raise TypeError(msg) + return compliant_object + return version.series( + compliant_object.__narwhals_series__()._with_version(version), level="full" + ) + # Object wasn't compliant, can't translate here. + return None + + +def _from_native_impl( # noqa: C901, PLR0911, PLR0912, PLR0915 + native_object: Any, + *, + pass_through: bool = False, + eager_only: bool = False, + # Interchange-level was removed after v1 + eager_or_interchange_only: bool, + series_only: bool, + allow_series: bool | None, + version: Version, +) -> Any: + from narwhals._interchange.dataframe import supports_dataframe_interchange + from narwhals.dataframe import DataFrame, LazyFrame + from narwhals.series import Series + + # Early returns + if isinstance(native_object, (DataFrame, LazyFrame)) and not series_only: + if native_object._version is version: + return native_object + + real_native_object = native_object.to_native() + return ( + version.namespace.from_native_object(real_native_object) + .compliant.from_native(real_native_object) + .to_narwhals() + ) + if isinstance(native_object, Series) and (series_only or allow_series): + if native_object._version is version: + return native_object + + real_native_object = native_object.to_native() + return ( + version.namespace.from_native_object(real_native_object) + .compliant.from_native(real_native_object) + .to_narwhals() + ) + + if series_only: + if allow_series is False: + msg = "Invalid parameter combination: `series_only=True` and `allow_series=False`" + raise ValueError(msg) + allow_series = True + if eager_only and eager_or_interchange_only: + msg = "Invalid parameter combination: `eager_only=True` and `eager_or_interchange_only=True`" + raise ValueError(msg) + + # Extensions + if ( + translated := _translate_if_compliant( + native_object, + pass_through=pass_through, + eager_only=eager_only, + eager_or_interchange_only=eager_or_interchange_only, + series_only=series_only, + allow_series=allow_series, + version=version, + ) + ) is not None: + return translated + + # Polars + if is_native_polars(native_object): + if series_only and not is_polars_series(native_object): + if not pass_through: + msg = f"Cannot only use `series_only` with {type(native_object).__qualname__}" + raise TypeError(msg) + return native_object + if (eager_only or eager_or_interchange_only) and is_polars_lazyframe( + native_object + ): + if not pass_through: + msg = "Cannot only use `eager_only` or `eager_or_interchange_only` with polars.LazyFrame" + raise TypeError(msg) + return native_object + if (not allow_series) and is_polars_series(native_object): + if not pass_through: + msg = "Please set `allow_series=True` or `series_only=True`" + raise TypeError(msg) + return native_object + return ( + version.namespace.from_native_object(native_object) + .compliant.from_native(native_object) + .to_narwhals() + ) + + # PandasLike + if is_native_pandas_like(native_object): + if is_pandas_like_dataframe(native_object): + if series_only: + if not pass_through: + msg = f"Cannot only use `series_only` with {type(native_object).__qualname__}" + raise TypeError(msg) + return native_object + elif not allow_series: + if not pass_through: + msg = "Please set `allow_series=True` or `series_only=True`" + raise TypeError(msg) + return native_object + return ( + version.namespace.from_native_object(native_object) + .compliant.from_native(native_object) + .to_narwhals() + ) + + # PyArrow + if is_native_arrow(native_object): + if is_pyarrow_table(native_object): + if series_only: + if not pass_through: + msg = f"Cannot only use `series_only` with {type(native_object).__qualname__}" + raise TypeError(msg) + return native_object + elif not allow_series: + if not pass_through: + msg = "Please set `allow_series=True` or `series_only=True`" + raise TypeError(msg) + return native_object + return ( + version.namespace.from_native_object(native_object) + .compliant.from_native(native_object) + .to_narwhals() + ) + + # Dask + if is_dask_dataframe(native_object): + if series_only: + if not pass_through: + msg = "Cannot only use `series_only` with dask DataFrame" + raise TypeError(msg) + return native_object + if eager_only or eager_or_interchange_only: + if not pass_through: + msg = "Cannot only use `eager_only` or `eager_or_interchange_only` with dask DataFrame" + raise TypeError(msg) + return native_object + if ( + Implementation.DASK._backend_version() <= (2024, 12, 1) + and get_dask_expr() is None + ): # pragma: no cover + msg = "Please install dask-expr" + raise ImportError(msg) + return ( + version.namespace.from_backend(Implementation.DASK) + .compliant.from_native(native_object) + .to_narwhals() + ) + + # DuckDB + if is_duckdb_relation(native_object): + if eager_only or series_only: # pragma: no cover + if not pass_through: + msg = "Cannot only use `series_only=True` or `eager_only=False` with DuckDBPyRelation" + raise TypeError(msg) + return native_object + return ( + version.namespace.from_native_object(native_object) + .compliant.from_native(native_object) + .to_narwhals() + ) + + # Ibis + if is_ibis_table(native_object): + if eager_only or series_only: # pragma: no cover + if not pass_through: + msg = "Cannot only use `series_only=True` or `eager_only=False` with ibis.Table" + raise TypeError(msg) + return native_object + return ( + version.namespace.from_native_object(native_object) + .compliant.from_native(native_object) + .to_narwhals() + ) + + # PySpark + if is_native_spark_like(native_object): # pragma: no cover + ns_spark = version.namespace.from_native_object(native_object) + if series_only or eager_only or eager_or_interchange_only: + if not pass_through: + msg = ( + "Cannot only use `series_only`, `eager_only` or `eager_or_interchange_only` " + f"with {ns_spark.implementation} DataFrame" + ) + raise TypeError(msg) + return native_object + return ns_spark.compliant.from_native(native_object).to_narwhals() + + # Interchange protocol + if version is Version.V1 and supports_dataframe_interchange(native_object): + from narwhals._interchange.dataframe import InterchangeFrame + + if eager_only or series_only: + if not pass_through: + msg = ( + "Cannot only use `series_only=True` or `eager_only=False` " + "with object which only implements __dataframe__" + ) + raise TypeError(msg) + return native_object + return Version.V1.dataframe(InterchangeFrame(native_object), level="interchange") + + if (compliant_object := plugins.from_native(native_object, version)) is not None: + return _translate_if_compliant( + compliant_object, + pass_through=pass_through, + eager_only=eager_only, + eager_or_interchange_only=eager_or_interchange_only, + series_only=series_only, + allow_series=allow_series, + version=version, + ) + + if not pass_through: + msg = f"Unsupported dataframe type, got: {type(native_object)}" + if hint := plugins._show_suggestions(type(native_object)): # pragma: no cover + msg += "\n\n" + hint + raise TypeError(msg) + return native_object + + +def get_native_namespace(*obj: Frame | Series[Any] | IntoFrame | IntoSeries) -> Any: + """Get native namespace from object. + + Arguments: + obj: Dataframe, Lazyframe, or Series. Multiple objects can be + passed positionally, in which case they must all have the + same native namespace (else an error is raised). + + Returns: + Native module. + + Examples: + >>> import polars as pl + >>> import pandas as pd + >>> import narwhals as nw + >>> df = nw.from_native(pd.DataFrame({"a": [1, 2, 3]})) + >>> nw.get_native_namespace(df) + + >>> df = nw.from_native(pl.DataFrame({"a": [1, 2, 3]})) + >>> nw.get_native_namespace(df) + + """ + if not obj: + msg = "At least one object must be passed to `get_native_namespace`." + raise ValueError(msg) + result = {_get_native_namespace_single_obj(x) for x in obj} + if len(result) != 1: + msg = f"Found objects with different native namespaces: {result}." + raise ValueError(msg) + return result.pop() + + +def _get_native_namespace_single_obj( + obj: Frame | Series[Any] | IntoFrame | IntoSeries, +) -> Any: + if has_native_namespace(obj): + return obj.__native_namespace__() + return Version.MAIN.namespace.from_native_object( + obj + ).implementation.to_native_namespace() + + +def narwhalify( + func: Callable[..., Any] | None = None, + *, + pass_through: bool = True, + eager_only: bool = False, + series_only: bool = False, + allow_series: bool | None = True, +) -> Callable[..., Any]: + """Decorate function so it becomes dataframe-agnostic. + + This will try to convert any dataframe/series-like object into the Narwhals + respective DataFrame/Series, while leaving the other parameters as they are. + Similarly, if the output of the function is a Narwhals DataFrame or Series, it will be + converted back to the original dataframe/series type, while if the output is another + type it will be left as is. + By setting `pass_through=False`, then every input and every output will be required to be a + dataframe/series-like object. + + Arguments: + func: Function to wrap in a `from_native`-`to_native` block. + pass_through: Determine what happens if the object can't be converted to Narwhals + + - `False`: raise an error + - `True` (default): pass object through as-is + eager_only: Whether to only allow eager objects + + - `False` (default): don't require `native_object` to be eager + - `True`: only convert to Narwhals if `native_object` is eager + series_only: Whether to only allow Series + + - `False` (default): don't require `native_object` to be a Series + - `True`: only convert to Narwhals if `native_object` is a Series + allow_series: Whether to allow Series (default is only Dataframe / Lazyframe) + + - `False` or `None`: don't convert to Narwhals if `native_object` is a Series + - `True` (default): allow `native_object` to be a Series + + Returns: + Decorated function. + + Examples: + Instead of writing + + >>> import narwhals as nw + >>> def agnostic_group_by_sum(df): + ... df = nw.from_native(df, pass_through=True) + ... df = df.group_by("a").agg(nw.col("b").sum()) + ... return nw.to_native(df) + + you can just write + + >>> @nw.narwhalify + ... def agnostic_group_by_sum(df): + ... return df.group_by("a").agg(nw.col("b").sum()) + """ + + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + args_nw = [ + from_native( + arg, + pass_through=pass_through, + eager_only=eager_only, + series_only=series_only, + allow_series=allow_series, + ) + for arg in args + ] + + kwargs_nw = { + name: from_native( + value, + pass_through=pass_through, + eager_only=eager_only, + series_only=series_only, + allow_series=allow_series, + ) + for name, value in kwargs.items() + } + + backends = { + b() + for v in (*args_nw, *kwargs_nw.values()) + if (b := getattr(v, "__native_namespace__", None)) + } + + if len(backends) > 1: + msg = "Found multiple backends. Make sure that all dataframe/series inputs come from the same backend." + raise ValueError(msg) + + result = func(*args_nw, **kwargs_nw) + + return to_native(result, pass_through=pass_through) + + return wrapper + + if func is None: + return decorator + # If func is not None, it means the decorator is used without arguments + return decorator(func) + + +def to_py_scalar(scalar_like: Any) -> Any: + """If a scalar is not Python native, converts it to Python native. + + Arguments: + scalar_like: Scalar-like value. + + Raises: + ValueError: If the object is not convertible to a scalar. + + Examples: + >>> import narwhals as nw + >>> import pandas as pd + >>> df = nw.from_native(pd.DataFrame({"a": [1, 2, 3]})) + >>> nw.to_py_scalar(df["a"].item(0)) + 1 + >>> import pyarrow as pa + >>> df = nw.from_native(pa.table({"a": [1, 2, 3]})) + >>> nw.to_py_scalar(df["a"].item(0)) + 1 + >>> nw.to_py_scalar(1) + 1 + """ + scalar: Any + pd = get_pandas() + if scalar_like is None or isinstance(scalar_like, NON_TEMPORAL_SCALAR_TYPES): + scalar = scalar_like + elif ( + (np := get_numpy()) + and isinstance(scalar_like, np.datetime64) + and scalar_like.dtype == "datetime64[ns]" + ): + ms = scalar_like.item() // MS_PER_SECOND + scalar = EPOCH + dt.timedelta(microseconds=ms) + elif is_numpy_scalar(scalar_like) or is_cupy_scalar(scalar_like): + scalar = scalar_like.item() + elif pd and isinstance(scalar_like, pd.Timestamp): + scalar = scalar_like.to_pydatetime() + elif pd and isinstance(scalar_like, pd.Timedelta): + scalar = scalar_like.to_pytimedelta() + # pd.Timestamp and pd.Timedelta subclass datetime and timedelta, + # so we need to check this separately + elif isinstance(scalar_like, TEMPORAL_SCALAR_TYPES): + scalar = scalar_like + elif _is_pandas_na(scalar_like): + scalar = None + elif is_pyarrow_scalar(scalar_like): + scalar = scalar_like.as_py() + else: + msg = ( + f"Expected object convertible to a scalar, found {type(scalar_like)}.\n" + f"{scalar_like!r}" + ) + raise ValueError(msg) + return scalar + + +def _is_pandas_na(obj: Any) -> bool: + return bool((pd := get_pandas()) and pd.api.types.is_scalar(obj) and pd.isna(obj)) + + +__all__ = ["get_native_namespace", "narwhalify", "to_native", "to_py_scalar"] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/typing.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..c99507f3807a7f8e5d68c8f9f2788f8df7755a8e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/typing.py @@ -0,0 +1,398 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar, Union + +from narwhals._compliant import CompliantDataFrame, CompliantLazyFrame, CompliantSeries +from narwhals._native import ( + IntoDataFrame, + IntoDataFrameT, + IntoFrame, + IntoFrameT, + IntoLazyFrame, + IntoLazyFrameT, + IntoSeries, + IntoSeriesT, +) +from narwhals._typing import Backend, EagerAllowed, IntoBackend, LazyAllowed + +if TYPE_CHECKING: + import datetime as dt + import os + from collections.abc import Sequence + from decimal import Decimal + from types import ModuleType + + import numpy as np + import pandas as pd + import polars as pl + import pyarrow as pa + from typing_extensions import TypeAlias + + from narwhals import dtypes + from narwhals.dataframe import DataFrame, LazyFrame + from narwhals.expr import Expr + from narwhals.schema import Schema + from narwhals.series import Series + + class SupportsNativeNamespace(Protocol): + def __native_namespace__(self) -> ModuleType: ... + + # ruff: noqa: N802 + class DTypes(Protocol): + @property + def Decimal(self) -> type[dtypes.Decimal]: ... + @property + def Int128(self) -> type[dtypes.Int128]: ... + @property + def Int64(self) -> type[dtypes.Int64]: ... + @property + def Int32(self) -> type[dtypes.Int32]: ... + @property + def Int16(self) -> type[dtypes.Int16]: ... + @property + def Int8(self) -> type[dtypes.Int8]: ... + @property + def UInt128(self) -> type[dtypes.UInt128]: ... + @property + def UInt64(self) -> type[dtypes.UInt64]: ... + @property + def UInt32(self) -> type[dtypes.UInt32]: ... + @property + def UInt16(self) -> type[dtypes.UInt16]: ... + @property + def UInt8(self) -> type[dtypes.UInt8]: ... + @property + def Float64(self) -> type[dtypes.Float64]: ... + @property + def Float32(self) -> type[dtypes.Float32]: ... + @property + def String(self) -> type[dtypes.String]: ... + @property + def Boolean(self) -> type[dtypes.Boolean]: ... + @property + def Object(self) -> type[dtypes.Object]: ... + @property + def Categorical(self) -> type[dtypes.Categorical]: ... + @property + def Enum(self) -> type[dtypes.Enum]: ... + @property + def Datetime(self) -> type[dtypes.Datetime]: ... + @property + def Duration(self) -> type[dtypes.Duration]: ... + @property + def Date(self) -> type[dtypes.Date]: ... + @property + def Field(self) -> type[dtypes.Field]: ... + @property + def Struct(self) -> type[dtypes.Struct]: ... + @property + def List(self) -> type[dtypes.List]: ... + @property + def Array(self) -> type[dtypes.Array]: ... + @property + def Unknown(self) -> type[dtypes.Unknown]: ... + @property + def Time(self) -> type[dtypes.Time]: ... + @property + def Binary(self) -> type[dtypes.Binary]: ... + + +_ShapeT = TypeVar("_ShapeT", bound="tuple[int, ...]") +_NDArray: TypeAlias = "np.ndarray[_ShapeT, Any]" +_1DArray: TypeAlias = "_NDArray[tuple[int]]" +_1DArrayBool: TypeAlias = "np.ndarray[tuple[bool], np.dtype[np.bool_]]" +_1DArrayInt: TypeAlias = "np.ndarray[tuple[int], np.dtype[np.integer[Any]]]" +_2DArray: TypeAlias = "_NDArray[tuple[int, int]]" # noqa: PYI047 +_AnyDArray: TypeAlias = "_NDArray[tuple[int, ...]]" # noqa: PYI047 +_NumpyScalar: TypeAlias = "np.generic[Any]" +Into1DArray: TypeAlias = "_1DArray | _NumpyScalar" +"""A 1-dimensional `numpy.ndarray` or scalar that can be converted into one.""" + +IntoExpr: TypeAlias = Union["Expr", str, "Series[Any]", _1DArray] +"""Anything which can be converted to an expression. + +Use this to mean "either a Narwhals expression, or something which can be converted +into one". For example, `exprs` in `DataFrame.select` is typed to accept `IntoExpr`, +as it can either accept a `nw.Expr` (e.g. `df.select(nw.col('a'))`) or a string +which will be interpreted as a `nw.Expr`, e.g. `df.select('a')`. +""" + +Frame: TypeAlias = Union["DataFrame[Any]", "LazyFrame[Any]"] +"""Narwhals DataFrame or Narwhals LazyFrame. + +Use this if your function can work with either and your function doesn't care +about its backend. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import Frame + >>> @nw.narwhalify + ... def agnostic_columns(df: Frame) -> list[str]: + ... return df.columns +""" + +FrameT = TypeVar("FrameT", "DataFrame[Any]", "LazyFrame[Any]") +"""TypeVar bound to Narwhals DataFrame or Narwhals LazyFrame. + +Use this if your function accepts either `nw.DataFrame` or `nw.LazyFrame` and returns +an object of the same kind. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import FrameT + >>> @nw.narwhalify + ... def agnostic_func(df: FrameT) -> FrameT: + ... return df.with_columns(c=nw.col("a") + 1) +""" + +DataFrameT = TypeVar("DataFrameT", bound="DataFrame[Any]") +"""TypeVar bound to Narwhals DataFrame. + +Use this if your function can accept a Narwhals DataFrame and returns a Narwhals +DataFrame backed by the same backend. + +Examples: + >>> import narwhals as nw + >>> from narwhals.typing import DataFrameT + >>> @nw.narwhalify + >>> def func(df: DataFrameT) -> DataFrameT: + ... return df.with_columns(c=df["a"] + 1) +""" + +LazyFrameT = TypeVar("LazyFrameT", bound="LazyFrame[Any]") +SeriesT = TypeVar("SeriesT", bound="Series[Any]") +DTypeBackend: TypeAlias = 'Literal["pyarrow", "numpy_nullable"] | None' +SizeUnit: TypeAlias = Literal[ + "b", + "kb", + "mb", + "gb", + "tb", + "bytes", + "kilobytes", + "megabytes", + "gigabytes", + "terabytes", +] + +TimeUnit: TypeAlias = Literal["ns", "us", "ms", "s"] + +AsofJoinStrategy: TypeAlias = Literal["backward", "forward", "nearest"] +"""Join strategy. + +- *"backward"*: Selects the last row in the right DataFrame whose `on` key + is less than or equal to the left's key. +- *"forward"*: Selects the first row in the right DataFrame whose `on` key + is greater than or equal to the left's key. +- *"nearest"*: Search selects the last row in the right DataFrame whose value + is nearest to the left's key. +""" + +ClosedInterval: TypeAlias = Literal["left", "right", "none", "both"] +"""Define which sides of the interval are closed (inclusive).""" + +ConcatMethod: TypeAlias = Literal["horizontal", "vertical", "diagonal"] +"""Concatenating strategy. + +- *"vertical"*: Concatenate vertically. Column names must match. +- *"horizontal"*: Concatenate horizontally. If lengths don't match, then + missing rows are filled with null values. +- *"diagonal"*: Finds a union between the column schemas and fills missing + column values with null. +""" + +FillNullStrategy: TypeAlias = Literal["forward", "backward"] +"""Strategy used to fill null values.""" + +JoinStrategy: TypeAlias = Literal["inner", "left", "full", "cross", "semi", "anti"] +"""Join strategy. + +- *"inner"*: Returns rows that have matching values in both tables. +- *"left"*: Returns all rows from the left table, and the matched rows from + the right table. +- *"full"*: Returns all rows in both dataframes, with the `suffix` appended to + the right join keys. +- *"cross"*: Returns the Cartesian product of rows from both tables. +- *"semi"*: Filter rows that have a match in the right table. +- *"anti"*: Filter rows that do not have a match in the right table. +""" + +PivotAgg: TypeAlias = Literal[ + "min", "max", "first", "last", "sum", "mean", "median", "len" +] +"""A predefined aggregate function string.""" + +RankMethod: TypeAlias = Literal["average", "min", "max", "dense", "ordinal"] +"""The method used to assign ranks to tied elements. + +- *"average"*: The average of the ranks that would have been assigned to + all the tied values is assigned to each value. +- *"min"*: The minimum of the ranks that would have been assigned to all + the tied values is assigned to each value. (This is also referred to + as "competition" ranking.) +- *"max"*: The maximum of the ranks that would have been assigned to all + the tied values is assigned to each value. +- *"dense"*: Like "min", but the rank of the next highest element is + assigned the rank immediately after those assigned to the tied elements. +- *"ordinal"*: All values are given a distinct rank, corresponding to the + order that the values occur in the Series. +""" + +RollingInterpolationMethod: TypeAlias = Literal[ + "nearest", "higher", "lower", "midpoint", "linear" +] +"""Interpolation method.""" + +CorrelationMethod: TypeAlias = Literal["pearson", "spearman"] + +UniqueKeepStrategy: TypeAlias = Literal["any", "first", "last", "none"] +"""Which of the duplicate rows to keep. + +- *"any"*: Does not give any guarantee of which row is kept. + This allows more optimizations. +- *"none"*: Don't keep duplicate rows. +- *"first"*: Keep first unique row. +- *"last"*: Keep last unique row. +""" + +ModeKeepStrategy: TypeAlias = Literal["any", "all"] +"""Which of the mode's to keep. + +- *"any"*: Does not give any guarantee of which mode is kept. +- *"all"*: Keeps all the mode's. +""" + + +PandasLikeDType: TypeAlias = "pd.api.extensions.ExtensionDtype | np.dtype[Any]" + + +NumericLiteral: TypeAlias = "int | float | Decimal" +TemporalLiteral: TypeAlias = "dt.date | dt.datetime | dt.time | dt.timedelta" +NonNestedLiteral: TypeAlias = ( + "NumericLiteral | TemporalLiteral | str | bool | bytes | None" +) +NestedLiteral: TypeAlias = "list[Any] | tuple[Any, ...] | dict[str, Any]" +PythonLiteral: TypeAlias = "NonNestedLiteral | NestedLiteral" + +NonNestedDType: TypeAlias = "dtypes.NumericType | dtypes.TemporalType | dtypes.String | dtypes.Boolean | dtypes.Binary | dtypes.Categorical | dtypes.Unknown | dtypes.Object" +"""Any Narwhals DType that does not have required arguments.""" + +IntoDType: TypeAlias = "dtypes.DType | type[NonNestedDType]" +"""Anything that can be converted into a Narwhals DType. + +Examples: + >>> import polars as pl + >>> import narwhals as nw + >>> df_native = pl.DataFrame({"a": [1, 2, 3], "b": [4.0, 5.0, 6.0]}) + >>> df = nw.from_native(df_native) + >>> df.select( + ... nw.col("a").cast(nw.Int32), + ... nw.col("b").cast(nw.String()).str.split(".").cast(nw.List(nw.Int8)), + ... ) + ┌──────────────────┐ + |Narwhals DataFrame| + |------------------| + |shape: (3, 2) | + |┌─────┬──────────┐| + |│ a ┆ b │| + |│ --- ┆ --- │| + |│ i32 ┆ list[i8] │| + |╞═════╪══════════╡| + |│ 1 ┆ [4, 0] │| + |│ 2 ┆ [5, 0] │| + |│ 3 ┆ [6, 0] │| + |└─────┴──────────┘| + └──────────────────┘ +""" + + +# TODO @dangotbanned: fix this? +# Constructor allows tuples, but we don't support that *everywhere* yet +IntoSchema: TypeAlias = "Mapping[str, dtypes.DType] | Schema" +"""Anything that can be converted into a Narwhals Schema. + +Defined by column names and their associated *instantiated* Narwhals DType. + +Examples: + >>> import narwhals as nw + >>> import pyarrow as pa + >>> data = {"a": [1, 2, 3], "b": [None, "hi", "howdy"], "c": [2.1, 2.0, None]} + >>> nw.DataFrame.from_dict( + ... data, + ... schema={"a": nw.UInt8(), "b": nw.String(), "c": nw.Float32()}, + ... backend="pyarrow", + ... ) + ┌────────────────────────┐ + | Narwhals DataFrame | + |------------------------| + |pyarrow.Table | + |a: uint8 | + |b: string | + |c: float | + |---- | + |a: [[1,2,3]] | + |b: [[null,"hi","howdy"]]| + |c: [[2.1,2,null]] | + └────────────────────────┘ +""" + +IntoArrowSchema: TypeAlias = "pa.Schema | Mapping[str, pa.DataType]" +IntoPolarsSchema: TypeAlias = "pl.Schema | Mapping[str, pl.DataType]" +IntoPandasSchema: TypeAlias = Mapping[str, PandasLikeDType] + +FileSource: TypeAlias = "str | os.PathLike[str]" +"""Path to a file. + +Either a string or an object that implements [`__fspath__`], such as [`pathlib.Path`]. + +[`__fspath__`]: https://docs.python.org/3/library/os.html#os.PathLike +[`pathlib.Path`]: https://docs.python.org/3/library/pathlib.html#pathlib.Path +""" + + +# Annotations for `__getitem__` methods +_T = TypeVar("_T") +_Slice: TypeAlias = "slice[_T, Any, Any] | slice[Any, _T, Any] | slice[None, None, _T]" +_SliceNone: TypeAlias = "slice[None, None, None]" +# Boolean positions +SizedMultiBoolSelector: TypeAlias = "Sequence[bool] | _T | _1DArrayBool" +# Index/column positions +SingleIndexSelector: TypeAlias = int +_SliceIndex: TypeAlias = "_Slice[int] | _SliceNone" +"""E.g. `[1:]` or `[:3]` or `[::2]`.""" +SizedMultiIndexSelector: TypeAlias = "Sequence[int] | _T | _1DArrayInt" +MultiIndexSelector: TypeAlias = "_SliceIndex | SizedMultiIndexSelector[_T]" +# Labels/column names +SingleNameSelector: TypeAlias = str +_SliceName: TypeAlias = "_Slice[str] | _SliceNone" +SizedMultiNameSelector: TypeAlias = "Sequence[str] | _T | _1DArray" +MultiNameSelector: TypeAlias = "_SliceName | SizedMultiNameSelector[_T]" +# Mixed selectors +SingleColSelector: TypeAlias = "SingleIndexSelector | SingleNameSelector" +MultiColSelector: TypeAlias = ( + "MultiIndexSelector[_T] | MultiNameSelector[_T] | SizedMultiBoolSelector[_T]" +) + + +__all__ = [ + "Backend", + "CompliantDataFrame", + "CompliantLazyFrame", + "CompliantSeries", + "DataFrameT", + "EagerAllowed", + "Frame", + "FrameT", + "IntoBackend", + "IntoDataFrame", + "IntoDataFrameT", + "IntoExpr", + "IntoFrame", + "IntoFrameT", + "IntoLazyFrame", + "IntoLazyFrameT", + "IntoSeries", + "IntoSeriesT", + "LazyAllowed", +] diff --git a/.venv_haddock/lib/python3.12/site-packages/narwhals/utils.py b/.venv_haddock/lib/python3.12/site-packages/narwhals/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..83e26873e04846e258f09aa9dfb69830c856f014 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/narwhals/utils.py @@ -0,0 +1,6 @@ +# Re-export some functions from `_utils` to make them public. +from __future__ import annotations + +from narwhals._utils import Implementation, Version, parse_version + +__all__ = ["Implementation", "Version", "parse_version"] diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__config__.py b/.venv_haddock/lib/python3.12/site-packages/numpy/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..1329b4257e1fd03d94fd5733d996d5b239556ec0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/__config__.py @@ -0,0 +1,170 @@ +# This file is generated by numpy's build process +# It contains system_info results at the time of building this package. +from enum import Enum +from numpy._core._multiarray_umath import ( + __cpu_features__, + __cpu_baseline__, + __cpu_dispatch__, +) + +__all__ = ["show_config"] +_built_with_meson = True + + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + + +def _cleanup(d): + """ + Removes empty values in a `dict` recursively + This ensures we remove values that Meson could not provide to CONFIG + """ + if isinstance(d, dict): + return {k: _cleanup(v) for k, v in d.items() if v and _cleanup(v)} + else: + return d + + +CONFIG = _cleanup( + { + "Compilers": { + "c": { + "name": "clang", + "linker": r"ld64", + "version": "15.0.0", + "commands": r"cc", + "args": r"", + "linker args": r"", + }, + "cython": { + "name": "cython", + "linker": r"cython", + "version": "3.2.4", + "commands": r"cython", + "args": r"", + "linker args": r"", + }, + "c++": { + "name": "clang", + "linker": r"ld64", + "version": "15.0.0", + "commands": r"c++", + "args": r"", + "linker args": r"", + }, + }, + "Machine Information": { + "host": { + "cpu": "aarch64", + "family": "aarch64", + "endian": "little", + "system": "darwin", + }, + "build": { + "cpu": "aarch64", + "family": "aarch64", + "endian": "little", + "system": "darwin", + }, + "cross-compiled": bool("False".lower().replace("false", "")), + }, + "Build Dependencies": { + "blas": { + "name": "accelerate", + "found": bool("True".lower().replace("false", "")), + "version": "unknown", + "detection method": "system", + "include directory": r"unknown", + "lib directory": r"unknown", + "openblas configuration": r"unknown", + "pc file directory": r"unknown", + }, + "lapack": { + "name": "accelerate", + "found": bool("True".lower().replace("false", "")), + "version": "unknown", + "detection method": "system", + "include directory": r"unknown", + "lib directory": r"unknown", + "openblas configuration": r"unknown", + "pc file directory": r"unknown", + }, + }, + "Python Information": { + "path": r"/private/var/folders/bb/km69qtt53nlbxc29ljr4c9d00000gn/T/build-env-8jz__88i/bin/python", + "version": "3.12", + }, + "SIMD Extensions": { + "baseline": __cpu_baseline__, + "found": [ + feature for feature in __cpu_dispatch__ if __cpu_features__[feature] + ], + "not found": [ + feature for feature in __cpu_dispatch__ if not __cpu_features__[feature] + ], + }, + } +) + + +def _check_pyyaml(): + import yaml + + return yaml + + +def show(mode=DisplayModes.stdout.value): + """ + Show libraries and system information on which NumPy was built + and is being used + + Parameters + ---------- + mode : {`'stdout'`, `'dicts'`}, optional. + Indicates how to display the config information. + `'stdout'` prints to console, `'dicts'` returns a dictionary + of the configuration. + + Returns + ------- + out : {`dict`, `None`} + If mode is `'dicts'`, a dict is returned, else None + + See Also + -------- + get_include : Returns the directory containing NumPy C + header files. + + Notes + ----- + 1. The `'stdout'` mode will give more readable + output if ``pyyaml`` is installed + + """ + if mode == DisplayModes.stdout.value: + try: # Non-standard library, check import + yaml = _check_pyyaml() + + print(yaml.dump(CONFIG)) + except ModuleNotFoundError: + import warnings + import json + + warnings.warn("Install `pyyaml` for better output", stacklevel=1) + print(json.dumps(CONFIG, indent=2)) + elif mode == DisplayModes.dicts.value: + return CONFIG + else: + raise AttributeError( + f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}" + ) + + +def show_config(mode=DisplayModes.stdout.value): + return show(mode) + + +show_config.__doc__ = show.__doc__ +show_config.__module__ = "numpy" diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/__config__.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/__config__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..21e8b01fdd96dcb5044758d1fa0a14839c5d1e3a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/__config__.pyi @@ -0,0 +1,108 @@ +from enum import Enum +from types import ModuleType +from typing import ( + Final, + Literal as L, + NotRequired, + TypedDict, + overload, + type_check_only, +) + +_CompilerConfigDictValue = TypedDict( + "_CompilerConfigDictValue", + { + "name": str, + "linker": str, + "version": str, + "commands": str, + "args": str, + "linker args": str, + }, +) +_CompilerConfigDict = TypedDict( + "_CompilerConfigDict", + { + "c": _CompilerConfigDictValue, + "cython": _CompilerConfigDictValue, + "c++": _CompilerConfigDictValue, + }, +) +_MachineInformationDict = TypedDict( + "_MachineInformationDict", + { + "host": _MachineInformationDictValue, + "build": _MachineInformationDictValue, + "cross-compiled": NotRequired[L[True]], + }, +) + +@type_check_only +class _MachineInformationDictValue(TypedDict): + cpu: str + family: str + endian: L["little", "big"] + system: str + +_BuildDependenciesDictValue = TypedDict( + "_BuildDependenciesDictValue", + { + "name": str, + "found": NotRequired[L[True]], + "version": str, + "include directory": str, + "lib directory": str, + "openblas configuration": str, + "pc file directory": str, + }, +) + +class _BuildDependenciesDict(TypedDict): + blas: _BuildDependenciesDictValue + lapack: _BuildDependenciesDictValue + +class _PythonInformationDict(TypedDict): + path: str + version: str + +_SIMDExtensionsDict = TypedDict( + "_SIMDExtensionsDict", + { + "baseline": list[str], + "found": list[str], + "not found": list[str], + }, +) + +_ConfigDict = TypedDict( + "_ConfigDict", + { + "Compilers": _CompilerConfigDict, + "Machine Information": _MachineInformationDict, + "Build Dependencies": _BuildDependenciesDict, + "Python Information": _PythonInformationDict, + "SIMD Extensions": _SIMDExtensionsDict, + }, +) + +### + +__all__ = ["show_config"] + +CONFIG: Final[_ConfigDict] = ... + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + +def _check_pyyaml() -> ModuleType: ... + +@overload +def show(mode: L["stdout"] = "stdout") -> None: ... +@overload +def show(mode: L["dicts"]) -> _ConfigDict: ... + +@overload +def show_config(mode: L["stdout"] = "stdout") -> None: ... +@overload +def show_config(mode: L["dicts"]) -> _ConfigDict: ... diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_configtool.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_configtool.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7e7363e797f3f5a33f66efd0349814c562e349e6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_configtool.pyi @@ -0,0 +1 @@ +def main() -> None: ... diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_distributor_init.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_distributor_init.py new file mode 100644 index 0000000000000000000000000000000000000000..f608036a2405528c0ddc4874b25b223dbe22c385 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_distributor_init.py @@ -0,0 +1,15 @@ +""" Distributor init file + +Distributors: you can add custom code here to support particular distributions +of numpy. + +For example, this is a good place to put any BLAS/LAPACK initialization code. + +The numpy standard source distribution will not put code in this file, so you +can safely replace this file with your own version. +""" + +try: + from . import _distributor_init_local # noqa: F401 +except ImportError: + pass diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_expired_attrs_2_0.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_expired_attrs_2_0.py new file mode 100644 index 0000000000000000000000000000000000000000..2eebf95bc558c609bd665ab120746420a5ccb432 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_expired_attrs_2_0.py @@ -0,0 +1,78 @@ +""" +Dict of expired attributes that are discontinued since 2.0 release. +Each item is associated with a migration note. +""" + +__expired_attributes__ = { + "geterrobj": "Use the np.errstate context manager instead.", + "seterrobj": "Use the np.errstate context manager instead.", + "cast": "Use `np.asarray(arr, dtype=dtype)` instead.", + "source": "Use `inspect.getsource` instead.", + "lookfor": "Search NumPy's documentation directly.", + "who": "Use an IDE variable explorer or `locals()` instead.", + "fastCopyAndTranspose": "Use `arr.T.copy()` instead.", + "set_numeric_ops": + "For the general case, use `PyUFunc_ReplaceLoopBySignature`. " + "For ndarray subclasses, define the ``__array_ufunc__`` method " + "and override the relevant ufunc.", + "NINF": "Use `-np.inf` instead.", + "PINF": "Use `np.inf` instead.", + "NZERO": "Use `-0.0` instead.", + "PZERO": "Use `0.0` instead.", + "add_newdoc": + "It's still available as `np.lib.add_newdoc`.", + "add_docstring": + "It's still available as `np.lib.add_docstring`.", + "add_newdoc_ufunc": + "It's an internal function and doesn't have a replacement.", + "safe_eval": "Use `ast.literal_eval` instead.", + "float_": "Use `np.float64` instead.", + "complex_": "Use `np.complex128` instead.", + "longfloat": "Use `np.longdouble` instead.", + "singlecomplex": "Use `np.complex64` instead.", + "cfloat": "Use `np.complex128` instead.", + "longcomplex": "Use `np.clongdouble` instead.", + "clongfloat": "Use `np.clongdouble` instead.", + "string_": "Use `np.bytes_` instead.", + "unicode_": "Use `np.str_` instead.", + "Inf": "Use `np.inf` instead.", + "Infinity": "Use `np.inf` instead.", + "NaN": "Use `np.nan` instead.", + "infty": "Use `np.inf` instead.", + "issctype": "Use `issubclass(rep, np.generic)` instead.", + "maximum_sctype": + "Use a specific dtype instead. You should avoid relying " + "on any implicit mechanism and select the largest dtype of " + "a kind explicitly in the code.", + "obj2sctype": "Use `np.dtype(obj).type` instead.", + "sctype2char": "Use `np.dtype(obj).char` instead.", + "sctypes": "Access dtypes explicitly instead.", + "issubsctype": "Use `np.issubdtype` instead.", + "set_string_function": + "Use `np.set_printoptions` instead with a formatter for " + "custom printing of NumPy objects.", + "asfarray": "Use `np.asarray` with a proper dtype instead.", + "issubclass_": "Use `issubclass` builtin instead.", + "tracemalloc_domain": "It's now available from `np.lib`.", + "mat": "Use `np.asmatrix` instead.", + "recfromcsv": "Use `np.genfromtxt` with comma delimiter instead.", + "recfromtxt": "Use `np.genfromtxt` instead.", + "deprecate": "Emit `DeprecationWarning` with `warnings.warn` directly, " + "or use `typing.deprecated`.", + "deprecate_with_doc": "Emit `DeprecationWarning` with `warnings.warn` " + "directly, or use `typing.deprecated`.", + "find_common_type": + "Use `numpy.promote_types` or `numpy.result_type` instead. " + "To achieve semantics for the `scalar_types` argument, use " + "`numpy.result_type` and pass the Python values `0`, `0.0`, or `0j`.", + "round_": "Use `np.round` instead.", + "get_array_wrap": "", + "DataSource": "It's still available as `np.lib.npyio.DataSource`.", + "nbytes": "Use `np.dtype().itemsize` instead.", + "byte_bounds": "Now it's available under `np.lib.array_utils.byte_bounds`", + "compare_chararrays": + "It's still available as `np.char.compare_chararrays`.", + "format_parser": "It's still available as `np.rec.format_parser`.", + "alltrue": "Use `np.all` instead.", + "sometrue": "Use `np.any` instead.", +} diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_expired_attrs_2_0.pyi b/.venv_haddock/lib/python3.12/site-packages/numpy/_expired_attrs_2_0.pyi new file mode 100644 index 0000000000000000000000000000000000000000..de6c2d10f9b0264238094e3ce9f8affafe5ca7a8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_expired_attrs_2_0.pyi @@ -0,0 +1,61 @@ +from typing import Final, TypedDict, final, type_check_only + +@final +@type_check_only +class _ExpiredAttributesType(TypedDict): + geterrobj: str + seterrobj: str + cast: str + source: str + lookfor: str + who: str + fastCopyAndTranspose: str + set_numeric_ops: str + NINF: str + PINF: str + NZERO: str + PZERO: str + add_newdoc: str + add_docstring: str + add_newdoc_ufunc: str + safe_eval: str + float_: str + complex_: str + longfloat: str + singlecomplex: str + cfloat: str + longcomplex: str + clongfloat: str + string_: str + unicode_: str + Inf: str + Infinity: str + NaN: str + infty: str + issctype: str + maximum_sctype: str + obj2sctype: str + sctype2char: str + sctypes: str + issubsctype: str + set_string_function: str + asfarray: str + issubclass_: str + tracemalloc_domain: str + mat: str + recfromcsv: str + recfromtxt: str + deprecate: str + deprecate_with_doc: str + find_common_type: str + round_: str + get_array_wrap: str + DataSource: str + nbytes: str + byte_bounds: str + compare_chararrays: str + format_parser: str + alltrue: str + sometrue: str + +__expired_attributes__: Final[_ExpiredAttributesType] = ... diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/_pytesttester.py b/.venv_haddock/lib/python3.12/site-packages/numpy/_pytesttester.py new file mode 100644 index 0000000000000000000000000000000000000000..77342e44aea0251c513dd0ed7a8fb67b074e298f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/_pytesttester.py @@ -0,0 +1,201 @@ +""" +Pytest test running. + +This module implements the ``test()`` function for NumPy modules. The usual +boiler plate for doing that is to put the following in the module +``__init__.py`` file:: + + from numpy._pytesttester import PytestTester + test = PytestTester(__name__) + del PytestTester + + +Warnings filtering and other runtime settings should be dealt with in the +``pytest.ini`` file in the numpy repo root. The behavior of the test depends on +whether or not that file is found as follows: + +* ``pytest.ini`` is present (develop mode) + All warnings except those explicitly filtered out are raised as error. +* ``pytest.ini`` is absent (release mode) + DeprecationWarnings and PendingDeprecationWarnings are ignored, other + warnings are passed through. + +In practice, tests run from the numpy repo are run in development mode with +``spin``, through the standard ``spin test`` invocation or from an inplace +build with ``pytest numpy``. + +This module is imported by every numpy subpackage, so lies at the top level to +simplify circular import issues. For the same reason, it contains no numpy +imports at module scope, instead importing numpy within function calls. +""" +import os +import sys + +__all__ = ['PytestTester'] + + +def _show_numpy_info(): + import numpy as np + + print(f"NumPy version {np.__version__}") + info = np.lib._utils_impl._opt_info() + print("NumPy CPU features: ", (info or 'nothing enabled')) + + +class PytestTester: + """ + Pytest test runner. + + A test function is typically added to a package's __init__.py like so:: + + from numpy._pytesttester import PytestTester + test = PytestTester(__name__).test + del PytestTester + + Calling this test function finds and runs all tests associated with the + module and all its sub-modules. + + Attributes + ---------- + module_name : str + Full path to the package to test. + + Parameters + ---------- + module_name : module name + The name of the module to test. + + Notes + ----- + Unlike the previous ``nose``-based implementation, this class is not + publicly exposed as it performs some ``numpy``-specific warning + suppression. + + """ + def __init__(self, module_name): + self.module_name = module_name + self.__module__ = module_name + + def __call__(self, label='fast', verbose=1, extra_argv=None, + doctests=False, coverage=False, durations=-1, tests=None): + """ + Run tests for module using pytest. + + Parameters + ---------- + label : {'fast', 'full'}, optional + Identifies the tests to run. When set to 'fast', tests decorated + with `pytest.mark.slow` are skipped, when 'full', the slow marker + is ignored. + verbose : int, optional + Verbosity value for test outputs, in the range 1-3. Default is 1. + extra_argv : list, optional + List with any extra arguments to pass to pytests. + doctests : bool, optional + .. note:: Not supported + coverage : bool, optional + If True, report coverage of NumPy code. Default is False. + Requires installation of (pip) pytest-cov. + durations : int, optional + If < 0, do nothing, If 0, report time of all tests, if > 0, + report the time of the slowest `timer` tests. Default is -1. + tests : test or list of tests + Tests to be executed with pytest '--pyargs' + + Returns + ------- + result : bool + Return True on success, false otherwise. + + Notes + ----- + Each NumPy module exposes `test` in its namespace to run all tests for + it. For example, to run all tests for numpy.lib: + + >>> np.lib.test() #doctest: +SKIP + + Examples + -------- + >>> result = np.lib.test() #doctest: +SKIP + ... + 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds + >>> result + True + + """ + import warnings + + import pytest + + module = sys.modules[self.module_name] + module_path = os.path.abspath(module.__path__[0]) + + # setup the pytest arguments + pytest_args = ["-l"] + + # offset verbosity. The "-q" cancels a "-v". + pytest_args += ["-q"] + + if sys.version_info < (3, 12): + with warnings.catch_warnings(): + warnings.simplefilter("always") + # Filter out distutils cpu warnings (could be localized to + # distutils tests). ASV has problems with top level import, + # so fetch module for suppression here. + from numpy.distutils import cpuinfo # noqa: F401 + + # Filter out annoying import messages. Want these in both develop and + # release mode. + pytest_args += [ + "-W ignore:Not importing directory", + "-W ignore:numpy.dtype size changed", + "-W ignore:numpy.ufunc size changed", + "-W ignore::UserWarning:cpuinfo", + ] + + # When testing matrices, ignore their PendingDeprecationWarnings + pytest_args += [ + "-W ignore:the matrix subclass is not", + "-W ignore:Importing from numpy.matlib is", + ] + + if doctests: + pytest_args += ["--doctest-modules"] + + if extra_argv: + pytest_args += list(extra_argv) + + if verbose > 1: + pytest_args += ["-" + "v" * (verbose - 1)] + + if coverage: + pytest_args += ["--cov=" + module_path] + + if label == "fast": + # not importing at the top level to avoid circular import of module + from numpy.testing import IS_PYPY + if IS_PYPY: + pytest_args += ["-m", "not slow and not slow_pypy"] + else: + pytest_args += ["-m", "not slow"] + + elif label != "full": + pytest_args += ["-m", label] + + if durations >= 0: + pytest_args += [f"--durations={durations}"] + + if tests is None: + tests = [self.module_name] + + pytest_args += ["--pyargs"] + list(tests) + + # run tests. + _show_numpy_info() + + try: + code = pytest.main(pytest_args) + except SystemExit as exc: + code = exc.code + + return code == 0 diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/exceptions.py b/.venv_haddock/lib/python3.12/site-packages/numpy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..cf70b4a4ce3bd752fc9dc10d32de8646217d9ef1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/exceptions.py @@ -0,0 +1,246 @@ +""" +Exceptions and Warnings +======================= + +General exceptions used by NumPy. Note that some exceptions may be module +specific, such as linear algebra errors. + +.. versionadded:: NumPy 1.25 + + The exceptions module is new in NumPy 1.25. + +.. currentmodule:: numpy.exceptions + +Warnings +-------- +.. autosummary:: + :toctree: generated/ + + ComplexWarning Given when converting complex to real. + VisibleDeprecationWarning Same as a DeprecationWarning, but more visible. + RankWarning Issued when the design matrix is rank deficient. + +Exceptions +---------- +.. autosummary:: + :toctree: generated/ + + AxisError Given when an axis was invalid. + DTypePromotionError Given when no common dtype could be found. + TooHardError Error specific to `numpy.shares_memory`. + +""" + + +__all__ = [ + "ComplexWarning", "VisibleDeprecationWarning", "ModuleDeprecationWarning", + "TooHardError", "AxisError", "DTypePromotionError"] + + +# Disallow reloading this module so as to preserve the identities of the +# classes defined here. +if '_is_loaded' in globals(): + raise RuntimeError('Reloading numpy._globals is not allowed') +_is_loaded = True + + +class ComplexWarning(RuntimeWarning): + """ + The warning raised when casting a complex dtype to a real dtype. + + As implemented, casting a complex number to a real discards its imaginary + part, but this behavior may not be what the user actually wants. + + """ + pass + + +class ModuleDeprecationWarning(DeprecationWarning): + """Module deprecation warning. + + .. warning:: + + This warning should not be used, since nose testing is not relevant + anymore. + + The nose tester turns ordinary Deprecation warnings into test failures. + That makes it hard to deprecate whole modules, because they get + imported by default. So this is a special Deprecation warning that the + nose tester will let pass without making tests fail. + + """ + pass + + +class VisibleDeprecationWarning(UserWarning): + """Visible deprecation warning. + + By default, python will not show deprecation warnings, so this class + can be used when a very visible warning is helpful, for example because + the usage is most likely a user bug. + + """ + pass + + +class RankWarning(RuntimeWarning): + """Matrix rank warning. + + Issued by polynomial functions when the design matrix is rank deficient. + + """ + pass + + +# Exception used in shares_memory() +class TooHardError(RuntimeError): + """``max_work`` was exceeded. + + This is raised whenever the maximum number of candidate solutions + to consider specified by the ``max_work`` parameter is exceeded. + Assigning a finite number to ``max_work`` may have caused the operation + to fail. + + """ + pass + + +class AxisError(ValueError, IndexError): + """Axis supplied was invalid. + + This is raised whenever an ``axis`` parameter is specified that is larger + than the number of array dimensions. + For compatibility with code written against older numpy versions, which + raised a mixture of :exc:`ValueError` and :exc:`IndexError` for this + situation, this exception subclasses both to ensure that + ``except ValueError`` and ``except IndexError`` statements continue + to catch ``AxisError``. + + Parameters + ---------- + axis : int or str + The out of bounds axis or a custom exception message. + If an axis is provided, then `ndim` should be specified as well. + ndim : int, optional + The number of array dimensions. + msg_prefix : str, optional + A prefix for the exception message. + + Attributes + ---------- + axis : int, optional + The out of bounds axis or ``None`` if a custom exception + message was provided. This should be the axis as passed by + the user, before any normalization to resolve negative indices. + + .. versionadded:: 1.22 + ndim : int, optional + The number of array dimensions or ``None`` if a custom exception + message was provided. + + .. versionadded:: 1.22 + + + Examples + -------- + >>> import numpy as np + >>> array_1d = np.arange(10) + >>> np.cumsum(array_1d, axis=1) + Traceback (most recent call last): + ... + numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1 + + Negative axes are preserved: + + >>> np.cumsum(array_1d, axis=-2) + Traceback (most recent call last): + ... + numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1 + + The class constructor generally takes the axis and arrays' + dimensionality as arguments: + + >>> print(np.exceptions.AxisError(2, 1, msg_prefix='error')) + error: axis 2 is out of bounds for array of dimension 1 + + Alternatively, a custom exception message can be passed: + + >>> print(np.exceptions.AxisError('Custom error message')) + Custom error message + + """ + + __slots__ = ("_msg", "axis", "ndim") + + def __init__(self, axis, ndim=None, msg_prefix=None): + if ndim is msg_prefix is None: + # single-argument form: directly set the error message + self._msg = axis + self.axis = None + self.ndim = None + else: + self._msg = msg_prefix + self.axis = axis + self.ndim = ndim + + def __str__(self): + axis = self.axis + ndim = self.ndim + + if axis is ndim is None: + return self._msg + else: + msg = f"axis {axis} is out of bounds for array of dimension {ndim}" + if self._msg is not None: + msg = f"{self._msg}: {msg}" + return msg + + +class DTypePromotionError(TypeError): + """Multiple DTypes could not be converted to a common one. + + This exception derives from ``TypeError`` and is raised whenever dtypes + cannot be converted to a single common one. This can be because they + are of a different category/class or incompatible instances of the same + one (see Examples). + + Notes + ----- + Many functions will use promotion to find the correct result and + implementation. For these functions the error will typically be chained + with a more specific error indicating that no implementation was found + for the input dtypes. + + Typically promotion should be considered "invalid" between the dtypes of + two arrays when `arr1 == arr2` can safely return all ``False`` because the + dtypes are fundamentally different. + + Examples + -------- + Datetimes and complex numbers are incompatible classes and cannot be + promoted: + + >>> import numpy as np + >>> np.result_type(np.dtype("M8[s]"), np.complex128) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + DTypePromotionError: The DType could not + be promoted by . This means that no common + DType exists for the given inputs. For example they cannot be stored in a + single array unless the dtype is `object`. The full list of DTypes is: + (, ) + + For example for structured dtypes, the structure can mismatch and the + same ``DTypePromotionError`` is given when two structured dtypes with + a mismatch in their number of fields is given: + + >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)]) + >>> dtype2 = np.dtype([("field1", np.float64)]) + >>> np.promote_types(dtype1, dtype2) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + DTypePromotionError: field names `('field1', 'field2')` and `('field1',)` + mismatch. + + """ # noqa: E501 + pass diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/matlib.py b/.venv_haddock/lib/python3.12/site-packages/numpy/matlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f27d503cdbca80c745b14b8854afecc56125df9a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/numpy/matlib.py @@ -0,0 +1,380 @@ +import warnings + +# 2018-05-29, PendingDeprecationWarning added to matrix.__new__ +# 2020-01-23, numpy 1.19.0 PendingDeprecatonWarning +warnings.warn("Importing from numpy.matlib is deprecated since 1.19.0. " + "The matrix subclass is not the recommended way to represent " + "matrices or deal with linear algebra (see " + "https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html). " + "Please adjust your code to use regular ndarray. ", + PendingDeprecationWarning, stacklevel=2) + +import numpy as np + +# Matlib.py contains all functions in the numpy namespace with a few +# replacements. See doc/source/reference/routines.matlib.rst for details. +# Need * as we're copying the numpy namespace. +from numpy import * # noqa: F403 +from numpy.matrixlib.defmatrix import asmatrix, matrix + +__version__ = np.__version__ + +__all__ = ['rand', 'randn', 'repmat'] +__all__ += np.__all__ + +def empty(shape, dtype=None, order='C'): + """Return a new matrix of given shape and type, without initializing entries. + + Parameters + ---------- + shape : int or tuple of int + Shape of the empty matrix. + dtype : data-type, optional + Desired output data-type. + order : {'C', 'F'}, optional + Whether to store multi-dimensional data in row-major + (C-style) or column-major (Fortran-style) order in + memory. + + See Also + -------- + numpy.empty : Equivalent array function. + matlib.zeros : Return a matrix of zeros. + matlib.ones : Return a matrix of ones. + + Notes + ----- + Unlike other matrix creation functions (e.g. `matlib.zeros`, + `matlib.ones`), `matlib.empty` does not initialize the values of the + matrix, and may therefore be marginally faster. However, the values + stored in the newly allocated matrix are arbitrary. For reproducible + behavior, be sure to set each element of the matrix before reading. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.empty((2, 2)) # filled with random data + matrix([[ 6.76425276e-320, 9.79033856e-307], # random + [ 7.39337286e-309, 3.22135945e-309]]) + >>> np.matlib.empty((2, 2), dtype=int) + matrix([[ 6600475, 0], # random + [ 6586976, 22740995]]) + + """ + return ndarray.__new__(matrix, shape, dtype, order=order) + +def ones(shape, dtype=None, order='C'): + """ + Matrix of ones. + + Return a matrix of given shape and type, filled with ones. + + Parameters + ---------- + shape : {sequence of ints, int} + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is np.float64. + order : {'C', 'F'}, optional + Whether to store matrix in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Matrix of ones of given shape, dtype, and order. + + See Also + -------- + ones : Array of ones. + matlib.zeros : Zero matrix. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> np.matlib.ones((2,3)) + matrix([[1., 1., 1.], + [1., 1., 1.]]) + + >>> np.matlib.ones(2) + matrix([[1., 1.]]) + + """ + a = ndarray.__new__(matrix, shape, dtype, order=order) + a.fill(1) + return a + +def zeros(shape, dtype=None, order='C'): + """ + Return a matrix of given shape and type, filled with zeros. + + Parameters + ---------- + shape : int or sequence of ints + Shape of the matrix + dtype : data-type, optional + The desired data-type for the matrix, default is float. + order : {'C', 'F'}, optional + Whether to store the result in C- or Fortran-contiguous order, + default is 'C'. + + Returns + ------- + out : matrix + Zero matrix of given shape, dtype, and order. + + See Also + -------- + numpy.zeros : Equivalent array function. + matlib.ones : Return a matrix of ones. + + Notes + ----- + If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, + `out` becomes a single row matrix of shape ``(1,N)``. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.zeros((2, 3)) + matrix([[0., 0., 0.], + [0., 0., 0.]]) + + >>> np.matlib.zeros(2) + matrix([[0., 0.]]) + + """ + a = ndarray.__new__(matrix, shape, dtype, order=order) + a.fill(0) + return a + +def identity(n, dtype=None): + """ + Returns the square identity matrix of given size. + + Parameters + ---------- + n : int + Size of the returned identity matrix. + dtype : data-type, optional + Data-type of the output. Defaults to ``float``. + + Returns + ------- + out : matrix + `n` x `n` matrix with its main diagonal set to one, + and all other elements zero. + + See Also + -------- + numpy.identity : Equivalent array function. + matlib.eye : More general matrix identity function. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.identity(3, dtype=int) + matrix([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + """ + a = array([1] + n * [0], dtype=dtype) + b = empty((n, n), dtype=dtype) + b.flat = a + return b + +def eye(n, M=None, k=0, dtype=float, order='C'): + """ + Return a matrix with ones on the diagonal and zeros elsewhere. + + Parameters + ---------- + n : int + Number of rows in the output. + M : int, optional + Number of columns in the output, defaults to `n`. + k : int, optional + Index of the diagonal: 0 refers to the main diagonal, + a positive value refers to an upper diagonal, + and a negative value to a lower diagonal. + dtype : dtype, optional + Data-type of the returned matrix. + order : {'C', 'F'}, optional + Whether the output should be stored in row-major (C-style) or + column-major (Fortran-style) order in memory. + + Returns + ------- + I : matrix + A `n` x `M` matrix where all elements are equal to zero, + except for the `k`-th diagonal, whose values are equal to one. + + See Also + -------- + numpy.eye : Equivalent array function. + identity : Square identity matrix. + + Examples + -------- + >>> import numpy.matlib + >>> np.matlib.eye(3, k=1, dtype=float) + matrix([[0., 1., 0.], + [0., 0., 1.], + [0., 0., 0.]]) + + """ + return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order)) + +def rand(*args): + """ + Return a matrix of random values with given shape. + + Create a matrix of the given shape and propagate it with + random samples from a uniform distribution over ``[0, 1)``. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. + If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + out : ndarray + The matrix of random values with shape given by `\\*args`. + + See Also + -------- + randn, numpy.random.RandomState.rand + + Examples + -------- + >>> np.random.seed(123) + >>> import numpy.matlib + >>> np.matlib.rand(2, 3) + matrix([[0.69646919, 0.28613933, 0.22685145], + [0.55131477, 0.71946897, 0.42310646]]) + >>> np.matlib.rand((2, 3)) + matrix([[0.9807642 , 0.68482974, 0.4809319 ], + [0.39211752, 0.34317802, 0.72904971]]) + + If the first argument is a tuple, other arguments are ignored: + + >>> np.matlib.rand((2, 3), 4) + matrix([[0.43857224, 0.0596779 , 0.39804426], + [0.73799541, 0.18249173, 0.17545176]]) + + """ + if isinstance(args[0], tuple): + args = args[0] + return asmatrix(np.random.rand(*args)) + +def randn(*args): + """ + Return a random matrix with data from the "standard normal" distribution. + + `randn` generates a matrix filled with random floats sampled from a + univariate "normal" (Gaussian) distribution of mean 0 and variance 1. + + Parameters + ---------- + \\*args : Arguments + Shape of the output. + If given as N integers, each integer specifies the size of one + dimension. If given as a tuple, this tuple gives the complete shape. + + Returns + ------- + Z : matrix of floats + A matrix of floating-point samples drawn from the standard normal + distribution. + + See Also + -------- + rand, numpy.random.RandomState.randn + + Notes + ----- + For random samples from the normal distribution with mean ``mu`` and + standard deviation ``sigma``, use:: + + sigma * np.matlib.randn(...) + mu + + Examples + -------- + >>> np.random.seed(123) + >>> import numpy.matlib + >>> np.matlib.randn(1) + matrix([[-1.0856306]]) + >>> np.matlib.randn(1, 2, 3) + matrix([[ 0.99734545, 0.2829785 , -1.50629471], + [-0.57860025, 1.65143654, -2.42667924]]) + + Two-by-four matrix of samples from the normal distribution with + mean 3 and standard deviation 2.5: + + >>> 2.5 * np.matlib.randn((2, 4)) + 3 + matrix([[1.92771843, 6.16484065, 0.83314899, 1.30278462], + [2.76322758, 6.72847407, 1.40274501, 1.8900451 ]]) + + """ + if isinstance(args[0], tuple): + args = args[0] + return asmatrix(np.random.randn(*args)) + +def repmat(a, m, n): + """ + Repeat a 0-D to 2-D array or matrix MxN times. + + Parameters + ---------- + a : array_like + The array or matrix to be repeated. + m, n : int + The number of times `a` is repeated along the first and second axes. + + Returns + ------- + out : ndarray + The result of repeating `a`. + + Examples + -------- + >>> import numpy.matlib + >>> a0 = np.array(1) + >>> np.matlib.repmat(a0, 2, 3) + array([[1, 1, 1], + [1, 1, 1]]) + + >>> a1 = np.arange(4) + >>> np.matlib.repmat(a1, 2, 2) + array([[0, 1, 2, 3, 0, 1, 2, 3], + [0, 1, 2, 3, 0, 1, 2, 3]]) + + >>> a2 = np.asmatrix(np.arange(6).reshape(2, 3)) + >>> np.matlib.repmat(a2, 2, 3) + matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5], + [0, 1, 2, 0, 1, 2, 0, 1, 2], + [3, 4, 5, 3, 4, 5, 3, 4, 5]]) + + """ + a = asanyarray(a) + ndim = a.ndim + if ndim == 0: + origrows, origcols = (1, 1) + elif ndim == 1: + origrows, origcols = (1, a.shape[0]) + else: + origrows, origcols = a.shape + rows = origrows * m + cols = origcols * n + c = a.reshape(1, a.size).repeat(m, 0).reshape(rows, origcols).repeat(n, 0) + return c.reshape(rows, cols) diff --git a/.venv_haddock/lib/python3.12/site-packages/numpy/py.typed b/.venv_haddock/lib/python3.12/site-packages/numpy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c1b3d36f8d2b742ea4f8f3fdd44fc32fc9c59f1e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/METADATA @@ -0,0 +1,108 @@ +Metadata-Version: 2.4 +Name: packaging +Version: 26.1 +Summary: Core utilities for Python packages +Author-email: Donald Stufft +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-Expression: Apache-2.0 OR BSD-2-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient +Classifier: Typing :: Typed +License-File: LICENSE +License-File: LICENSE.APACHE +License-File: LICENSE.BSD +Project-URL: Documentation, https://packaging.pypa.io/ +Project-URL: Source, https://github.com/pypa/packaging + +packaging +========= + +.. start-intro + +Reusable core utilities for various Python Packaging +`interoperability specifications `_. + +This library provides utilities that implement the interoperability +specifications which have clearly one correct behaviour (eg: :pep:`440`) +or benefit greatly from having a single shared implementation (eg: :pep:`425`). + +.. end-intro + +The ``packaging`` project includes the following: version handling, specifiers, +markers, requirements, tags, metadata, lockfiles, utilities. + +Documentation +------------- + +The `documentation`_ provides information and the API for the following: + +- Version Handling +- Specifiers +- Markers +- Requirements +- Tags +- Metadata +- Lockfiles +- Utilities + +Installation +------------ + +Use ``pip`` to install these utilities:: + + pip install packaging + +The ``packaging`` library uses calendar-based versioning (``YY.N``). + +Discussion +---------- + +If you run into bugs, you can file them in our `issue tracker`_. + +You can also join discussions on `GitHub Discussions`_ to ask questions or get involved. + +.. _`documentation`: https://packaging.pypa.io/ +.. _`issue tracker`: https://github.com/pypa/packaging/issues +.. _`GitHub Discussions`: https://github.com/pypa/packaging/discussions + + +Code of Conduct +--------------- + +Everyone interacting in the packaging project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + +Contributing +------------ + +The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as +well as how to report a potential security issue. The documentation for this +project also covers information about `project development`_ and `security`_. + +.. _`project development`: https://packaging.pypa.io/en/latest/development/ +.. _`security`: https://packaging.pypa.io/en/latest/security/ + +Project History +--------------- + +Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for +recent changes and project history. + +.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ + diff --git a/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f3e2427c0ce872faaf53d625ff20b84717769a85 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/RECORD @@ -0,0 +1,46 @@ +packaging-26.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +packaging-26.1.dist-info/METADATA,sha256=7l9S61gHv-txB4r0GDduSfhr5sLI0m_N6OzcnnPjp5Q,3473 +packaging-26.1.dist-info/RECORD,, +packaging-26.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +packaging-26.1.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +packaging-26.1.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +packaging-26.1.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +packaging/__init__.py,sha256=VdPTbH5gdO5lDUfejETmJNtXxCpKSrFb15J4xMyje8w,494 +packaging/__pycache__/__init__.cpython-312.pyc,, +packaging/__pycache__/_elffile.cpython-312.pyc,, +packaging/__pycache__/_manylinux.cpython-312.pyc,, +packaging/__pycache__/_musllinux.cpython-312.pyc,, +packaging/__pycache__/_parser.cpython-312.pyc,, +packaging/__pycache__/_tokenizer.cpython-312.pyc,, +packaging/__pycache__/dependency_groups.cpython-312.pyc,, +packaging/__pycache__/direct_url.cpython-312.pyc,, +packaging/__pycache__/errors.cpython-312.pyc,, +packaging/__pycache__/markers.cpython-312.pyc,, +packaging/__pycache__/metadata.cpython-312.pyc,, +packaging/__pycache__/pylock.cpython-312.pyc,, +packaging/__pycache__/requirements.cpython-312.pyc,, +packaging/__pycache__/specifiers.cpython-312.pyc,, +packaging/__pycache__/tags.cpython-312.pyc,, +packaging/__pycache__/utils.cpython-312.pyc,, +packaging/__pycache__/version.cpython-312.pyc,, +packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211 +packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559 +packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707 +packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518 +packaging/_tokenizer.py,sha256=tFU2Wr-ZZJdAbkXLEJo7qUQDJaIkfft9DqaifiEND7A,5391 +packaging/dependency_groups.py,sha256=XZIAVFK9uHG4RCGprmJn3VInUWMesxha_kytJuMO9eY,10218 +packaging/direct_url.py,sha256=eKmbDiPP1sLV4Mj_kCSZqqknrIyVO9Sr7JpF8KCjp4U,10917 +packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680 +packaging/licenses/__init__.py,sha256=_Jx0XRiD_58palsWnyLrLuh59ZpGCPIPXLKdZo9OJvQ,7293 +packaging/licenses/__pycache__/__init__.cpython-312.pyc,, +packaging/licenses/__pycache__/_spdx.cpython-312.pyc,, +packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122 +packaging/markers.py,sha256=8D4eXn7MPfjCOHoM0RHkgWumkokORY21pXiK_XDXnL0,15258 +packaging/metadata.py,sha256=rK19fQhrBNv3nINqurpuo-QsCZQuWnmSEaR4Hp-76Js,38691 +packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging/pylock.py,sha256=G_1gncTmDbRLY1jo4VDI9Uw-b5IErh_Q9V_BbVJTmD8,33890 +packaging/requirements.py,sha256=ttyeCsLD19hoHCUChqixMKkocDGqWmXxzGZWs7IhUSA,2984 +packaging/specifiers.py,sha256=vr9t7nC5VDqapdOqbMa2tDxJcHE_elq5rBtAh3YRwKc,65328 +packaging/tags.py,sha256=nwfsCqWxlB3hZ8kxE9xayLykDnLLbYhAsNbOCENh6GM,32421 +packaging/utils.py,sha256=M7-JMKic2sP1YtV_8aW7eVGB-x3ADuKCiSrsVeCd2Uo,9848 +packaging/version.py,sha256=4XfXTSkh90jQWycNJpwJT4dBs59RSVVvJPeb30s1VnU,35427 diff --git a/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/packaging-26.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/LICENSE b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..733963a744c3d6710058de9f0ea316893c5492ca --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/LICENSE @@ -0,0 +1,1250 @@ +BSD 3-Clause License + +Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team +All rights reserved. + +Copyright (c) 2011-2023, Open source contributors. + +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 copyright holder 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. +Copyright (c) 2010-2019 Keith Goodman +Copyright (c) 2019 Bottleneck 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. + +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.Copyright 2017- Paul Ganssle +Copyright 2017- dateutil contributors (see AUTHORS file) + + Licensed 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. + +The above license applies to all contributions after 2017-12-01, as well as +all contributions that have been re-licensed (see AUTHORS file for the list of +contributors who have re-licensed their code). +-------------------------------------------------------------------------------- +dateutil - Extensions to the standard Python datetime module. + +Copyright (c) 2003-2011 - Gustavo Niemeyer +Copyright (c) 2012-2014 - Tomi Pieviläinen +Copyright (c) 2014-2016 - Yaron de Leeuw +Copyright (c) 2015- - Paul Ganssle +Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + +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 copyright holder 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. + +The above BSD License Applies to all code, even that also covered by Apache 2.0.# MIT License + +Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +Based on http://opensource.org/licenses/MIT + +This is a template. Complete and ship as file LICENSE the following 2 +lines (only) + +YEAR: +COPYRIGHT HOLDER: + +and specify as + +License: MIT + file LICENSE + +Copyright (c) , + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +The MIT License + +Copyright (c) 2008- Attractive Chaos + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.musl as a whole is licensed under the following standard MIT license: + +---------------------------------------------------------------------- +Copyright © 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +---------------------------------------------------------------------- + +Authors/contributors include: + +A. Wilcox +Ada Worcester +Alex Dowad +Alex Suykov +Alexander Monakov +Andre McCurdy +Andrew Kelley +Anthony G. Basile +Aric Belsito +Arvid Picciani +Bartosz Brachaczek +Benjamin Peterson +Bobby Bingham +Boris Brezillon +Brent Cook +Chris Spiegel +Clément Vasseur +Daniel Micay +Daniel Sabogal +Daurnimator +David Carlier +David Edelsohn +Denys Vlasenko +Dmitry Ivanov +Dmitry V. Levin +Drew DeVault +Emil Renner Berthing +Fangrui Song +Felix Fietkau +Felix Janda +Gianluca Anzolin +Hauke Mehrtens +He X +Hiltjo Posthuma +Isaac Dunham +Jaydeep Patil +Jens Gustedt +Jeremy Huntwork +Jo-Philipp Wich +Joakim Sindholt +John Spencer +Julien Ramseier +Justin Cormack +Kaarle Ritvanen +Khem Raj +Kylie McClain +Leah Neukirchen +Luca Barbato +Luka Perkov +M Farkas-Dyck (Strake) +Mahesh Bodapati +Markus Wichmann +Masanori Ogino +Michael Clark +Michael Forney +Mikhail Kremnyov +Natanael Copa +Nicholas J. Kain +orc +Pascal Cuoq +Patrick Oppenlander +Petr Hosek +Petr Skocik +Pierre Carrier +Reini Urban +Rich Felker +Richard Pennington +Ryan Fairfax +Samuel Holland +Segev Finer +Shiz +sin +Solar Designer +Stefan Kristiansson +Stefan O'Rear +Szabolcs Nagy +Timo Teräs +Trutz Behn +Valentin Ochs +Will Dietz +William Haddon +William Pitcock + +Portions of this software are derived from third-party works licensed +under terms compatible with the above MIT license: + +The TRE regular expression implementation (src/regex/reg* and +src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed +under a 2-clause BSD license (license text in the source files). The +included version has been heavily modified by Rich Felker in 2012, in +the interests of size, simplicity, and namespace cleanliness. + +Much of the math library code (src/math/* and src/complex/*) is +Copyright © 1993,2004 Sun Microsystems or +Copyright © 2003-2011 David Schultz or +Copyright © 2003-2009 Steven G. Kargl or +Copyright © 2003-2009 Bruce D. Evans or +Copyright © 2008 Stephen L. Moshier or +Copyright © 2017-2018 Arm Limited +and labelled as such in comments in the individual source files. All +have been licensed under extremely permissive terms. + +The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008 +The Android Open Source Project and is licensed under a two-clause BSD +license. It was taken from Bionic libc, used on Android. + +The AArch64 memcpy and memset code (src/string/aarch64/*) are +Copyright © 1999-2019, Arm Limited. + +The implementation of DES for crypt (src/crypt/crypt_des.c) is +Copyright © 1994 David Burren. It is licensed under a BSD license. + +The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was +originally written by Solar Designer and placed into the public +domain. The code also comes with a fallback permissive license for use +in jurisdictions that may not recognize the public domain. + +The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011 +Valentin Ochs and is licensed under an MIT-style license. + +The x86_64 port was written by Nicholas J. Kain and is licensed under +the standard MIT terms. + +The mips and microblaze ports were originally written by Richard +Pennington for use in the ellcc project. The original code was adapted +by Rich Felker for build system and code conventions during upstream +integration. It is licensed under the standard MIT terms. + +The mips64 port was contributed by Imagination Technologies and is +licensed under the standard MIT terms. + +The powerpc port was also originally written by Richard Pennington, +and later supplemented and integrated by John Spencer. It is licensed +under the standard MIT terms. + +All other files which have no copyright comments are original works +produced specifically for use as part of this library, written either +by Rich Felker, the main author of the library, or by one or more +contibutors listed above. Details on authorship of individual files +can be found in the git version control history of the project. The +omission of copyright and license comments in each file is in the +interest of source tree size. + +In addition, permission is hereby granted for all public header files +(include/* and arch/*/bits/*) and crt files intended to be linked into +applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit +the copyright notice and permission notice otherwise required by the +license, and to use these files without any requirement of +attribution. These files include substantial contributions from: + +Bobby Bingham +John Spencer +Nicholas J. Kain +Rich Felker +Richard Pennington +Stefan Kristiansson +Szabolcs Nagy + +all of whom have explicitly granted such permission. + +This file previously contained text expressing a belief that most of +the files covered by the above exception were sufficiently trivial not +to be subject to copyright, resulting in confusion over whether it +negated the permissions granted in the license. In the spirit of +permissive licensing, and of not having licensing issues being an +obstacle to adoption, that text has been removed.Copyright (c) 2005-2023, NumPy 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 NumPy Developers nor the names of any + 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. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + +Copyright (c) Donald Stufft and individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + +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.A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +Copyright (c) 2014, Al Sweigart +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 {organization} 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.Copyright (c) 2017 Anthony Sottile + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.Copyright (c) 2015-2019 Jared Hobbs + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.Developed by ESN, an Electronic Arts Inc. studio. +Copyright (c) 2014, Electronic Arts Inc. +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 ESN, Electronic Arts Inc. 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 ELECTRONIC ARTS INC. 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. + +---- + +Portions of code from MODP_ASCII - Ascii transformations (upper/lower, etc) +https://github.com/client9/stringencoders + + Copyright 2005, 2006, 2007 + Nick Galbreath -- nickg [at] modp [dot] com + 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 modp.com 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. + + This is the standard "new" BSD license: + http://www.opensource.org/licenses/bsd-license.php + +https://github.com/client9/stringencoders/blob/cfd5c1507325ae497ea9bacdacba12c0ffd79d30/COPYING + +---- + +Numeric decoder derived from from TCL library +https://opensource.apple.com/source/tcl/tcl-14/tcl/license.terms + * Copyright (c) 1988-1993 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + + This software is copyrighted by the Regents of the University of + California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState + Corporation and other parties. The following terms apply to all files + associated with the software unless explicitly disclaimed in + individual files. + + The authors hereby grant permission to use, copy, modify, distribute, + and license this software and its documentation for any purpose, provided + that existing copyright notices are retained in all copies and that this + notice is included verbatim in any distributions. No written agreement, + license, or royalty fee is required for any of the authorized uses. + Modifications to this software may be copyrighted by their authors + and need not follow the licensing terms described here, provided that + the new terms are clearly indicated on the first page of each file where + they apply. + + IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY + FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY + DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE + IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE + NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR + MODIFICATIONS. + + GOVERNMENT USE: If you are acquiring this software on behalf of the + U.S. government, the Government shall have only "Restricted Rights" + in the software and related documentation as defined in the Federal + Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you + are acquiring the software on behalf of the Department of Defense, the + software shall be classified as "Commercial Computer Software" and the + Government shall have only "Restricted Rights" as defined in Clause + 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the + authors grant the U.S. Government and others acting in its behalf + permission to use and distribute the software in accordance with the + terms specified in this license.Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..6bb36031ec37644414b37ecde8f46e52e05fbc8b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/METADATA @@ -0,0 +1,1574 @@ +Metadata-Version: 2.1 +Name: pandas +Version: 2.3.3 +Summary: Powerful data structures for data analysis, time series, and statistics +Author-Email: The Pandas Development Team +License: BSD 3-Clause License + + Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team + All rights reserved. + + Copyright (c) 2011-2023, Open source contributors. + + 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 copyright holder 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. + Copyright (c) 2010-2019 Keith Goodman + Copyright (c) 2019 Bottleneck 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. + + 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.Copyright 2017- Paul Ganssle + Copyright 2017- dateutil contributors (see AUTHORS file) + + Licensed 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. + + The above license applies to all contributions after 2017-12-01, as well as + all contributions that have been re-licensed (see AUTHORS file for the list of + contributors who have re-licensed their code). + -------------------------------------------------------------------------------- + dateutil - Extensions to the standard Python datetime module. + + Copyright (c) 2003-2011 - Gustavo Niemeyer + Copyright (c) 2012-2014 - Tomi Pieviläinen + Copyright (c) 2014-2016 - Yaron de Leeuw + Copyright (c) 2015- - Paul Ganssle + Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + + 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 copyright holder 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. + + The above BSD License Applies to all code, even that also covered by Apache 2.0.# MIT License + + Copyright (c) 2019 Hadley Wickham; RStudio; and Evan Miller + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + Based on http://opensource.org/licenses/MIT + + This is a template. Complete and ship as file LICENSE the following 2 + lines (only) + + YEAR: + COPYRIGHT HOLDER: + + and specify as + + License: MIT + file LICENSE + + Copyright (c) , + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + The MIT License + + Copyright (c) 2008- Attractive Chaos + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE.musl as a whole is licensed under the following standard MIT license: + + ---------------------------------------------------------------------- + Copyright © 2005-2020 Rich Felker, et al. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + ---------------------------------------------------------------------- + + Authors/contributors include: + + A. Wilcox + Ada Worcester + Alex Dowad + Alex Suykov + Alexander Monakov + Andre McCurdy + Andrew Kelley + Anthony G. Basile + Aric Belsito + Arvid Picciani + Bartosz Brachaczek + Benjamin Peterson + Bobby Bingham + Boris Brezillon + Brent Cook + Chris Spiegel + Clément Vasseur + Daniel Micay + Daniel Sabogal + Daurnimator + David Carlier + David Edelsohn + Denys Vlasenko + Dmitry Ivanov + Dmitry V. Levin + Drew DeVault + Emil Renner Berthing + Fangrui Song + Felix Fietkau + Felix Janda + Gianluca Anzolin + Hauke Mehrtens + He X + Hiltjo Posthuma + Isaac Dunham + Jaydeep Patil + Jens Gustedt + Jeremy Huntwork + Jo-Philipp Wich + Joakim Sindholt + John Spencer + Julien Ramseier + Justin Cormack + Kaarle Ritvanen + Khem Raj + Kylie McClain + Leah Neukirchen + Luca Barbato + Luka Perkov + M Farkas-Dyck (Strake) + Mahesh Bodapati + Markus Wichmann + Masanori Ogino + Michael Clark + Michael Forney + Mikhail Kremnyov + Natanael Copa + Nicholas J. Kain + orc + Pascal Cuoq + Patrick Oppenlander + Petr Hosek + Petr Skocik + Pierre Carrier + Reini Urban + Rich Felker + Richard Pennington + Ryan Fairfax + Samuel Holland + Segev Finer + Shiz + sin + Solar Designer + Stefan Kristiansson + Stefan O'Rear + Szabolcs Nagy + Timo Teräs + Trutz Behn + Valentin Ochs + Will Dietz + William Haddon + William Pitcock + + Portions of this software are derived from third-party works licensed + under terms compatible with the above MIT license: + + The TRE regular expression implementation (src/regex/reg* and + src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed + under a 2-clause BSD license (license text in the source files). The + included version has been heavily modified by Rich Felker in 2012, in + the interests of size, simplicity, and namespace cleanliness. + + Much of the math library code (src/math/* and src/complex/*) is + Copyright © 1993,2004 Sun Microsystems or + Copyright © 2003-2011 David Schultz or + Copyright © 2003-2009 Steven G. Kargl or + Copyright © 2003-2009 Bruce D. Evans or + Copyright © 2008 Stephen L. Moshier or + Copyright © 2017-2018 Arm Limited + and labelled as such in comments in the individual source files. All + have been licensed under extremely permissive terms. + + The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008 + The Android Open Source Project and is licensed under a two-clause BSD + license. It was taken from Bionic libc, used on Android. + + The AArch64 memcpy and memset code (src/string/aarch64/*) are + Copyright © 1999-2019, Arm Limited. + + The implementation of DES for crypt (src/crypt/crypt_des.c) is + Copyright © 1994 David Burren. It is licensed under a BSD license. + + The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was + originally written by Solar Designer and placed into the public + domain. The code also comes with a fallback permissive license for use + in jurisdictions that may not recognize the public domain. + + The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011 + Valentin Ochs and is licensed under an MIT-style license. + + The x86_64 port was written by Nicholas J. Kain and is licensed under + the standard MIT terms. + + The mips and microblaze ports were originally written by Richard + Pennington for use in the ellcc project. The original code was adapted + by Rich Felker for build system and code conventions during upstream + integration. It is licensed under the standard MIT terms. + + The mips64 port was contributed by Imagination Technologies and is + licensed under the standard MIT terms. + + The powerpc port was also originally written by Richard Pennington, + and later supplemented and integrated by John Spencer. It is licensed + under the standard MIT terms. + + All other files which have no copyright comments are original works + produced specifically for use as part of this library, written either + by Rich Felker, the main author of the library, or by one or more + contibutors listed above. Details on authorship of individual files + can be found in the git version control history of the project. The + omission of copyright and license comments in each file is in the + interest of source tree size. + + In addition, permission is hereby granted for all public header files + (include/* and arch/*/bits/*) and crt files intended to be linked into + applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit + the copyright notice and permission notice otherwise required by the + license, and to use these files without any requirement of + attribution. These files include substantial contributions from: + + Bobby Bingham + John Spencer + Nicholas J. Kain + Rich Felker + Richard Pennington + Stefan Kristiansson + Szabolcs Nagy + + all of whom have explicitly granted such permission. + + This file previously contained text expressing a belief that most of + the files covered by the above exception were sufficiently trivial not + to be subject to copyright, resulting in confusion over whether it + negated the permissions granted in the license. In the spirit of + permissive licensing, and of not having licensing issues being an + obstacle to adoption, that text has been removed.Copyright (c) 2005-2023, NumPy 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 NumPy Developers nor the names of any + 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. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + Copyright (c) Donald Stufft and individual contributors. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 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.A. HISTORY OF THE SOFTWARE + ========================== + + Python was created in the early 1990s by Guido van Rossum at Stichting + Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands + as a successor of a language called ABC. Guido remains Python's + principal author, although it includes many contributions from others. + + In 1995, Guido continued his work on Python at the Corporation for + National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) + in Reston, Virginia where he released several versions of the + software. + + In May 2000, Guido and the Python core development team moved to + BeOpen.com to form the BeOpen PythonLabs team. In October of the same + year, the PythonLabs team moved to Digital Creations, which became + Zope Corporation. In 2001, the Python Software Foundation (PSF, see + https://www.python.org/psf/) was formed, a non-profit organization + created specifically to own Python-related Intellectual Property. + Zope Corporation was a sponsoring member of the PSF. + + All Python releases are Open Source (see https://opensource.org for + the Open Source Definition). Historically, most, but not all, Python + releases have also been GPL-compatible; the table below summarizes + the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + + Footnotes: + + (1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + + (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + + Thanks to the many outside volunteers who have worked under Guido's + direction to make these releases possible. + + + B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON + =============================================================== + + Python software and documentation are licensed under the + Python Software Foundation License Version 2. + + Starting with Python 3.8.6, examples, recipes, and other code in + the documentation are dual licensed under the PSF License Version 2 + and the Zero-Clause BSD license. + + Some software incorporated into Python is under different licenses. + The licenses are listed with code falling under that license. + + + PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 + -------------------------------------------- + + 1. This LICENSE AGREEMENT is between the Python Software Foundation + ("PSF"), and the Individual or Organization ("Licensee") accessing and + otherwise using this software ("Python") in source or binary form and + its associated documentation. + + 2. Subject to the terms and conditions of this License Agreement, PSF hereby + grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python alone or in any derivative version, + provided, however, that PSF's License Agreement and PSF's notice of copyright, + i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, + 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; + All Rights Reserved" are retained in Python alone or in any derivative version + prepared by Licensee. + + 3. In the event Licensee prepares a derivative work that is based on + or incorporates Python or any part thereof, and wants to make + the derivative work available to others as provided herein, then + Licensee hereby agrees to include in any such work a brief summary of + the changes made to Python. + + 4. PSF is making Python available to Licensee on an "AS IS" + basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR + IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND + DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS + FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT + INFRINGE ANY THIRD PARTY RIGHTS. + + 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS + A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, + OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + + 6. This License Agreement will automatically terminate upon a material + breach of its terms and conditions. + + 7. Nothing in this License Agreement shall be deemed to create any + relationship of agency, partnership, or joint venture between PSF and + Licensee. This License Agreement does not grant permission to use PSF + trademarks or trade name in a trademark sense to endorse or promote + products or services of Licensee, or any third party. + + 8. By copying, installing or otherwise using Python, Licensee + agrees to be bound by the terms and conditions of this License + Agreement. + + + BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 + ------------------------------------------- + + BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + + 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an + office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the + Individual or Organization ("Licensee") accessing and otherwise using + this software in source or binary form and its associated + documentation ("the Software"). + + 2. Subject to the terms and conditions of this BeOpen Python License + Agreement, BeOpen hereby grants Licensee a non-exclusive, + royalty-free, world-wide license to reproduce, analyze, test, perform + and/or display publicly, prepare derivative works, distribute, and + otherwise use the Software alone or in any derivative version, + provided, however, that the BeOpen Python License is retained in the + Software, alone or in any derivative version prepared by Licensee. + + 3. BeOpen is making the Software available to Licensee on an "AS IS" + basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR + IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND + DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS + FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT + INFRINGE ANY THIRD PARTY RIGHTS. + + 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE + SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS + AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY + DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + + 5. This License Agreement will automatically terminate upon a material + breach of its terms and conditions. + + 6. This License Agreement shall be governed by and interpreted in all + respects by the law of the State of California, excluding conflict of + law provisions. Nothing in this License Agreement shall be deemed to + create any relationship of agency, partnership, or joint venture + between BeOpen and Licensee. This License Agreement does not grant + permission to use BeOpen trademarks or trade names in a trademark + sense to endorse or promote products or services of Licensee, or any + third party. As an exception, the "BeOpen Python" logos available at + http://www.pythonlabs.com/logos.html may be used according to the + permissions granted on that web page. + + 7. By copying, installing or otherwise using the software, Licensee + agrees to be bound by the terms and conditions of this License + Agreement. + + + CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 + --------------------------------------- + + 1. This LICENSE AGREEMENT is between the Corporation for National + Research Initiatives, having an office at 1895 Preston White Drive, + Reston, VA 20191 ("CNRI"), and the Individual or Organization + ("Licensee") accessing and otherwise using Python 1.6.1 software in + source or binary form and its associated documentation. + + 2. Subject to the terms and conditions of this License Agreement, CNRI + hereby grants Licensee a nonexclusive, royalty-free, world-wide + license to reproduce, analyze, test, perform and/or display publicly, + prepare derivative works, distribute, and otherwise use Python 1.6.1 + alone or in any derivative version, provided, however, that CNRI's + License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) + 1995-2001 Corporation for National Research Initiatives; All Rights + Reserved" are retained in Python 1.6.1 alone or in any derivative + version prepared by Licensee. Alternately, in lieu of CNRI's License + Agreement, Licensee may substitute the following text (omitting the + quotes): "Python 1.6.1 is made available subject to the terms and + conditions in CNRI's License Agreement. This Agreement together with + Python 1.6.1 may be located on the internet using the following + unique, persistent identifier (known as a handle): 1895.22/1013. This + Agreement may also be obtained from a proxy server on the internet + using the following URL: http://hdl.handle.net/1895.22/1013". + + 3. In the event Licensee prepares a derivative work that is based on + or incorporates Python 1.6.1 or any part thereof, and wants to make + the derivative work available to others as provided herein, then + Licensee hereby agrees to include in any such work a brief summary of + the changes made to Python 1.6.1. + + 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" + basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR + IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND + DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS + FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT + INFRINGE ANY THIRD PARTY RIGHTS. + + 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON + 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS + A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, + OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + + 6. This License Agreement will automatically terminate upon a material + breach of its terms and conditions. + + 7. This License Agreement shall be governed by the federal + intellectual property law of the United States, including without + limitation the federal copyright law, and, to the extent such + U.S. federal law does not apply, by the law of the Commonwealth of + Virginia, excluding Virginia's conflict of law provisions. + Notwithstanding the foregoing, with regard to derivative works based + on Python 1.6.1 that incorporate non-separable material that was + previously distributed under the GNU General Public License (GPL), the + law of the Commonwealth of Virginia shall govern this License + Agreement only as to issues arising under or with respect to + Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this + License Agreement shall be deemed to create any relationship of + agency, partnership, or joint venture between CNRI and Licensee. This + License Agreement does not grant permission to use CNRI trademarks or + trade name in a trademark sense to endorse or promote products or + services of Licensee, or any third party. + + 8. By clicking on the "ACCEPT" button where indicated, or by copying, + installing or otherwise using Python 1.6.1, Licensee agrees to be + bound by the terms and conditions of this License Agreement. + + ACCEPT + + + CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 + -------------------------------------------------- + + Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, + The Netherlands. All rights reserved. + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation, and that the name of Stichting Mathematisch + Centrum or CWI not be used in advertising or publicity pertaining to + distribution of the software without specific, written prior + permission. + + STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE + FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION + ---------------------------------------------------------------------- + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + Copyright (c) 2014, Al Sweigart + 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 {organization} 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.Copyright (c) 2017 Anthony Sottile + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE.Copyright (c) 2015-2019 Jared Hobbs + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do + so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE.Developed by ESN, an Electronic Arts Inc. studio. + Copyright (c) 2014, Electronic Arts Inc. + 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 ESN, Electronic Arts Inc. 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 ELECTRONIC ARTS INC. 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. + + ---- + + Portions of code from MODP_ASCII - Ascii transformations (upper/lower, etc) + https://github.com/client9/stringencoders + + Copyright 2005, 2006, 2007 + Nick Galbreath -- nickg [at] modp [dot] com + 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 modp.com 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. + + This is the standard "new" BSD license: + http://www.opensource.org/licenses/bsd-license.php + + https://github.com/client9/stringencoders/blob/cfd5c1507325ae497ea9bacdacba12c0ffd79d30/COPYING + + ---- + + Numeric decoder derived from from TCL library + https://opensource.apple.com/source/tcl/tcl-14/tcl/license.terms + * Copyright (c) 1988-1993 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + + This software is copyrighted by the Regents of the University of + California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState + Corporation and other parties. The following terms apply to all files + associated with the software unless explicitly disclaimed in + individual files. + + The authors hereby grant permission to use, copy, modify, distribute, + and license this software and its documentation for any purpose, provided + that existing copyright notices are retained in all copies and that this + notice is included verbatim in any distributions. No written agreement, + license, or royalty fee is required for any of the authorized uses. + Modifications to this software may be copyrighted by their authors + and need not follow the licensing terms described here, provided that + the new terms are clearly indicated on the first page of each file where + they apply. + + IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY + FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY + DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE + IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE + NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR + MODIFICATIONS. + + GOVERNMENT USE: If you are acquiring this software on behalf of the + U.S. government, the Government shall have only "Restricted Rights" + in the software and related documentation as defined in the Federal + Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you + are acquiring the software on behalf of the Department of Defense, the + software shall be classified as "Commercial Computer Software" and the + Government shall have only "Restricted Rights" as defined in Clause + 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the + authors grant the U.S. Government and others acting in its behalf + permission to use and distribute the software in accordance with the + terms specified in this license.Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and + distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the copyright + owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other entities + that control, are controlled by, or are under common control with that entity. + For the purposes of this definition, "control" means (i) the power, direct or + indirect, to cause the direction or management of such entity, whether by + contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising + permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, including + but not limited to software source code, documentation source, and configuration + files. + + "Object" form shall mean any form resulting from mechanical transformation or + translation of a Source form, including but not limited to compiled object code, + generated documentation, and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or Object form, made + available under the License, as indicated by a copyright notice that is included + in or attached to the work (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, that + is based on (or derived from) the Work and for which the editorial revisions, + annotations, elaborations, or other modifications represent, as a whole, an + original work of authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely link (or bind by + name) to the interfaces of, the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original version + of the Work and any modifications or additions to that Work or Derivative Works + thereof, that is intentionally submitted to Licensor for inclusion in the Work + by the copyright owner or by an individual or Legal Entity authorized to submit + on behalf of the copyright owner. For the purposes of this definition, + "submitted" means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, and + issue tracking systems that are managed by, or on behalf of, the Licensor for + the purpose of discussing and improving the Work, but excluding communication + that is conspicuously marked or otherwise designated in writing by the copyright + owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on behalf + of whom a Contribution has been received by Licensor and subsequently + incorporated within the Work. + + 2. Grant of Copyright License. + + Subject to the terms and conditions of this License, each Contributor hereby + grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the Work and such + Derivative Works in Source or Object form. + + 3. Grant of Patent License. + + Subject to the terms and conditions of this License, each Contributor hereby + grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, + irrevocable (except as stated in this section) patent license to make, have + made, use, offer to sell, sell, import, and otherwise transfer the Work, where + such license applies only to those patent claims licensable by such Contributor + that are necessarily infringed by their Contribution(s) alone or by combination + of their Contribution(s) with the Work to which such Contribution(s) was + submitted. If You institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work or a + Contribution incorporated within the Work constitutes direct or contributory + patent infringement, then any patent licenses granted to You under this License + for that Work shall terminate as of the date such litigation is filed. + + 4. Redistribution. + + You may reproduce and distribute copies of the Work or Derivative Works thereof + in any medium, with or without modifications, and in Source or Object form, + provided that You meet the following conditions: + + You must give any other recipients of the Work or Derivative Works a copy of + this License; and + You must cause any modified files to carry prominent notices stating that You + changed the files; and + You must retain, in the Source form of any Derivative Works that You distribute, + all copyright, patent, trademark, and attribution notices from the Source form + of the Work, excluding those notices that do not pertain to any part of the + Derivative Works; and + If the Work includes a "NOTICE" text file as part of its distribution, then any + Derivative Works that You distribute must include a readable copy of the + attribution notices contained within such NOTICE file, excluding those notices + that do not pertain to any part of the Derivative Works, in at least one of the + following places: within a NOTICE text file distributed as part of the + Derivative Works; within the Source form or documentation, if provided along + with the Derivative Works; or, within a display generated by the Derivative + Works, if and wherever such third-party notices normally appear. The contents of + the NOTICE file are for informational purposes only and do not modify the + License. You may add Your own attribution notices within Derivative Works that + You distribute, alongside or as an addendum to the NOTICE text from the Work, + provided that such additional attribution notices cannot be construed as + modifying the License. + You may add Your own copyright statement to Your modifications and may provide + additional or different license terms and conditions for use, reproduction, or + distribution of Your modifications, or for any such Derivative Works as a whole, + provided Your use, reproduction, and distribution of the Work otherwise complies + with the conditions stated in this License. + + 5. Submission of Contributions. + + Unless You explicitly state otherwise, any Contribution intentionally submitted + for inclusion in the Work by You to the Licensor shall be under the terms and + conditions of this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify the terms of + any separate license agreement you may have executed with Licensor regarding + such Contributions. + + 6. Trademarks. + + This License does not grant permission to use the trade names, trademarks, + service marks, or product names of the Licensor, except as required for + reasonable and customary use in describing the origin of the Work and + reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. + + Unless required by applicable law or agreed to in writing, Licensor provides the + Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, + including, without limitation, any warranties or conditions of TITLE, + NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are + solely responsible for determining the appropriateness of using or + redistributing the Work and assume any risks associated with Your exercise of + permissions under this License. + + 8. Limitation of Liability. + + In no event and under no legal theory, whether in tort (including negligence), + contract, or otherwise, unless required by applicable law (such as deliberate + and grossly negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, incidental, + or consequential damages of any character arising as a result of this License or + out of the use or inability to use the Work (including but not limited to + damages for loss of goodwill, work stoppage, computer failure or malfunction, or + any and all other commercial damages or losses), even if such Contributor has + been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. + + While redistributing the Work or Derivative Works thereof, You may choose to + offer, and charge a fee for, acceptance of support, warranty, indemnity, or + other liability obligations and/or rights consistent with this License. However, + in accepting such obligations, You may act only on Your own behalf and on Your + sole responsibility, not on behalf of any other Contributor, and only if You + agree to indemnify, defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason of your + accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work + + To apply the Apache License to your work, attach the following boilerplate + notice, with the fields enclosed by brackets "[]" replaced with your own + identifying information. (Don't include the brackets!) The text should be + enclosed in the appropriate comment syntax for the file format. We also + recommend that a file or class name and description of purpose be included on + the same "printed page" as the copyright notice for easier identification within + third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed 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. +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering +Project-URL: homepage, https://pandas.pydata.org +Project-URL: documentation, https://pandas.pydata.org/docs/ +Project-URL: repository, https://github.com/pandas-dev/pandas +Requires-Python: >=3.9 +Requires-Dist: numpy>=1.22.4; python_version < "3.11" +Requires-Dist: numpy>=1.23.2; python_version == "3.11" +Requires-Dist: numpy>=1.26.0; python_version >= "3.12" +Requires-Dist: python-dateutil>=2.8.2 +Requires-Dist: pytz>=2020.1 +Requires-Dist: tzdata>=2022.7 +Provides-Extra: test +Requires-Dist: hypothesis>=6.46.1; extra == "test" +Requires-Dist: pytest>=7.3.2; extra == "test" +Requires-Dist: pytest-xdist>=2.2.0; extra == "test" +Provides-Extra: pyarrow +Requires-Dist: pyarrow>=10.0.1; extra == "pyarrow" +Provides-Extra: performance +Requires-Dist: bottleneck>=1.3.6; extra == "performance" +Requires-Dist: numba>=0.56.4; extra == "performance" +Requires-Dist: numexpr>=2.8.4; extra == "performance" +Provides-Extra: computation +Requires-Dist: scipy>=1.10.0; extra == "computation" +Requires-Dist: xarray>=2022.12.0; extra == "computation" +Provides-Extra: fss +Requires-Dist: fsspec>=2022.11.0; extra == "fss" +Provides-Extra: aws +Requires-Dist: s3fs>=2022.11.0; extra == "aws" +Provides-Extra: gcp +Requires-Dist: gcsfs>=2022.11.0; extra == "gcp" +Requires-Dist: pandas-gbq>=0.19.0; extra == "gcp" +Provides-Extra: excel +Requires-Dist: odfpy>=1.4.1; extra == "excel" +Requires-Dist: openpyxl>=3.1.0; extra == "excel" +Requires-Dist: python-calamine>=0.1.7; extra == "excel" +Requires-Dist: pyxlsb>=1.0.10; extra == "excel" +Requires-Dist: xlrd>=2.0.1; extra == "excel" +Requires-Dist: xlsxwriter>=3.0.5; extra == "excel" +Provides-Extra: parquet +Requires-Dist: pyarrow>=10.0.1; extra == "parquet" +Provides-Extra: feather +Requires-Dist: pyarrow>=10.0.1; extra == "feather" +Provides-Extra: hdf5 +Requires-Dist: tables>=3.8.0; extra == "hdf5" +Provides-Extra: spss +Requires-Dist: pyreadstat>=1.2.0; extra == "spss" +Provides-Extra: postgresql +Requires-Dist: SQLAlchemy>=2.0.0; extra == "postgresql" +Requires-Dist: psycopg2>=2.9.6; extra == "postgresql" +Requires-Dist: adbc-driver-postgresql>=0.8.0; extra == "postgresql" +Provides-Extra: mysql +Requires-Dist: SQLAlchemy>=2.0.0; extra == "mysql" +Requires-Dist: pymysql>=1.0.2; extra == "mysql" +Provides-Extra: sql-other +Requires-Dist: SQLAlchemy>=2.0.0; extra == "sql-other" +Requires-Dist: adbc-driver-postgresql>=0.8.0; extra == "sql-other" +Requires-Dist: adbc-driver-sqlite>=0.8.0; extra == "sql-other" +Provides-Extra: html +Requires-Dist: beautifulsoup4>=4.11.2; extra == "html" +Requires-Dist: html5lib>=1.1; extra == "html" +Requires-Dist: lxml>=4.9.2; extra == "html" +Provides-Extra: xml +Requires-Dist: lxml>=4.9.2; extra == "xml" +Provides-Extra: plot +Requires-Dist: matplotlib>=3.6.3; extra == "plot" +Provides-Extra: output-formatting +Requires-Dist: jinja2>=3.1.2; extra == "output-formatting" +Requires-Dist: tabulate>=0.9.0; extra == "output-formatting" +Provides-Extra: clipboard +Requires-Dist: PyQt5>=5.15.9; extra == "clipboard" +Requires-Dist: qtpy>=2.3.0; extra == "clipboard" +Provides-Extra: compression +Requires-Dist: zstandard>=0.19.0; extra == "compression" +Provides-Extra: consortium-standard +Requires-Dist: dataframe-api-compat>=0.1.7; extra == "consortium-standard" +Provides-Extra: all +Requires-Dist: adbc-driver-postgresql>=0.8.0; extra == "all" +Requires-Dist: adbc-driver-sqlite>=0.8.0; extra == "all" +Requires-Dist: beautifulsoup4>=4.11.2; extra == "all" +Requires-Dist: bottleneck>=1.3.6; extra == "all" +Requires-Dist: dataframe-api-compat>=0.1.7; extra == "all" +Requires-Dist: fastparquet>=2022.12.0; extra == "all" +Requires-Dist: fsspec>=2022.11.0; extra == "all" +Requires-Dist: gcsfs>=2022.11.0; extra == "all" +Requires-Dist: html5lib>=1.1; extra == "all" +Requires-Dist: hypothesis>=6.46.1; extra == "all" +Requires-Dist: jinja2>=3.1.2; extra == "all" +Requires-Dist: lxml>=4.9.2; extra == "all" +Requires-Dist: matplotlib>=3.6.3; extra == "all" +Requires-Dist: numba>=0.56.4; extra == "all" +Requires-Dist: numexpr>=2.8.4; extra == "all" +Requires-Dist: odfpy>=1.4.1; extra == "all" +Requires-Dist: openpyxl>=3.1.0; extra == "all" +Requires-Dist: pandas-gbq>=0.19.0; extra == "all" +Requires-Dist: psycopg2>=2.9.6; extra == "all" +Requires-Dist: pyarrow>=10.0.1; extra == "all" +Requires-Dist: pymysql>=1.0.2; extra == "all" +Requires-Dist: PyQt5>=5.15.9; extra == "all" +Requires-Dist: pyreadstat>=1.2.0; extra == "all" +Requires-Dist: pytest>=7.3.2; extra == "all" +Requires-Dist: pytest-xdist>=2.2.0; extra == "all" +Requires-Dist: python-calamine>=0.1.7; extra == "all" +Requires-Dist: pyxlsb>=1.0.10; extra == "all" +Requires-Dist: qtpy>=2.3.0; extra == "all" +Requires-Dist: scipy>=1.10.0; extra == "all" +Requires-Dist: s3fs>=2022.11.0; extra == "all" +Requires-Dist: SQLAlchemy>=2.0.0; extra == "all" +Requires-Dist: tables>=3.8.0; extra == "all" +Requires-Dist: tabulate>=0.9.0; extra == "all" +Requires-Dist: xarray>=2022.12.0; extra == "all" +Requires-Dist: xlrd>=2.0.1; extra == "all" +Requires-Dist: xlsxwriter>=3.0.5; extra == "all" +Requires-Dist: zstandard>=0.19.0; extra == "all" +Description-Content-Type: text/markdown + +
+
+
+ +----------------- + +# pandas: powerful Python data analysis toolkit + +| | | +| --- | --- | +| Testing | [![CI - Test](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml/badge.svg)](https://github.com/pandas-dev/pandas/actions/workflows/unit-tests.yml) [![Coverage](https://codecov.io/github/pandas-dev/pandas/coverage.svg?branch=main)](https://codecov.io/gh/pandas-dev/pandas) | +| Package | [![PyPI Latest Release](https://img.shields.io/pypi/v/pandas.svg)](https://pypi.org/project/pandas/) [![PyPI Downloads](https://img.shields.io/pypi/dm/pandas.svg?label=PyPI%20downloads)](https://pypi.org/project/pandas/) [![Conda Latest Release](https://anaconda.org/conda-forge/pandas/badges/version.svg)](https://anaconda.org/conda-forge/pandas) [![Conda Downloads](https://img.shields.io/conda/dn/conda-forge/pandas.svg?label=Conda%20downloads)](https://anaconda.org/conda-forge/pandas) | +| Meta | [![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3509134.svg)](https://doi.org/10.5281/zenodo.3509134) [![License - BSD 3-Clause](https://img.shields.io/pypi/l/pandas.svg)](https://github.com/pandas-dev/pandas/blob/main/LICENSE) [![Slack](https://img.shields.io/badge/join_Slack-information-brightgreen.svg?logo=slack)](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) | + + +## What is it? + +**pandas** is a Python package that provides fast, flexible, and expressive data +structures designed to make working with "relational" or "labeled" data both +easy and intuitive. It aims to be the fundamental high-level building block for +doing practical, **real world** data analysis in Python. Additionally, it has +the broader goal of becoming **the most powerful and flexible open source data +analysis / manipulation tool available in any language**. It is already well on +its way towards this goal. + +## Table of Contents + +- [Main Features](#main-features) +- [Where to get it](#where-to-get-it) +- [Dependencies](#dependencies) +- [Installation from sources](#installation-from-sources) +- [License](#license) +- [Documentation](#documentation) +- [Background](#background) +- [Getting Help](#getting-help) +- [Discussion and Development](#discussion-and-development) +- [Contributing to pandas](#contributing-to-pandas) + +## Main Features +Here are just a few of the things that pandas does well: + + - Easy handling of [**missing data**][missing-data] (represented as + `NaN`, `NA`, or `NaT`) in floating point as well as non-floating point data + - Size mutability: columns can be [**inserted and + deleted**][insertion-deletion] from DataFrame and higher dimensional + objects + - Automatic and explicit [**data alignment**][alignment]: objects can + be explicitly aligned to a set of labels, or the user can simply + ignore the labels and let `Series`, `DataFrame`, etc. automatically + align the data for you in computations + - Powerful, flexible [**group by**][groupby] functionality to perform + split-apply-combine operations on data sets, for both aggregating + and transforming data + - Make it [**easy to convert**][conversion] ragged, + differently-indexed data in other Python and NumPy data structures + into DataFrame objects + - Intelligent label-based [**slicing**][slicing], [**fancy + indexing**][fancy-indexing], and [**subsetting**][subsetting] of + large data sets + - Intuitive [**merging**][merging] and [**joining**][joining] data + sets + - Flexible [**reshaping**][reshape] and [**pivoting**][pivot-table] of + data sets + - [**Hierarchical**][mi] labeling of axes (possible to have multiple + labels per tick) + - Robust IO tools for loading data from [**flat files**][flat-files] + (CSV and delimited), [**Excel files**][excel], [**databases**][db], + and saving/loading data from the ultrafast [**HDF5 format**][hdfstore] + - [**Time series**][timeseries]-specific functionality: date range + generation and frequency conversion, moving window statistics, + date shifting and lagging + + + [missing-data]: https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html + [insertion-deletion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#column-selection-addition-deletion + [alignment]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html?highlight=alignment#intro-to-data-structures + [groupby]: https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#group-by-split-apply-combine + [conversion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#dataframe + [slicing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#slicing-ranges + [fancy-indexing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced + [subsetting]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing + [merging]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging + [joining]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#joining-on-index + [reshape]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html + [pivot-table]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html + [mi]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#hierarchical-indexing-multiindex + [flat-files]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files + [excel]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#excel-files + [db]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#sql-queries + [hdfstore]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#hdf5-pytables + [timeseries]: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-series-date-functionality + +## Where to get it +The source code is currently hosted on GitHub at: +https://github.com/pandas-dev/pandas + +Binary installers for the latest released version are available at the [Python +Package Index (PyPI)](https://pypi.org/project/pandas) and on [Conda](https://docs.conda.io/en/latest/). + +```sh +# conda +conda install -c conda-forge pandas +``` + +```sh +# or PyPI +pip install pandas +``` + +The list of changes to pandas between each release can be found +[here](https://pandas.pydata.org/pandas-docs/stable/whatsnew/index.html). For full +details, see the commit logs at https://github.com/pandas-dev/pandas. + +## Dependencies +- [NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays](https://www.numpy.org) +- [python-dateutil - Provides powerful extensions to the standard datetime module](https://dateutil.readthedocs.io/en/stable/index.html) +- [pytz - Brings the Olson tz database into Python which allows accurate and cross platform timezone calculations](https://github.com/stub42/pytz) + +See the [full installation instructions](https://pandas.pydata.org/pandas-docs/stable/install.html#dependencies) for minimum supported versions of required, recommended and optional dependencies. + +## Installation from sources +To install pandas from source you need [Cython](https://cython.org/) in addition to the normal +dependencies above. Cython can be installed from PyPI: + +```sh +pip install cython +``` + +In the `pandas` directory (same one where you found this file after +cloning the git repo), execute: + +```sh +pip install . +``` + +or for installing in [development mode](https://pip.pypa.io/en/latest/cli/pip_install/#install-editable): + + +```sh +python -m pip install -ve . --no-build-isolation --config-settings=editable-verbose=true +``` + +See the full instructions for [installing from source](https://pandas.pydata.org/docs/dev/development/contributing_environment.html). + +## License +[BSD 3](LICENSE) + +## Documentation +The official documentation is hosted on [PyData.org](https://pandas.pydata.org/pandas-docs/stable/). + +## Background +Work on ``pandas`` started at [AQR](https://www.aqr.com/) (a quantitative hedge fund) in 2008 and +has been under active development since then. + +## Getting Help + +For usage questions, the best place to go to is [StackOverflow](https://stackoverflow.com/questions/tagged/pandas). +Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata). + +## Discussion and Development +Most development discussions take place on GitHub in this repo, via the [GitHub issue tracker](https://github.com/pandas-dev/pandas/issues). + +Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Slack channel](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack) is available for quick development related questions. + +There are also frequent [community meetings](https://pandas.pydata.org/docs/dev/development/community.html#community-meeting) for project maintainers open to the community as well as monthly [new contributor meetings](https://pandas.pydata.org/docs/dev/development/community.html#new-contributor-meeting) to help support new contributors. + +Additional information on the communication channels can be found on the [contributor community](https://pandas.pydata.org/docs/development/community.html) page. + +## Contributing to pandas + +[![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/pandas) + +All contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome. + +A detailed overview on how to contribute can be found in the **[contributing guide](https://pandas.pydata.org/docs/dev/development/contributing.html)**. + +If you are simply looking to start working with the pandas codebase, navigate to the [GitHub "issues" tab](https://github.com/pandas-dev/pandas/issues) and start looking through interesting issues. There are a number of issues listed under [Docs](https://github.com/pandas-dev/pandas/issues?labels=Docs&sort=updated&state=open) and [good first issue](https://github.com/pandas-dev/pandas/issues?labels=good+first+issue&sort=updated&state=open) where you could start out. + +You can also triage issues which may include reproducing bug reports, or asking for vital information such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to pandas on CodeTriage](https://www.codetriage.com/pandas-dev/pandas). + +Or maybe through using pandas you have an idea of your own or are looking for something in the documentation and thinking ‘this can be improved’...you can do something about it! + +Feel free to ask questions on the [mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata) or on [Slack](https://pandas.pydata.org/docs/dev/development/community.html?highlight=slack#community-slack). + +As contributors and maintainers to this project, you are expected to abide by pandas' code of conduct. More information can be found at: [Contributor Code of Conduct](https://github.com/pandas-dev/.github/blob/master/CODE_OF_CONDUCT.md) + +
+ +[Go to Top](#table-of-contents) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..bcee45fa5a08f9e39326f7fd688e407bc05eb6b5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/RECORD @@ -0,0 +1,2929 @@ +pandas-2.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pandas-2.3.3.dist-info/LICENSE,sha256=HeougO0cvQIz-EzuRIaylonxM7q6zPTSleUcQwUfMhY,62399 +pandas-2.3.3.dist-info/METADATA,sha256=QO6VPcfKFVhAtjmhiB_4RXgHUYf84Kwg7tpVp_oNmpA,91215 +pandas-2.3.3.dist-info/RECORD,, +pandas-2.3.3.dist-info/WHEEL,sha256=GndFmsGQkhesJMB09xd5xy1JFawKJlDZt6AMMgqJ-Pw,122 +pandas-2.3.3.dist-info/entry_points.txt,sha256=OVLKNEPs-Q7IWypWBL6fxv56_zt4sRnEI7zawo6y_0w,69 +pandas/__init__.py,sha256=EIvoyjrhoqXHZe5vh-iGfYfC-1qJEH5sLTpqzJZhK3s,8658 +pandas/__pycache__/__init__.cpython-312.pyc,, +pandas/__pycache__/_typing.cpython-312.pyc,, +pandas/__pycache__/_version.cpython-312.pyc,, +pandas/__pycache__/_version_meson.cpython-312.pyc,, +pandas/__pycache__/conftest.cpython-312.pyc,, +pandas/__pycache__/testing.cpython-312.pyc,, +pandas/_config/__init__.py,sha256=PIOJaU3IvUe9iL66ZztlkJ-R70v2YSVuFIeM5viVSx0,1429 +pandas/_config/__pycache__/__init__.cpython-312.pyc,, +pandas/_config/__pycache__/config.cpython-312.pyc,, +pandas/_config/__pycache__/dates.cpython-312.pyc,, +pandas/_config/__pycache__/display.cpython-312.pyc,, +pandas/_config/__pycache__/localization.cpython-312.pyc,, +pandas/_config/config.py,sha256=YwadTnEN93OFAxyzW289d_v4dhWLzxpMHGZrl3xt_XY,25454 +pandas/_config/dates.py,sha256=HgZFPT02hugJO7uhSTjwebcKOd34JkcYY2gSPtOydmg,668 +pandas/_config/display.py,sha256=xv_TetWUhFlVpog23QzyhMYsScops_OOsWIAGnmKdJ8,1804 +pandas/_config/localization.py,sha256=79Q2KU1aHxX6Q8Wn8EGOEUAyv3XIjQ4YaTaEzeFbtwM,5190 +pandas/_libs/__init__.py,sha256=6i-pdZncVhiCRL_ChKyrTLNhn14aDbsYw243-PfAnJQ,673 +pandas/_libs/__pycache__/__init__.cpython-312.pyc,, +pandas/_libs/algos.cpython-312-darwin.so,sha256=v4ChG6Rr9_b3JjDH2Y2x0gGx6JugxR09X5mfSxfzSJU,1614072 +pandas/_libs/algos.pyi,sha256=KEF48zZLn3TSUCmd8thdo4DzYvJ5zaCK60hYX6nzyZI,15182 +pandas/_libs/arrays.cpython-312-darwin.so,sha256=CwPxRekD-0YEbDCe1tbnwP6f_KwAVit-j0eyJP1-JTY,136496 +pandas/_libs/arrays.pyi,sha256=PfpeOMplxyN2vbfFCdkkSKGCg21SFRydvqBdeJhBVqQ,1105 +pandas/_libs/byteswap.cpython-312-darwin.so,sha256=f94aWYrpJ5t9ZNwnotH09w1AlGCEnKt44_sD8lYDRG4,76784 +pandas/_libs/byteswap.pyi,sha256=SxL2I1rKqe73WZgkO511PWJx20P160V4hrws1TG0JTk,423 +pandas/_libs/groupby.cpython-312-darwin.so,sha256=8oUJYgiqgfszP-TI-lxM8h0_p37x09JQwY2yxeWp8Co,2043440 +pandas/_libs/groupby.pyi,sha256=xQNDpqTPCUy2FqxZytOpaubrUgzQ9axyQXrg37UEnyk,7278 +pandas/_libs/hashing.cpython-312-darwin.so,sha256=QP6jpqKOwCYYDlX_7hoReMlLSzz1Pr90Yaf4UzDcngI,193088 +pandas/_libs/hashing.pyi,sha256=cdNwppEilaMnVN77ABt3TBadjUawMtMFgSQb1PCqwQk,181 +pandas/_libs/hashtable.cpython-312-darwin.so,sha256=eivvaLd66qpZIhCviTXXwbLuviABsCmLTGCz7bg_0IE,1743456 +pandas/_libs/hashtable.pyi,sha256=jBv8QuQii-ikWklP76_DPCYfms88fpj6pPOaCOK6s0M,7424 +pandas/_libs/index.cpython-312-darwin.so,sha256=GdG2hbeJYodaZm4Rj-lG_jxoI7IOr7sxiyoR_mGG_ds,772280 +pandas/_libs/index.pyi,sha256=8xJKzarI9fTYhM7kvSfw-G6V12YGnoJ7ToianNQvZ0M,3798 +pandas/_libs/indexing.cpython-312-darwin.so,sha256=fBkAu61iHKgK6yjG-MEv4hGMs0h7BO_YGkKj9VSERoM,97824 +pandas/_libs/indexing.pyi,sha256=hlJwakbofPRdt1Lm31bfQ3CvHW-nMxm0nrInSWAey58,427 +pandas/_libs/internals.cpython-312-darwin.so,sha256=AzbN01sHNHH8vNdOA9cGLnNhvb6TWqcOt3wG8zjNPAk,342768 +pandas/_libs/internals.pyi,sha256=1zfOoULlHvpbbRHvPlcrV_kbY7WI3qEXYExbENEDdtE,2761 +pandas/_libs/interval.cpython-312-darwin.so,sha256=PLVMPhLT7CSKcVSVctVJZ7-Ju7XdfWqRgxhrlL-C0O8,1064288 +pandas/_libs/interval.pyi,sha256=cotxOfoqp7DX7XgIeKrGd31mfAeNerW1WD-yBrLfTlE,5378 +pandas/_libs/join.cpython-312-darwin.so,sha256=MFI0Gp7dGc1wHHkuTcMj42grELH0j5V5rqlgft5gSE4,1017544 +pandas/_libs/join.pyi,sha256=O61ZOIYi-I3gZJjDpLYIWWEe3iG0pogEQIB0ZxJ_E3Y,2780 +pandas/_libs/json.cpython-312-darwin.so,sha256=NwFyVyACiipIcwQ3A61GlzXqS4I-KQBXuePHYFVTcjI,93608 +pandas/_libs/json.pyi,sha256=kbqlmh7HTk4cc2hIDWdXZSFqOfh0cqGpBwcys3m32XM,496 +pandas/_libs/lib.cpython-312-darwin.so,sha256=g3MhPB1kP737o2DHM9SFzCaZMI0T_jeincjhgc8SQ2Q,699384 +pandas/_libs/lib.pyi,sha256=fU6YG6MGFBajevj1_KYnzlyzMlhRYCa-bICpoGnFcDI,7209 +pandas/_libs/missing.cpython-312-darwin.so,sha256=yaiJFnroRLGRVCfEwF-w1BB9r8H1D87FKQTIEqNdk0k,193488 +pandas/_libs/missing.pyi,sha256=iIftmSeHBcfgz7d9JWW_FQcyyAkuBzRiSnZw690OhDw,524 +pandas/_libs/ops.cpython-312-darwin.so,sha256=UwyHGfdAKXzPuwqtzF8HXWJBwpSb8lPme0DiUh2-qWg,228088 +pandas/_libs/ops.pyi,sha256=99NSmMUkneVNWOojl8Dsb8GmbUa5y_uhKUtfIgwgwek,1318 +pandas/_libs/ops_dispatch.cpython-312-darwin.so,sha256=-8ITLXuhbMswOFZH_07Jh_hFurqjhoswHtzX9N7gJ1c,79968 +pandas/_libs/ops_dispatch.pyi,sha256=Yxq3SUJ-qoMZ8ErL7wfHfCsTTcETOuu0FuoCOyhmGl0,124 +pandas/_libs/pandas_datetime.cpython-312-darwin.so,sha256=bRp0AsM8XaCkksJwqmGH37hEekBHj4WGxeTDvl6nzZo,70184 +pandas/_libs/pandas_parser.cpython-312-darwin.so,sha256=Z7a2mMauffxWj7AHBp4clymTgtsmJFFw3Y4oxwRfvpo,70080 +pandas/_libs/parsers.cpython-312-darwin.so,sha256=Y_Cr46n1hxlh_u1HctV772iLiFhdSFSHRONLNoOLIQ4,449504 +pandas/_libs/parsers.pyi,sha256=raoGhPLoRKLQAthm9JQT5rTjLR1PGFDS179aqtQdgnY,2378 +pandas/_libs/properties.cpython-312-darwin.so,sha256=MvEkBUFgXVZC5T7U1JL35Zn_95o85RH00hZB1XoI9pA,99824 +pandas/_libs/properties.pyi,sha256=HF93vy5OSNtQKz5NL_zwTnOj6tzBtW9Cog-5Zk2bnAA,717 +pandas/_libs/reshape.cpython-312-darwin.so,sha256=L9of9RYZ40coPyafW-OyUQXPuvriZLifFzQcUopFA14,264160 +pandas/_libs/reshape.pyi,sha256=xaU-NNnRhXVT9AVrksVXrbKfAC7Ny9p-Vwp6srRoGns,419 +pandas/_libs/sas.cpython-312-darwin.so,sha256=BTqcq6YKsZimfpyRPxNq-FLUhu50AODzRB4OdRYSgHY,229480 +pandas/_libs/sas.pyi,sha256=qkrJiuBd7GQbw3DQyhH9M6cMfNSkovArOXRdhJ8PFDA,224 +pandas/_libs/sparse.cpython-312-darwin.so,sha256=79XarYa3DSH0I54LLkuv4kMVYASlqnHW8Rc71rG_d-c,703136 +pandas/_libs/sparse.pyi,sha256=Yyi7QHpAt7K6l2iEhxgufRqbvSRfYpBHeC_hJaSK8Ho,1485 +pandas/_libs/testing.cpython-312-darwin.so,sha256=4NwUD0kFW4PNGdPIVnTCrdd7oH-Are8xxy6ouCiJVLw,149872 +pandas/_libs/testing.pyi,sha256=_fpEWiBmlWGR_3QUj1RU42WCTtW2Ug-EXHpM-kP6vB0,243 +pandas/_libs/tslib.cpython-312-darwin.so,sha256=dCMvAZUodI4vHsIQLvJiNHFqaMxEJ2FfTKMK5YAwam0,282712 +pandas/_libs/tslib.pyi,sha256=aWJDfzlbmlF6sAst1BTMKMcWt3me50-sqCS5YwWt0HI,969 +pandas/_libs/tslibs/__init__.py,sha256=dowITNV3Gxq8wB3XdqiyRCtEDn83_GkLcGJiQnzM1mA,2125 +pandas/_libs/tslibs/__pycache__/__init__.cpython-312.pyc,, +pandas/_libs/tslibs/base.cpython-312-darwin.so,sha256=HYWimwBm8lKXN_OURs23fs2uhoK3EGAEgDY7N5KYYZQ,96520 +pandas/_libs/tslibs/ccalendar.cpython-312-darwin.so,sha256=bNlLoOy0ohCd9k4m9mu_kAzklf_JR2MT0gFlZ4o8ZXU,98416 +pandas/_libs/tslibs/ccalendar.pyi,sha256=dizWWmYtxWa5Lc4Hv69iRaJoazRhegJaDGWYgWtJu-U,502 +pandas/_libs/tslibs/conversion.cpython-312-darwin.so,sha256=6Dgp6yd9If-d2pRn956n5WY_52YMvqK0el-Pxcl5Ng8,265744 +pandas/_libs/tslibs/conversion.pyi,sha256=sHO9CBRrDh0wovkr736kI5G6gaW1WY9tSOOAkBi63MA,300 +pandas/_libs/tslibs/dtypes.cpython-312-darwin.so,sha256=q_Tw2Tipov9l67_ivlbiM-uy1XsQhWjttu1gK5L6Ias,199568 +pandas/_libs/tslibs/dtypes.pyi,sha256=ZNUPcAyhkkh7kIGLDIDTfUmwefbtdxxvn668YN-AAeE,1988 +pandas/_libs/tslibs/fields.cpython-312-darwin.so,sha256=6lCFYgXOfRN_iD_346iZXE1AFm9ovYWxZFaiLQ3lPH8,284400 +pandas/_libs/tslibs/fields.pyi,sha256=LOke0XZ9XJnzX2MC9nL3u-JpbmddBfpy0UQ_d-_NvN8,1860 +pandas/_libs/tslibs/nattype.cpython-312-darwin.so,sha256=tD43yucqwiMjg_CnbCciM7FMyvkbQP1H0aU1e-c8kaU,230704 +pandas/_libs/tslibs/nattype.pyi,sha256=R3qw7RgZFLG7IgKTssmJdjm-lP3V18GEz810nzVHsTs,4116 +pandas/_libs/tslibs/np_datetime.cpython-312-darwin.so,sha256=Dgr9b2rJr_lisz323SUTNsinuFKdLIvFkOOva4x7QYc,153664 +pandas/_libs/tslibs/np_datetime.pyi,sha256=Y6l1KVdyKTMiYfzOjXNwV946GjoFAHaCEEhLDsHRCxI,831 +pandas/_libs/tslibs/offsets.cpython-312-darwin.so,sha256=BrKNsAjL7M2uMkuWtgxXDzngYxZNRBZEACMj_3gwk_Y,905152 +pandas/_libs/tslibs/offsets.pyi,sha256=QkYq2CgQ4aZ-92e_8wSpuxaACBIKjk2eI4-M-6wSeZU,8345 +pandas/_libs/tslibs/parsing.cpython-312-darwin.so,sha256=AqXBzIzH1f4_Ft9T7oX6_zoNQQjtpnbTxanFz5h_rck,360352 +pandas/_libs/tslibs/parsing.pyi,sha256=cbS8tHb95ygwDU-9gNaFs83FpbVj8aoQfw7gwJGEE6o,914 +pandas/_libs/tslibs/period.cpython-312-darwin.so,sha256=kdyCRvx_DyDGgxVX4o2TTQ3bCAjXNV4jYrzE6LuAj1A,431984 +pandas/_libs/tslibs/period.pyi,sha256=Bf0lYd6dh9O61Gq_TReVI4NcRf-5aINkdYJNDaq5az8,3908 +pandas/_libs/tslibs/strptime.cpython-312-darwin.so,sha256=Vv8RuNR7Z6TMo0bVM-cAYCaY6FchDeCwcZs4Cfn-tUo,320112 +pandas/_libs/tslibs/strptime.pyi,sha256=dizASoJenvjCydaWDo72_FQmiNOjLmnCZbUZgCm8EnI,349 +pandas/_libs/tslibs/timedeltas.cpython-312-darwin.so,sha256=aiR1DRP-W8wiVYHOH0Ynq29Ba6zx6zvO2eRxSRfiJNg,488816 +pandas/_libs/tslibs/timedeltas.pyi,sha256=6MW61MbVDqOH4JUQoR32z8qYUWRfPECV3fcQSrOkI_M,5009 +pandas/_libs/tslibs/timestamps.cpython-312-darwin.so,sha256=0SqgmgC6dYxMcglf_joO9SEAqGuP3wbIiVuUwfQw4HU,542080 +pandas/_libs/tslibs/timestamps.pyi,sha256=zCu9cAbFf_IVDb1sf5j_Ww5LYSFzGVwMhpZZUP370kw,7831 +pandas/_libs/tslibs/timezones.cpython-312-darwin.so,sha256=KqJZWFV6_pc7Q40HCIgnO5KJ2DRpKqXSrD8tZWOmTqQ,247344 +pandas/_libs/tslibs/timezones.pyi,sha256=MZ9kC5E1J3XlVqyBwFuVd7NsqL8STztzT8W8NK-_2r0,600 +pandas/_libs/tslibs/tzconversion.cpython-312-darwin.so,sha256=L0et8VaU6hEnDjBARvVmxUKTWzHuiZRJon1dY6aes_I,265360 +pandas/_libs/tslibs/tzconversion.pyi,sha256=MW4HtIKZpf7ZcOUQ4U6FL24BiJpASXI-mN0DOADtl10,560 +pandas/_libs/tslibs/vectorized.cpython-312-darwin.so,sha256=dLnCjXv9YlMx5SMYvugJrEh2mmmY-har0lJWGL6-HMs,211328 +pandas/_libs/tslibs/vectorized.pyi,sha256=Dv5ryF4HiPZcHWMyxyfP4D_tONdqLm2Mn4MpVi5RKCc,1239 +pandas/_libs/window/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/_libs/window/__pycache__/__init__.cpython-312.pyc,, +pandas/_libs/window/aggregations.cpython-312-darwin.so,sha256=xMemx_-7XCXPPAVaIwAlrD3hLm9q0Ba5jG6ThEnZcmQ,344032 +pandas/_libs/window/aggregations.pyi,sha256=vVjfgqY4cBPmjFadcrDc6heCiFbJ5Lz65bCadbHJbwU,4063 +pandas/_libs/window/indexers.cpython-312-darwin.so,sha256=h142H8tD4gie8fJE6iV4nMrI-pZMJxu09rKpcCqY7tA,192336 +pandas/_libs/window/indexers.pyi,sha256=53aBxew7jBcAc9sbSoOlvpQHhiLDSWPXFcVbCeJDbQA,319 +pandas/_libs/writers.cpython-312-darwin.so,sha256=6SBKYaySAnvwCEeYiAgCVOSwyE2bDRxGViwGTyUV_5g,213040 +pandas/_libs/writers.pyi,sha256=RvwFCzrsU4RkKm7Mc3wo12RqdGdo-PuANkMo3Z9hLiU,516 +pandas/_testing/__init__.py,sha256=GbvKDUymC5sD9x0oVVcv0EAtS8rBbkmoREWXfHLPpkU,17525 +pandas/_testing/__pycache__/__init__.cpython-312.pyc,, +pandas/_testing/__pycache__/_hypothesis.cpython-312.pyc,, +pandas/_testing/__pycache__/_io.cpython-312.pyc,, +pandas/_testing/__pycache__/_warnings.cpython-312.pyc,, +pandas/_testing/__pycache__/asserters.cpython-312.pyc,, +pandas/_testing/__pycache__/compat.cpython-312.pyc,, +pandas/_testing/__pycache__/contexts.cpython-312.pyc,, +pandas/_testing/_hypothesis.py,sha256=WS4ysEJwmMor02cwMw15kBtAR0SLvUUpTfYEpc0c6iI,2426 +pandas/_testing/_io.py,sha256=OwfQ9L0XZgD_Yfi5mF8_BLgPx8pgGZbTzq46uTa7jDo,4448 +pandas/_testing/_warnings.py,sha256=x7YMaPkmSaimJquGT3vAt9pKn0r_Hj5lE1uV0eCoDiU,8357 +pandas/_testing/asserters.py,sha256=R8oCv64OxoOG34eBfe3fefNREJMvd5HmK7LnSmyOM3s,48276 +pandas/_testing/compat.py,sha256=0o_biVI-wLh7kcw9FHvbwYyzNvM0PI06QRD2ZhiD2Fs,658 +pandas/_testing/contexts.py,sha256=_n9lQqod-zhc4xKHBiY-5kRBVOvxGCdB4Jhr62Yekcg,6737 +pandas/_typing.py,sha256=gVSimiU46Dduc2Ez8ZaOczv8c-UHTH4FZeg6LL6mnGk,14037 +pandas/_version.py,sha256=FXn5cnzqhgCmE1EGmDQS8RwvkhLZo4xPL292vWDKwRc,23677 +pandas/_version_meson.py,sha256=xqctrRkxGU50bfrdFIsKtAwrHmUXIuBVbndODlo07eU,79 +pandas/api/__init__.py,sha256=QnoYVW828TM17uq-3ELeethZm8XN2Y0DkEaTc3sLr3Q,219 +pandas/api/__pycache__/__init__.cpython-312.pyc,, +pandas/api/extensions/__init__.py,sha256=O7tmzpvIT0uv9H5K-yMTKcwZpml9cEaB5CLVMiUkRCk,685 +pandas/api/extensions/__pycache__/__init__.cpython-312.pyc,, +pandas/api/indexers/__init__.py,sha256=kNbZv9nja9iLVmGZU2D6w2dqB2ndsbqTfcsZsGz_Yo0,357 +pandas/api/indexers/__pycache__/__init__.cpython-312.pyc,, +pandas/api/interchange/__init__.py,sha256=J2hQIYAvL7gyh8hG9r3XYPX69lK7nJS3IIHZl4FESjw,230 +pandas/api/interchange/__pycache__/__init__.cpython-312.pyc,, +pandas/api/types/__init__.py,sha256=bOU3TUuskT12Dpp-SsCYtCWdHvBDp3MWf3Etq4ZMdT8,447 +pandas/api/types/__pycache__/__init__.cpython-312.pyc,, +pandas/api/typing/__init__.py,sha256=IC4_ZmjsX4804Nnu-lQDccQr0zt5mzIZEaB3Bzdva8Y,1244 +pandas/api/typing/__pycache__/__init__.cpython-312.pyc,, +pandas/arrays/__init__.py,sha256=gMhtojH1KdRwxMmM_Ulblxk4L09o7WLUsXLp6qdUS-I,1227 +pandas/arrays/__pycache__/__init__.cpython-312.pyc,, +pandas/compat/__init__.py,sha256=BJVIDYjdedr3q2oFUOC4qXgxOITt_Fm7DXW-sK5c_wU,4614 +pandas/compat/__pycache__/__init__.cpython-312.pyc,, +pandas/compat/__pycache__/_constants.cpython-312.pyc,, +pandas/compat/__pycache__/_optional.cpython-312.pyc,, +pandas/compat/__pycache__/compressors.cpython-312.pyc,, +pandas/compat/__pycache__/pickle_compat.cpython-312.pyc,, +pandas/compat/__pycache__/pyarrow.cpython-312.pyc,, +pandas/compat/_constants.py,sha256=-o3ZgTRNZwemvCppAeQpX9e0YuVUUIx76aDfIWTf9So,617 +pandas/compat/_optional.py,sha256=96Zlc2gqUYneSzSlraVRGfh2BsTWp4cOUcG2gHjw2E0,5089 +pandas/compat/compressors.py,sha256=GdDWdKzWqkImjdwzuVBwW2JvI7aMzpPV8QyhxWgJo0g,1975 +pandas/compat/numpy/__init__.py,sha256=UO-06Rj2g2Mk9rptXZG_fLtA3BhSPMVF4JhTLdSt5AM,1366 +pandas/compat/numpy/__pycache__/__init__.cpython-312.pyc,, +pandas/compat/numpy/__pycache__/function.cpython-312.pyc,, +pandas/compat/numpy/function.py,sha256=Qvflr9h4rYCw9o8I3RggkhdRqxvav1yioq_JeEUh2T4,13291 +pandas/compat/pickle_compat.py,sha256=MTp_LYeueJWVJBWKzWUyiwcwu9MvjEtBzEC0SozvWs8,7723 +pandas/compat/pyarrow.py,sha256=HsIOSx5eWLOeQDrhpTtHzP4gKGkBLwPw60n2GWgUWXM,1393 +pandas/conftest.py,sha256=mH_w2h4R2mLF_GP_dUr5ghBvM65U8tVk-gC5pMYSVQY,51045 +pandas/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/__pycache__/__init__.cpython-312.pyc,, +pandas/core/__pycache__/accessor.cpython-312.pyc,, +pandas/core/__pycache__/algorithms.cpython-312.pyc,, +pandas/core/__pycache__/api.cpython-312.pyc,, +pandas/core/__pycache__/apply.cpython-312.pyc,, +pandas/core/__pycache__/arraylike.cpython-312.pyc,, +pandas/core/__pycache__/base.cpython-312.pyc,, +pandas/core/__pycache__/common.cpython-312.pyc,, +pandas/core/__pycache__/config_init.cpython-312.pyc,, +pandas/core/__pycache__/construction.cpython-312.pyc,, +pandas/core/__pycache__/flags.cpython-312.pyc,, +pandas/core/__pycache__/frame.cpython-312.pyc,, +pandas/core/__pycache__/generic.cpython-312.pyc,, +pandas/core/__pycache__/indexing.cpython-312.pyc,, +pandas/core/__pycache__/missing.cpython-312.pyc,, +pandas/core/__pycache__/nanops.cpython-312.pyc,, +pandas/core/__pycache__/resample.cpython-312.pyc,, +pandas/core/__pycache__/roperator.cpython-312.pyc,, +pandas/core/__pycache__/sample.cpython-312.pyc,, +pandas/core/__pycache__/series.cpython-312.pyc,, +pandas/core/__pycache__/shared_docs.cpython-312.pyc,, +pandas/core/__pycache__/sorting.cpython-312.pyc,, +pandas/core/_numba/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/_numba/__pycache__/__init__.cpython-312.pyc,, +pandas/core/_numba/__pycache__/executor.cpython-312.pyc,, +pandas/core/_numba/__pycache__/extensions.cpython-312.pyc,, +pandas/core/_numba/executor.py,sha256=vsH8jIzWRHho1Au4euWT2opfg5YLG4SBD7xlpvvXGUs,7530 +pandas/core/_numba/extensions.py,sha256=awk7FcE_idoVGG0fc90R3qNFD-BFnghXuF3KrytB7hI,18430 +pandas/core/_numba/kernels/__init__.py,sha256=Z1t4IUC2MO0a5KbA0LurWfRZL4wNksHVBDLprGtPLlo,520 +pandas/core/_numba/kernels/__pycache__/__init__.cpython-312.pyc,, +pandas/core/_numba/kernels/__pycache__/mean_.cpython-312.pyc,, +pandas/core/_numba/kernels/__pycache__/min_max_.cpython-312.pyc,, +pandas/core/_numba/kernels/__pycache__/shared.cpython-312.pyc,, +pandas/core/_numba/kernels/__pycache__/sum_.cpython-312.pyc,, +pandas/core/_numba/kernels/__pycache__/var_.cpython-312.pyc,, +pandas/core/_numba/kernels/mean_.py,sha256=BesqY1gwFXPIeuXAQtDvvDBZuegsszFVTnl4lxguXEA,5646 +pandas/core/_numba/kernels/min_max_.py,sha256=tJ7OSKhne7jXpy4XSBpQS0tkP_0LggkH6iqWlxQ-FeE,3284 +pandas/core/_numba/kernels/shared.py,sha256=JUBa96LX4NmXhgXNyo859IwMXEl29EyhmRdMoQo1n78,611 +pandas/core/_numba/kernels/sum_.py,sha256=FeKOQl22qO6kN4hAmwmA3wXihrph5S03ucSt65GBquU,6488 +pandas/core/_numba/kernels/var_.py,sha256=5BaLdr7HKzdUvKvyifvL9qM36W16SAqk3Ny11OtpW9o,6973 +pandas/core/accessor.py,sha256=u57BIkm61_SNRzSdQjL210Jtil7BWFUB0HPNl9wCKdo,10044 +pandas/core/algorithms.py,sha256=gcP6Crbhyuf05Q52Lav84bkHtwCsYyzQFT8RFfpLWD4,55180 +pandas/core/api.py,sha256=9tm275sTpOKtdUvsFCXYQHmBdeJczGNBV1QGv3TQOOc,2911 +pandas/core/apply.py,sha256=ChLu7u0YETP8dboHansS0ZcjGqthfBwlFKLfONl9EXs,67184 +pandas/core/array_algos/__init__.py,sha256=8YLlO6TysEPxltfbNKdG9MlVXeDLfTIGNo2nUR-Zwl0,408 +pandas/core/array_algos/__pycache__/__init__.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/datetimelike_accumulations.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/masked_accumulations.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/masked_reductions.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/putmask.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/quantile.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/replace.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/take.cpython-312.pyc,, +pandas/core/array_algos/__pycache__/transforms.cpython-312.pyc,, +pandas/core/array_algos/datetimelike_accumulations.py,sha256=BCy87HXqI2WO0_cCGK-redvi2STJzCxswYYs06YdxB4,1686 +pandas/core/array_algos/masked_accumulations.py,sha256=PL-ZAMai7H1PIXLKE2f9LSL2Ow6WZqkusSQkFfIE8d4,2618 +pandas/core/array_algos/masked_reductions.py,sha256=3hgYzhgIQT5qY2Jj59-hwui8qGKhqtr6KKK51jxfqPY,5067 +pandas/core/array_algos/putmask.py,sha256=g02wtMt5MTIuT4IS6ukE1Eh8KWb3Hi932hc47dszqJ4,4593 +pandas/core/array_algos/quantile.py,sha256=zdzcwgoVRP3eBSM4NJHwocBJC3PINYN1jB02mJubFow,6548 +pandas/core/array_algos/replace.py,sha256=Q6uMdn4ebaQEoLc91P-NIZsFdCqKhfCxtCeky6-Z1x0,4070 +pandas/core/array_algos/take.py,sha256=n_pjn9mU7QQJ77SFXogEc5ofoMqRgNbkimwXFunz79M,20815 +pandas/core/array_algos/transforms.py,sha256=TPpSPX5CiePVGTFUwnimpcC5YeBOtjAPK20wQvG92QI,1104 +pandas/core/arraylike.py,sha256=BD2ZQP4zGPd4rJas9lS5C-_qp3XXDL2udU8tzD9bQIQ,17655 +pandas/core/arrays/__init__.py,sha256=dE6WRTblcq40JKhXJQDsOwvhFPJstj_8cegiLthH0ks,1314 +pandas/core/arrays/__pycache__/__init__.cpython-312.pyc,, +pandas/core/arrays/__pycache__/_arrow_string_mixins.cpython-312.pyc,, +pandas/core/arrays/__pycache__/_mixins.cpython-312.pyc,, +pandas/core/arrays/__pycache__/_ranges.cpython-312.pyc,, +pandas/core/arrays/__pycache__/_utils.cpython-312.pyc,, +pandas/core/arrays/__pycache__/base.cpython-312.pyc,, +pandas/core/arrays/__pycache__/boolean.cpython-312.pyc,, +pandas/core/arrays/__pycache__/categorical.cpython-312.pyc,, +pandas/core/arrays/__pycache__/datetimelike.cpython-312.pyc,, +pandas/core/arrays/__pycache__/datetimes.cpython-312.pyc,, +pandas/core/arrays/__pycache__/floating.cpython-312.pyc,, +pandas/core/arrays/__pycache__/integer.cpython-312.pyc,, +pandas/core/arrays/__pycache__/interval.cpython-312.pyc,, +pandas/core/arrays/__pycache__/masked.cpython-312.pyc,, +pandas/core/arrays/__pycache__/numeric.cpython-312.pyc,, +pandas/core/arrays/__pycache__/numpy_.cpython-312.pyc,, +pandas/core/arrays/__pycache__/period.cpython-312.pyc,, +pandas/core/arrays/__pycache__/string_.cpython-312.pyc,, +pandas/core/arrays/__pycache__/string_arrow.cpython-312.pyc,, +pandas/core/arrays/__pycache__/timedeltas.cpython-312.pyc,, +pandas/core/arrays/_arrow_string_mixins.py,sha256=HJQgnA_jIVMbNdyxGpgofdAwKDpKNmqJ2HHNbgSn00o,13375 +pandas/core/arrays/_mixins.py,sha256=1LuY5ZmBfMlW1uY0l9QxK7E5Wet05NfbvQ5BrRlsgGg,17406 +pandas/core/arrays/_ranges.py,sha256=Ig3E_ROJ5mbOtK639SJ0UqcI229BrtsAfa_avbqrO8g,6996 +pandas/core/arrays/_utils.py,sha256=RmwOy6xNhgZ61qmk_PFnQ5sW-RVrkOhsl4AvQyqOuAY,1901 +pandas/core/arrays/arrow/__init__.py,sha256=-EKwaHww-yrbm7Z5d3AN_KETWmXYgZ2dW6KHaE2iiLI,221 +pandas/core/arrays/arrow/__pycache__/__init__.cpython-312.pyc,, +pandas/core/arrays/arrow/__pycache__/_arrow_utils.cpython-312.pyc,, +pandas/core/arrays/arrow/__pycache__/accessors.cpython-312.pyc,, +pandas/core/arrays/arrow/__pycache__/array.cpython-312.pyc,, +pandas/core/arrays/arrow/__pycache__/extension_types.cpython-312.pyc,, +pandas/core/arrays/arrow/_arrow_utils.py,sha256=RulRjyWzUn9gVFVeypndUwDLezpR2SWACD6_BYmxKDg,1586 +pandas/core/arrays/arrow/accessors.py,sha256=tnhqgzdt-AwoekYClqDIiRN9hIIK1VHkQv3_cOYP9F4,13887 +pandas/core/arrays/arrow/array.py,sha256=C0Kibckj8bV56ncjl3sATkD575Rfv2P_1KGJDIfLFFs,104712 +pandas/core/arrays/arrow/extension_types.py,sha256=NJLTuf_8U8u-Fjt_qfWm7zhUtPQdvjH1JV8fY3oRv-Y,5459 +pandas/core/arrays/base.py,sha256=lVDKuYZLq8Cbkpg9Yc4eUF3-TUnF6R4Pv88HmX9r-WU,85781 +pandas/core/arrays/boolean.py,sha256=ln7GjlHHTtByAhQKX9XuymhifZTCNSpk1j7I-fQKObo,12440 +pandas/core/arrays/categorical.py,sha256=9h1IOXmihyWoiI-9Jj6sU8hklXZT7q8JDjfUeGcB8ug,100781 +pandas/core/arrays/datetimelike.py,sha256=fSbpUqiBljmsmvlf5iRsCESEtp6ge0hQVoL6GIvYOME,90548 +pandas/core/arrays/datetimes.py,sha256=N9uK8ieFv80NTcoN1BWWhy12sqBh7yN7Kb-icOWse1k,92963 +pandas/core/arrays/floating.py,sha256=pvZ72VDstzgslAM5-36KEyJ0z5PBVwTNogcJAxhhMP8,4286 +pandas/core/arrays/integer.py,sha256=FWsrgzs_DB3eG8VX1kfzUTMcKOHfa-ACFQh_xVpZPJU,6470 +pandas/core/arrays/interval.py,sha256=NsaDlzxiRTj6awmxgr7UYE8HQoSexy-Rozck5ce-J0Y,63830 +pandas/core/arrays/masked.py,sha256=qa7fJCCSRu_qnGYM2ci73MzXv56wf9Q3ITGi_xNp8vU,56578 +pandas/core/arrays/numeric.py,sha256=lVpSpsG_66z2QMHghCRoYef6dVJJ_QZAf9vkpLMJokI,9165 +pandas/core/arrays/numpy_.py,sha256=o9FVkgX8FtLlJPfF6yqxpRDqLnxGt-lEv3kjJwwceYA,18253 +pandas/core/arrays/period.py,sha256=VmfDHc7OC20gytcJ-qDRaipX7kJWN0LPoW6owMyk3Eg,41620 +pandas/core/arrays/sparse/__init__.py,sha256=iwvVqa2GG9TjYrd1rxCBjdLeGQBoRqUO2fZnILElbZg,356 +pandas/core/arrays/sparse/__pycache__/__init__.cpython-312.pyc,, +pandas/core/arrays/sparse/__pycache__/accessor.cpython-312.pyc,, +pandas/core/arrays/sparse/__pycache__/array.cpython-312.pyc,, +pandas/core/arrays/sparse/__pycache__/scipy_sparse.cpython-312.pyc,, +pandas/core/arrays/sparse/accessor.py,sha256=lZa3hwvXJKLMkXhqiWU8eev8qthvYQ1HgtW875qQe7g,12503 +pandas/core/arrays/sparse/array.py,sha256=tIAxGKX3yHW6YDBzLvfjIbQXBJP-MQup8f_U5yunmag,64585 +pandas/core/arrays/sparse/scipy_sparse.py,sha256=rVaj3PtVRrMPlzkoVFSkIopWV0xg0GJnpt1YljWT_zg,6462 +pandas/core/arrays/string_.py,sha256=jygz8cIpCCUosYwrVxcZd4lvKpploPPa8LC9FuUwPc0,39211 +pandas/core/arrays/string_arrow.py,sha256=Xn9uxBgF_eht7N5UtAfnIMwxTtpbSN4GCf3s-DrFA4g,19725 +pandas/core/arrays/timedeltas.py,sha256=eTi8b16Jumac8WIx8LLf_9ZeFzA4u1nipHMUoc5-lyM,37830 +pandas/core/base.py,sha256=em41dG9syrQXWeGG5f8v_ubiYfgP9GDZfvwwLNM1sJs,41384 +pandas/core/common.py,sha256=WwkpCOI8b9j5rxkhL_Dh5l-7EdkHFfSjIIx-QBsefa0,17449 +pandas/core/computation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/computation/__pycache__/__init__.cpython-312.pyc,, +pandas/core/computation/__pycache__/align.cpython-312.pyc,, +pandas/core/computation/__pycache__/api.cpython-312.pyc,, +pandas/core/computation/__pycache__/check.cpython-312.pyc,, +pandas/core/computation/__pycache__/common.cpython-312.pyc,, +pandas/core/computation/__pycache__/engines.cpython-312.pyc,, +pandas/core/computation/__pycache__/eval.cpython-312.pyc,, +pandas/core/computation/__pycache__/expr.cpython-312.pyc,, +pandas/core/computation/__pycache__/expressions.cpython-312.pyc,, +pandas/core/computation/__pycache__/ops.cpython-312.pyc,, +pandas/core/computation/__pycache__/parsing.cpython-312.pyc,, +pandas/core/computation/__pycache__/pytables.cpython-312.pyc,, +pandas/core/computation/__pycache__/scope.cpython-312.pyc,, +pandas/core/computation/align.py,sha256=IBp-G1qbFMICrgm8DYOF-Kt18iCcY_P3peeIGsDkNv4,6161 +pandas/core/computation/api.py,sha256=CQ2AF0hwydcgTHycMCFiyZIAU57RcZT-TVid17SIsV4,65 +pandas/core/computation/check.py,sha256=Vb1YqLq381-nUp8Vjkg6ycJOxP3dV2aO9XjyM1uhe2Q,226 +pandas/core/computation/common.py,sha256=-2EHScxo2jfEQ1oqnnlQ_2eOvtAIn8O2krBaveSwmjs,1442 +pandas/core/computation/engines.py,sha256=g9eiyVCUtNmJGbexh7KvTreAKKhs5mQaWx4Z5UeOZ5s,3314 +pandas/core/computation/eval.py,sha256=LLnOIBxP2AA9D21NdogPmc7cHL_Rm0729fqVR6HObq8,14212 +pandas/core/computation/expr.py,sha256=C9w_peWLaszjqJi6KjEW8dmnJJKBlW--kpa2i4PCZds,25269 +pandas/core/computation/expressions.py,sha256=K0vu_v8JBVjJn6eQqNocC4ciNKsIYnEZrq8xwvhik2M,7503 +pandas/core/computation/ops.py,sha256=x5Qe3PfjHF5v-FHBerUr39iNXk_T0hLvw0Wchm0RiAQ,14829 +pandas/core/computation/parsing.py,sha256=VhYh3en2onhyJkzTelz32-U4Vc3XadyjTwOVctsqlEI,6399 +pandas/core/computation/pytables.py,sha256=7-L2GZ43aWNKG6hz-j8RhL8BIEGAEvpYi6rX6Zsvm_4,20745 +pandas/core/computation/scope.py,sha256=eyMdfx-gcgJaVIRY2NBgQDt2nW5KSdUZ3M9VRPYUJtU,10203 +pandas/core/config_init.py,sha256=8-VUEhbIJ2_qnBNQjDT_Qjz7Au9E1Grg8c8YZdc3rfs,27004 +pandas/core/construction.py,sha256=LL1wNdLYbHcRfQNbTrSh5VPIyEHYPISUlCl1cHpOhjE,26384 +pandas/core/dtypes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/dtypes/__pycache__/__init__.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/api.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/astype.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/base.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/cast.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/common.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/concat.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/dtypes.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/generic.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/inference.cpython-312.pyc,, +pandas/core/dtypes/__pycache__/missing.cpython-312.pyc,, +pandas/core/dtypes/api.py,sha256=5mtML1OspdDbsWShw1fsDq93pg2pmuUGSBrvQWQcCgg,1819 +pandas/core/dtypes/astype.py,sha256=awzOpnfZ0dCYhzw_J4fekT7u0F0VwgsIapuiAbBkxxg,9207 +pandas/core/dtypes/base.py,sha256=EeL8zNbMtrvObdEJtqjkG_vIsoQE8zDZiIR2dHzHKPI,17042 +pandas/core/dtypes/cast.py,sha256=K9mMsjWoUGxk8thGOq4B6NGdEBrgv4ddURdY6EJocuo,62763 +pandas/core/dtypes/common.py,sha256=QtwlJgSKUvcwdxAwOOKxKW6Isnx_DuB6uBorYbz4cSk,48001 +pandas/core/dtypes/concat.py,sha256=Q_QujfB0C-CIWbcTlktmB02RgxCf7xQsOgEkOV67VPo,12579 +pandas/core/dtypes/dtypes.py,sha256=Iom_4KXCBa1T9w363LmO6miVd8WHE5fWyOLUpQGR47Y,76055 +pandas/core/dtypes/generic.py,sha256=avKoJBzIQ0pJiFg9mmQ1D5ltkZsYxu8uPa46Hat70Ro,4122 +pandas/core/dtypes/inference.py,sha256=OqA9itS2osQBP-mp8jJK9RJZJps4VPsTIvQFCX4EbGM,9012 +pandas/core/dtypes/missing.py,sha256=BPzbmr7O7ihmjLKE9A31ck54ANjAtrp8-dVT20MR5fQ,23632 +pandas/core/flags.py,sha256=NxbTcYlNEaO8MKCpbEc22PEpInFn7f7za7EAO6-mxEE,3763 +pandas/core/frame.py,sha256=8u3RH6B-lts04NAGAlubZiAPZ-vgFsHgEd0j7Bc97Fs,448198 +pandas/core/generic.py,sha256=pqS0lMiJaibBq-Un5qDVZ-qYY9xVcmt77DyFL_n4GAk,476871 +pandas/core/groupby/__init__.py,sha256=KamY9WI5B4cMap_3wZ5ycMdXM_rOxGSL7RtoKKPfjAo,301 +pandas/core/groupby/__pycache__/__init__.cpython-312.pyc,, +pandas/core/groupby/__pycache__/base.cpython-312.pyc,, +pandas/core/groupby/__pycache__/categorical.cpython-312.pyc,, +pandas/core/groupby/__pycache__/generic.cpython-312.pyc,, +pandas/core/groupby/__pycache__/groupby.cpython-312.pyc,, +pandas/core/groupby/__pycache__/grouper.cpython-312.pyc,, +pandas/core/groupby/__pycache__/indexing.cpython-312.pyc,, +pandas/core/groupby/__pycache__/numba_.cpython-312.pyc,, +pandas/core/groupby/__pycache__/ops.cpython-312.pyc,, +pandas/core/groupby/base.py,sha256=OrqG2_h_Bp8Z_MeLrAGWGROG-MtSloGqeaJ79qYbJm0,2740 +pandas/core/groupby/categorical.py,sha256=iCsl3d_unK4zAh_lR3eDIBVOhwsv9Bj9X1wbnaR90pw,3047 +pandas/core/groupby/generic.py,sha256=LCsrCIjuhcEz-yw3gyk5nYKNiMF1h8en6nQO1hhTywE,96885 +pandas/core/groupby/groupby.py,sha256=FDBsxGdLiy8SUpIURRUqKmEzJx-_MxAgU2SvcFnQjeg,197238 +pandas/core/groupby/grouper.py,sha256=Dl-0aoi3WEM9XXkEGNdv1aD8chxr6jteajAHhz3MU3c,38703 +pandas/core/groupby/indexing.py,sha256=QY4GZ4wDd-1K-we0EfdiFvmdAZ_VxVgPrYB0kBZf6wU,9510 +pandas/core/groupby/numba_.py,sha256=XjfPfYGbYJgkIKYFiq7Gjnr5wwZ8mKrkeHKTW42HZMg,4894 +pandas/core/groupby/ops.py,sha256=JLRUxQZ1E53mdAao4UAYGNANR3m2ONioBtQd0zD9Flk,38564 +pandas/core/indexers/__init__.py,sha256=M4CyNLiQoQ5ohoAMH5HES9Rh2lpryAM1toL-b1TJXj0,736 +pandas/core/indexers/__pycache__/__init__.cpython-312.pyc,, +pandas/core/indexers/__pycache__/objects.cpython-312.pyc,, +pandas/core/indexers/__pycache__/utils.cpython-312.pyc,, +pandas/core/indexers/objects.py,sha256=PR063DVlu8_-ti7GsLRb0e7o4oAz2xpMil0nMee18z0,14737 +pandas/core/indexers/utils.py,sha256=TgVCAX9r4MZw3QPH6aE-d55gRZcKN9H9X-MTZ4u-LiY,16069 +pandas/core/indexes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/indexes/__pycache__/__init__.cpython-312.pyc,, +pandas/core/indexes/__pycache__/accessors.cpython-312.pyc,, +pandas/core/indexes/__pycache__/api.cpython-312.pyc,, +pandas/core/indexes/__pycache__/base.cpython-312.pyc,, +pandas/core/indexes/__pycache__/category.cpython-312.pyc,, +pandas/core/indexes/__pycache__/datetimelike.cpython-312.pyc,, +pandas/core/indexes/__pycache__/datetimes.cpython-312.pyc,, +pandas/core/indexes/__pycache__/extension.cpython-312.pyc,, +pandas/core/indexes/__pycache__/frozen.cpython-312.pyc,, +pandas/core/indexes/__pycache__/interval.cpython-312.pyc,, +pandas/core/indexes/__pycache__/multi.cpython-312.pyc,, +pandas/core/indexes/__pycache__/period.cpython-312.pyc,, +pandas/core/indexes/__pycache__/range.cpython-312.pyc,, +pandas/core/indexes/__pycache__/timedeltas.cpython-312.pyc,, +pandas/core/indexes/accessors.py,sha256=MdP8zNlSQeeU7psOXwGUdQ1-8XKzYCl5mKMIcpMCiN8,19152 +pandas/core/indexes/api.py,sha256=tDBBn84I19nvPFQKj0GAZhb0zioLJqTUJjSVqyc4Fn4,10426 +pandas/core/indexes/base.py,sha256=dp-is3i5GQfl6lYro-cM2stcyXPvRM0fkH3TPbHogy0,267385 +pandas/core/indexes/category.py,sha256=_6LpQtBGFsgB4KSZhxEQT4QX57W3172MbvLIAzxboPA,16128 +pandas/core/indexes/datetimelike.py,sha256=JH8_o2NJNQj1A0N0YFcC3m5nQGStacI5bv1G-dzYKVA,28377 +pandas/core/indexes/datetimes.py,sha256=9WlccEKDghA6i_CTgcvDfsqa0qEzG9mHoJq1k7WgG0k,38330 +pandas/core/indexes/extension.py,sha256=-g-4POQ_dox1g3zG-HSZDCYu_UAwdQTMTZ-w7Rz63LE,5228 +pandas/core/indexes/frozen.py,sha256=QuFW2zV8wqY7PD5PHbUMJQc3a-c5Eyfkjblp4umOylM,3482 +pandas/core/indexes/interval.py,sha256=ISEFn2oinehs_WXcVDMMP1MOWeDd0FHeJkOxLM08GFI,38246 +pandas/core/indexes/multi.py,sha256=fp_JSAmx8zBjVUNT-lMDGwEkJAQG8e-wUfo6hccny7c,144147 +pandas/core/indexes/period.py,sha256=ohh7J43CgV1ijxn9ozNhO5Vwu0k1-3yURIWTWeNPRgg,18978 +pandas/core/indexes/range.py,sha256=qt5IS2batjnOHe90UK5jES7pZhglppW_-1wieLlZysA,39511 +pandas/core/indexes/timedeltas.py,sha256=9a5m2wLQUA2v2O6JibpDSssNvNzV8Af6dAJETEpD4qM,10960 +pandas/core/indexing.py,sha256=Fs0-PAzRtB0tuF8NYzqG0XZWMq3AbdA8rDc2GnwiP7E,98987 +pandas/core/interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/interchange/__pycache__/__init__.cpython-312.pyc,, +pandas/core/interchange/__pycache__/buffer.cpython-312.pyc,, +pandas/core/interchange/__pycache__/column.cpython-312.pyc,, +pandas/core/interchange/__pycache__/dataframe.cpython-312.pyc,, +pandas/core/interchange/__pycache__/dataframe_protocol.cpython-312.pyc,, +pandas/core/interchange/__pycache__/from_dataframe.cpython-312.pyc,, +pandas/core/interchange/__pycache__/utils.cpython-312.pyc,, +pandas/core/interchange/buffer.py,sha256=KujVQ1qeXMjgRdvwea37FqO9f2ULmLa6Rtr_mTQ11XU,3453 +pandas/core/interchange/column.py,sha256=tlHYyU6RP9ESD693d4WpDUNP0hq7MaTZnm6tLJXSq98,17547 +pandas/core/interchange/dataframe.py,sha256=M1mWjS70pYLFJau534NtgslcpY_8NiY4dRmRgT73TVo,3879 +pandas/core/interchange/dataframe_protocol.py,sha256=L9Wy8vB5oTsuYJQ9NBY4RIEAWXBclnTOH3I_txkIbZk,16177 +pandas/core/interchange/from_dataframe.py,sha256=m2Xu6_bXCNqZZhNvN9PT7vklzc51h_ItpFfu7h-LqD4,18077 +pandas/core/interchange/utils.py,sha256=TNyR-uXm7J_-wU0CLpIf9ih_bq8p5aBuUv6O_41wKK8,5051 +pandas/core/internals/__init__.py,sha256=LE8M58WRu_cvQZns2dxUMeBVjqNfwRWw6vtWKiBrr2I,2615 +pandas/core/internals/__pycache__/__init__.cpython-312.pyc,, +pandas/core/internals/__pycache__/api.cpython-312.pyc,, +pandas/core/internals/__pycache__/array_manager.cpython-312.pyc,, +pandas/core/internals/__pycache__/base.cpython-312.pyc,, +pandas/core/internals/__pycache__/blocks.cpython-312.pyc,, +pandas/core/internals/__pycache__/concat.cpython-312.pyc,, +pandas/core/internals/__pycache__/construction.cpython-312.pyc,, +pandas/core/internals/__pycache__/managers.cpython-312.pyc,, +pandas/core/internals/__pycache__/ops.cpython-312.pyc,, +pandas/core/internals/api.py,sha256=s78Hb4dHuBAufRH9vTd1KO6o0bs-9CoBOsRF6GP03lE,4695 +pandas/core/internals/array_manager.py,sha256=q_QKlETGKdb1r8aFKVfV4ZrMoVO1wFNAC2JNHCZ6rGE,43927 +pandas/core/internals/base.py,sha256=pO6sju5EIq7u23J7CGPZNTEotbL4KYKzRgyIEmBhqpg,11161 +pandas/core/internals/blocks.py,sha256=JmqtO3vd5hCa6UnT-yrCCQelO__EliVte59HODSXrOU,101163 +pandas/core/internals/concat.py,sha256=Q_MnHIKSMBvIvA6DpMNkcsQSv8aU9DivUn1mlA_9zEs,19151 +pandas/core/internals/construction.py,sha256=KTXO-vrWKfm8-HwTLrsw0r0qVPadXc5pJ_lmkb8U25s,34207 +pandas/core/internals/managers.py,sha256=edyWolHEp3Tzt1HyCLbfr1T9vCtF55e19WD-WjuNsNw,82601 +pandas/core/internals/ops.py,sha256=Rh2-gWjeSwXnjkiacohSNM5iNvqQqBiAqgblwP6rD9o,5145 +pandas/core/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/core/methods/__pycache__/describe.cpython-312.pyc,, +pandas/core/methods/__pycache__/selectn.cpython-312.pyc,, +pandas/core/methods/__pycache__/to_dict.cpython-312.pyc,, +pandas/core/methods/describe.py,sha256=IeCkAFDUdVNxoPPqP1R1HzDlKFQHvlg46AgIxntD5Cs,11961 +pandas/core/methods/selectn.py,sha256=oomBEebumUfbJ5OLi9vw7saH31vbiy3lK-i63VKWBOw,7696 +pandas/core/methods/to_dict.py,sha256=sep0EfimrQ5UNJu-KwC1uYzx1BvbrackOe2-qxl2F5Y,8649 +pandas/core/missing.py,sha256=x_XOmge6_k9uIij2tyJZBEFKpAju1xUS9knQhe5kleU,35270 +pandas/core/nanops.py,sha256=kJpYqWg4E-D89HOXcufquZH0_rPFRbgbmZAULygpDnU,50984 +pandas/core/ops/__init__.py,sha256=CQ7tQB-QPUxD6ZnbS2SzFVjjvCD7-ciglexkdbbn7y8,1620 +pandas/core/ops/__pycache__/__init__.cpython-312.pyc,, +pandas/core/ops/__pycache__/array_ops.cpython-312.pyc,, +pandas/core/ops/__pycache__/common.cpython-312.pyc,, +pandas/core/ops/__pycache__/dispatch.cpython-312.pyc,, +pandas/core/ops/__pycache__/docstrings.cpython-312.pyc,, +pandas/core/ops/__pycache__/invalid.cpython-312.pyc,, +pandas/core/ops/__pycache__/mask_ops.cpython-312.pyc,, +pandas/core/ops/__pycache__/missing.cpython-312.pyc,, +pandas/core/ops/array_ops.py,sha256=wNV7RL-HZoB_I61YlF5nskpH-4RxA2n3P_gj31i18FM,19079 +pandas/core/ops/common.py,sha256=jVf_L_oN6bKcUOuH6FgaKOx18se9C3Hl2JPd0Uoj4t4,3500 +pandas/core/ops/dispatch.py,sha256=5XFIr7HV1Dicohgm0ZJu-6argn2Qd0OwES2bBxQwCj0,635 +pandas/core/ops/docstrings.py,sha256=WlGWcWjNsldPW73krxbgRwQvkacmKqRqJsN4VVz-FXU,18448 +pandas/core/ops/invalid.py,sha256=5-gRzdBfk2F8qIZ_vzUlnI-vo1HsAh2F5BYJUEN--m0,1433 +pandas/core/ops/mask_ops.py,sha256=0sm9L1LB_USp8DxNBuCdoB8cJ_MzzvSAb_u3QQmQrKI,5409 +pandas/core/ops/missing.py,sha256=0WlqN_us0LU5RAdoitM-Ko_4xghJ_HBRkteLQ53fU14,5140 +pandas/core/resample.py,sha256=O_tYjMqORGEp7thHWgUS7vkJwYWtevPLbtXjqPStRYE,95014 +pandas/core/reshape/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/reshape/__pycache__/__init__.cpython-312.pyc,, +pandas/core/reshape/__pycache__/api.cpython-312.pyc,, +pandas/core/reshape/__pycache__/concat.cpython-312.pyc,, +pandas/core/reshape/__pycache__/encoding.cpython-312.pyc,, +pandas/core/reshape/__pycache__/melt.cpython-312.pyc,, +pandas/core/reshape/__pycache__/merge.cpython-312.pyc,, +pandas/core/reshape/__pycache__/pivot.cpython-312.pyc,, +pandas/core/reshape/__pycache__/reshape.cpython-312.pyc,, +pandas/core/reshape/__pycache__/tile.cpython-312.pyc,, +pandas/core/reshape/__pycache__/util.cpython-312.pyc,, +pandas/core/reshape/api.py,sha256=Qk5y-D5-OdRYKkCgc-ktcxKGNGSCPteISEsByXFWI9M,680 +pandas/core/reshape/concat.py,sha256=qwXsAlI9pnLld1pj9uqHf2zinXd-fj8GE3kZ-XNVacU,28253 +pandas/core/reshape/encoding.py,sha256=jcRfM1NdE6FSjrvrYD8a--PsqXTq6FTFWfC2mwIzS54,19016 +pandas/core/reshape/melt.py,sha256=Zj6PSyI3Dbi_aQPhYyFTz_cWi9m8kIubwItq57JNCFQ,17400 +pandas/core/reshape/merge.py,sha256=WiJNUTxQywQPl0FUPyuy-sThsCK4QEADDOqwDmOSfCo,99673 +pandas/core/reshape/pivot.py,sha256=ylkSVYQcoMmuxqvEoyEP6YHzeVtGL9y6ueAEfN6_RzY,28917 +pandas/core/reshape/reshape.py,sha256=_slnrYBb1ZFgqP1501D5JNF5LmWzD2PQGDtrzwk-eP0,34661 +pandas/core/reshape/tile.py,sha256=bDzSjjPydhiCce0DOJab1327a613mhs98PimwfIddjQ,21947 +pandas/core/reshape/util.py,sha256=zrShSZARSsWULoXI5tdWqwgZSLQ-u_3xNPS5cpB4QbY,2014 +pandas/core/roperator.py,sha256=ljko3iHhBm5ZvEVqrGEbwGV4z0cXd4TE1uSzf-LZlQ8,1114 +pandas/core/sample.py,sha256=QEPzbFmeMRMxAIqfkRrJLnIjUZgSupbP8YUEezW-Pcw,4626 +pandas/core/series.py,sha256=rcPpqn1bUYHGPf3asAUOzXi-4LMrgcka6yfR_Cfc5Ck,213784 +pandas/core/shared_docs.py,sha256=Fdd7Xi1TQ_esZXq32Gu-ZPiShIHE2VROSSRtzet509s,30103 +pandas/core/sorting.py,sha256=kxr4Phz8HHAsEbyx9J5SCYZ4xENhoZnFmMEAUI-NpIU,22976 +pandas/core/sparse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/sparse/__pycache__/__init__.cpython-312.pyc,, +pandas/core/sparse/__pycache__/api.cpython-312.pyc,, +pandas/core/sparse/api.py,sha256=y0onCpBKCj_5Iaybw5e-gxk8zAa9d1p5Zu58RLzPT1k,143 +pandas/core/strings/__init__.py,sha256=KYCMtwb7XWzZXsIZGijtjw9ofs2DIqE9psfKoxRsHuw,1087 +pandas/core/strings/__pycache__/__init__.cpython-312.pyc,, +pandas/core/strings/__pycache__/accessor.cpython-312.pyc,, +pandas/core/strings/__pycache__/base.cpython-312.pyc,, +pandas/core/strings/__pycache__/object_array.cpython-312.pyc,, +pandas/core/strings/accessor.py,sha256=aWeqPXLhqBVN3atM7MyQG5O_uLAS-E0IbxwtRjM0xE0,113836 +pandas/core/strings/base.py,sha256=ir-yia8EsnqfBp9MvpGC3WP2wQaQAQzlPG48iR6l4-E,5619 +pandas/core/strings/object_array.py,sha256=jNTKrF_2HhUs53dgHrIGY6pW94Pe6PTLwu5cKEPcExE,16855 +pandas/core/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/tools/__pycache__/__init__.cpython-312.pyc,, +pandas/core/tools/__pycache__/datetimes.cpython-312.pyc,, +pandas/core/tools/__pycache__/numeric.cpython-312.pyc,, +pandas/core/tools/__pycache__/timedeltas.cpython-312.pyc,, +pandas/core/tools/__pycache__/times.cpython-312.pyc,, +pandas/core/tools/datetimes.py,sha256=BIHvjFnfH3XxuHtpb4Wxxdk46LxAcmYyD8OGDb_qXwA,43606 +pandas/core/tools/numeric.py,sha256=JnlwsvJlZTiNUxR_MZLHx9Gqz-vwNlNkaXgHP16ijcM,11051 +pandas/core/tools/timedeltas.py,sha256=kyDgKp9yRpw-gzucChvvekVQKy1sHu8J5qQwbwWaukg,8858 +pandas/core/tools/times.py,sha256=_-z5faRW4NA04LKN-eUgvklqOjRIncQyndFdSzwzDXI,5373 +pandas/core/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/core/util/__pycache__/__init__.cpython-312.pyc,, +pandas/core/util/__pycache__/hashing.cpython-312.pyc,, +pandas/core/util/__pycache__/numba_.cpython-312.pyc,, +pandas/core/util/hashing.py,sha256=LlYoJfn80z0zj0xNt5P3PYRVFJafXI3bRnSYV361Avs,9657 +pandas/core/util/numba_.py,sha256=U-2_obqjB_DwLc7Bu6swTCdPdNU62Z9l0QpxYM5Edng,2582 +pandas/core/window/__init__.py,sha256=DewB8XXkLGEDgtQqICYPmnkZZ3Y4tN6zPoTYvpNuJGE,450 +pandas/core/window/__pycache__/__init__.cpython-312.pyc,, +pandas/core/window/__pycache__/common.cpython-312.pyc,, +pandas/core/window/__pycache__/doc.cpython-312.pyc,, +pandas/core/window/__pycache__/ewm.cpython-312.pyc,, +pandas/core/window/__pycache__/expanding.cpython-312.pyc,, +pandas/core/window/__pycache__/numba_.cpython-312.pyc,, +pandas/core/window/__pycache__/online.cpython-312.pyc,, +pandas/core/window/__pycache__/rolling.cpython-312.pyc,, +pandas/core/window/common.py,sha256=LZBddjEy7C_nb-9gmsk2wQr-FsF1WBMsGKd8ptmMdug,6714 +pandas/core/window/doc.py,sha256=iCAs_hJ_pwstet2FHwSilVSXoTaKRuuMHwyZ9l2dz_c,4158 +pandas/core/window/ewm.py,sha256=nniOOhhrrx88wUd1iG2C2vyhT6mfd1N4UbDt4pY1F78,35190 +pandas/core/window/expanding.py,sha256=MnepmpreeY11OX9nQHj5TxgYdnOPJIRC-Cr3MyDnC38,27845 +pandas/core/window/numba_.py,sha256=7x9RvcIvPab0C5uXT4U9cP1VNaI7Yym0CevTsMIu27U,10606 +pandas/core/window/online.py,sha256=NKHkFpehR5QDT5VrCESEqjZ9a_Fq0JkchzmXFtzLRds,3735 +pandas/core/window/rolling.py,sha256=jj5NmCV28NgsWXMaBVqV-j8-JPwZOCu3heLi9AAbTMU,95504 +pandas/errors/__init__.py,sha256=DotJJfd-bS7FSQbnLC6SKWCfz_GqGYS6Gy6Fc9AJZg0,27164 +pandas/errors/__pycache__/__init__.cpython-312.pyc,, +pandas/io/__init__.py,sha256=4YJcSmLT6iTWceVgxGNSyRJq91wxhrgsNr47uc4Rw-I,293 +pandas/io/__pycache__/__init__.cpython-312.pyc,, +pandas/io/__pycache__/_util.cpython-312.pyc,, +pandas/io/__pycache__/api.cpython-312.pyc,, +pandas/io/__pycache__/clipboards.cpython-312.pyc,, +pandas/io/__pycache__/common.cpython-312.pyc,, +pandas/io/__pycache__/feather_format.cpython-312.pyc,, +pandas/io/__pycache__/gbq.cpython-312.pyc,, +pandas/io/__pycache__/html.cpython-312.pyc,, +pandas/io/__pycache__/orc.cpython-312.pyc,, +pandas/io/__pycache__/parquet.cpython-312.pyc,, +pandas/io/__pycache__/pickle.cpython-312.pyc,, +pandas/io/__pycache__/pytables.cpython-312.pyc,, +pandas/io/__pycache__/spss.cpython-312.pyc,, +pandas/io/__pycache__/sql.cpython-312.pyc,, +pandas/io/__pycache__/stata.cpython-312.pyc,, +pandas/io/__pycache__/xml.cpython-312.pyc,, +pandas/io/_util.py,sha256=7AXuIcOdzDaLxkapNC00BUbTBAFwiQ21rorXLGlJd4A,2676 +pandas/io/api.py,sha256=w7Ux3U8PI-SeP13hD3PMjWMf3YbOGog6zCDqj0nfnpI,1264 +pandas/io/clipboard/__init__.py,sha256=3aFzdoqbabE8XM-FYjdYIctTps_sTAJDJMrhEbDv_UU,24235 +pandas/io/clipboard/__pycache__/__init__.cpython-312.pyc,, +pandas/io/clipboards.py,sha256=t88NnxP8TOpmM1V438o6jgvlEMzlRLaqWBxUQiH_EQ8,6320 +pandas/io/common.py,sha256=hsjBpZc8i9O_aKMpCms0tuQ2jAqbkVzLXnUKI01TVcU,40615 +pandas/io/excel/__init__.py,sha256=w62gHQ9nF3XgBOmjhM8eHmV-YXF7gflz1lFqxFq7io8,486 +pandas/io/excel/__pycache__/__init__.cpython-312.pyc,, +pandas/io/excel/__pycache__/_base.cpython-312.pyc,, +pandas/io/excel/__pycache__/_calamine.cpython-312.pyc,, +pandas/io/excel/__pycache__/_odfreader.cpython-312.pyc,, +pandas/io/excel/__pycache__/_odswriter.cpython-312.pyc,, +pandas/io/excel/__pycache__/_openpyxl.cpython-312.pyc,, +pandas/io/excel/__pycache__/_pyxlsb.cpython-312.pyc,, +pandas/io/excel/__pycache__/_util.cpython-312.pyc,, +pandas/io/excel/__pycache__/_xlrd.cpython-312.pyc,, +pandas/io/excel/__pycache__/_xlsxwriter.cpython-312.pyc,, +pandas/io/excel/_base.py,sha256=tEBB5m3LcL8ZHv62Kv7G4Ul9MElr2X8JrkXvadypzC4,59073 +pandas/io/excel/_calamine.py,sha256=7O8I8yg-dpaK6OqdZflV14ggDbNDJrinhgAPxXgh9ro,3474 +pandas/io/excel/_odfreader.py,sha256=vMVZ-lNJpMB0vQ8cewanVpjj3-sFzUAS-I-w28nOmoY,8262 +pandas/io/excel/_odswriter.py,sha256=o7dP9MQYRyDO88kFeJMiyW5SmCxusykb8vew4QHMjsg,11210 +pandas/io/excel/_openpyxl.py,sha256=CshETVibZ0_rwbNq0y7sPkzSgnXpwI7FUtvAj8efU6Q,19861 +pandas/io/excel/_pyxlsb.py,sha256=74huu-7ISIsfvguwDID84B3KIooHtU53XOP3PFkX6ts,4358 +pandas/io/excel/_util.py,sha256=1fwMlNjLSd_qlCGLGBcXDPLnZ_SOpAZTIaUgYUVr0_0,8105 +pandas/io/excel/_xlrd.py,sha256=tddoGt7ugmyTTryMeqSvU6FE9vgajsMYfrSLQytMEV0,4556 +pandas/io/excel/_xlsxwriter.py,sha256=nqbCJWypKW4q56n9MdjcTlrPUiPRD7__s8AExSMbVlY,9217 +pandas/io/feather_format.py,sha256=rIbQD6J6nOzYvfs6be1vXLptR3ObL7fP36eOa8b4GRg,4007 +pandas/io/formats/__init__.py,sha256=MGhPbyRcirFXg_uAGxyQ_q8Bky6ZUpBZ0nHXQa5LYd8,238 +pandas/io/formats/__pycache__/__init__.cpython-312.pyc,, +pandas/io/formats/__pycache__/_color_data.cpython-312.pyc,, +pandas/io/formats/__pycache__/console.cpython-312.pyc,, +pandas/io/formats/__pycache__/css.cpython-312.pyc,, +pandas/io/formats/__pycache__/csvs.cpython-312.pyc,, +pandas/io/formats/__pycache__/excel.cpython-312.pyc,, +pandas/io/formats/__pycache__/format.cpython-312.pyc,, +pandas/io/formats/__pycache__/html.cpython-312.pyc,, +pandas/io/formats/__pycache__/info.cpython-312.pyc,, +pandas/io/formats/__pycache__/printing.cpython-312.pyc,, +pandas/io/formats/__pycache__/string.cpython-312.pyc,, +pandas/io/formats/__pycache__/style.cpython-312.pyc,, +pandas/io/formats/__pycache__/style_render.cpython-312.pyc,, +pandas/io/formats/__pycache__/xml.cpython-312.pyc,, +pandas/io/formats/_color_data.py,sha256=fZ_QluvMFUNKUE4-T32x7Pn0nulQgxmsEMHB9URcBOY,4332 +pandas/io/formats/console.py,sha256=dcoFM-rirR8qdc1bvgJySPhZvk23S6Nkz3-2Lc30pMk,2748 +pandas/io/formats/css.py,sha256=gCSjRV6QatAMY-La26wnrQmyF78G4BruMfpWrDIKIkk,12793 +pandas/io/formats/csvs.py,sha256=JAI3kO6xKSMjsLxlYk4EijBuktOHRwU9U91a92OvYnQ,10526 +pandas/io/formats/excel.py,sha256=vW5_Pii4i_wv_VNVR0wn-7IFwdgf2tzROor4eThVO68,32994 +pandas/io/formats/format.py,sha256=hE435SvGhcNrad54edLzyvPnHty1uCUYmtN9gD1x2G4,66148 +pandas/io/formats/html.py,sha256=AiROfWxTRrMT75LZsrBMJTIs3ky9n1x3nUnXzKpZILM,24165 +pandas/io/formats/info.py,sha256=heCm4flQPvNMNW6zecz_XUrfV5O-_zWdpam_dk3V2Tc,32621 +pandas/io/formats/printing.py,sha256=Hrs0vaaacrfswH7FuPCM9FnVg5kKL5vGYl8-ZxAQC4Q,17950 +pandas/io/formats/string.py,sha256=f6UNLnvUV-iO-7k7zXqWBOs7hOoU7_fWQzogyeY8c7I,6707 +pandas/io/formats/style.py,sha256=BRv6I9qQLXOUP-qtBtAg9ms8mZRD7kd60J2w6k7wVpo,155868 +pandas/io/formats/style_render.py,sha256=TgyXK40A4dp8geKIeGWMwNm_v597jWQmJZH-H-TSSdQ,90899 +pandas/io/formats/templates/html.tpl,sha256=KA-w_npfnHM_1c5trtJtkd3OD9j8hqtoQAY4GCC5UgI,412 +pandas/io/formats/templates/html_style.tpl,sha256=_gCqktLyUGAo5TzL3I-UCp1Njj8KyeLCWunHz4nYHsE,694 +pandas/io/formats/templates/html_table.tpl,sha256=MJxwJFwOa4KNli-ix7vYAGjRzw59FLAmYKHMy9nC32k,1811 +pandas/io/formats/templates/latex.tpl,sha256=m-YMxqKVJ52kLd61CA9V2MiC_Dtwwa-apvU8YtH8TYU,127 +pandas/io/formats/templates/latex_longtable.tpl,sha256=opn-JNfuMX81g1UOWYFJLKdQSUwoSP_UAKbK4kYRph4,2877 +pandas/io/formats/templates/latex_table.tpl,sha256=YNvnvjtwYXrWFVXndQZdJqKFIXYTUj8f1YOUdMmxXmQ,2221 +pandas/io/formats/templates/string.tpl,sha256=Opr87f1tY8yp_G7GOY8ouFllR_7vffN_ok7Ndf98joE,344 +pandas/io/formats/xml.py,sha256=dLBpVLGltVRiOxYCIVLb4okLXwhPneRp7whi2VbV1gk,16029 +pandas/io/gbq.py,sha256=nkdYZ0w5ZetYdWpIIKALLh5_3nNhFE1hvVV9rJ5yyhk,9372 +pandas/io/html.py,sha256=E4rdZT6DVcMRSeDaceBsMpWrc-A9aAEvF5sbW4DstIg,39546 +pandas/io/json/__init__.py,sha256=ArWTQnIKhxDVaMI1j0Whgpk0ci6dP0mpUiGwMRqEdtY,270 +pandas/io/json/__pycache__/__init__.cpython-312.pyc,, +pandas/io/json/__pycache__/_json.cpython-312.pyc,, +pandas/io/json/__pycache__/_normalize.cpython-312.pyc,, +pandas/io/json/__pycache__/_table_schema.cpython-312.pyc,, +pandas/io/json/_json.py,sha256=nyznN821ajpCfe-z-geEWqQDNaWnHsnn_3tfDT81Dj8,48231 +pandas/io/json/_normalize.py,sha256=rbyrEKwuxotrABiv6Jmb9JN6k6rCXd99ONrEZv2IbXI,17212 +pandas/io/json/_table_schema.py,sha256=KB-w3ozEEQUITNLtMtx8P9JeDrjQo8G7uYsVnqna4c8,11552 +pandas/io/orc.py,sha256=xz3dk0AvHEC92LiCn7cH-x7fA6DXZQaR8xA2zQUVi2c,7817 +pandas/io/parquet.py,sha256=CotFKy_O8b6Ccygh7H35KwIhjxNSWH94A5GL1iHC_WM,23641 +pandas/io/parsers/__init__.py,sha256=7BLx4kn9y5ipgfZUWZ4y_MLEUNgX6MQ5DyDwshhJxVM,204 +pandas/io/parsers/__pycache__/__init__.cpython-312.pyc,, +pandas/io/parsers/__pycache__/arrow_parser_wrapper.cpython-312.pyc,, +pandas/io/parsers/__pycache__/base_parser.cpython-312.pyc,, +pandas/io/parsers/__pycache__/c_parser_wrapper.cpython-312.pyc,, +pandas/io/parsers/__pycache__/python_parser.cpython-312.pyc,, +pandas/io/parsers/__pycache__/readers.cpython-312.pyc,, +pandas/io/parsers/arrow_parser_wrapper.py,sha256=I-OXG06TKyv6lx__lSpTgIchpWct9VU6F-88cH6fbyQ,11080 +pandas/io/parsers/base_parser.py,sha256=s-bYfeFE7R3gfTuOQQPAP600fgu950Z81UnvCHPDvKA,49980 +pandas/io/parsers/c_parser_wrapper.py,sha256=yXK-ZrUOxZcXdZ9rtINgRl7l426tdoch8GyZIS_nCMI,14199 +pandas/io/parsers/python_parser.py,sha256=9fnAQ5iFQwBETy-6ptu66-3Ppu8tn81CGSRyYxhgE2I,48456 +pandas/io/parsers/readers.py,sha256=yP4xBAdreacpmmKamh7w6O4CTl0NQ5z0UVSuA7LSs0c,87157 +pandas/io/pickle.py,sha256=t4OulGy7CQL60LXTC8kebegWM7QaJOmudlynAgWxo4w,6582 +pandas/io/pytables.py,sha256=85igkNwq029a70jiU7obu3DYAnTP5VVjgoWGhtjFVBI,181685 +pandas/io/sas/__init__.py,sha256=AIAudC9f784kcEzuho8GiXU63vj2ThRitKznl7Imkq4,69 +pandas/io/sas/__pycache__/__init__.cpython-312.pyc,, +pandas/io/sas/__pycache__/sas7bdat.cpython-312.pyc,, +pandas/io/sas/__pycache__/sas_constants.cpython-312.pyc,, +pandas/io/sas/__pycache__/sas_xport.cpython-312.pyc,, +pandas/io/sas/__pycache__/sasreader.cpython-312.pyc,, +pandas/io/sas/sas7bdat.py,sha256=kHkufkBH7jqj9cPACxImJnybYDRQ5pOguJ1QjZ4KJ5A,27730 +pandas/io/sas/sas_constants.py,sha256=CM1wSNzXn6nkjLMSTeBhBJlL6d0hU-1YdNwEO8HE-9U,8719 +pandas/io/sas/sas_xport.py,sha256=_N7sGHw4Z80u-emCxS4lv6UFs6N01eKj5CZkTzq7XiM,15134 +pandas/io/sas/sasreader.py,sha256=S7bRlsXahhpoTkKdsHoWY9TLo_jgzNJJdsb6gxpcfuY,4885 +pandas/io/spss.py,sha256=p4vW9rJEFLPBqEIHMR5fCmo2U-JBTvgnDNd74Y7DFuI,2182 +pandas/io/sql.py,sha256=7zxdQNoaw4AR_mWjmR37pCPc9Rs0ZSyTXnHgMpXb8go,101544 +pandas/io/stata.py,sha256=3JnSRxbd_NxE6grWAOa1OZO_bGtqGgjKIls6wZpUn_A,136105 +pandas/io/xml.py,sha256=ZKHsFACIJhlNJqU8nNBpG-OjHZ2uE_wzh94OOBuj8iI,38656 +pandas/plotting/__init__.py,sha256=W_2wP9v02mNCK4lV5ekG1iJHYSF8dD1NbByJiNq3g8I,2826 +pandas/plotting/__pycache__/__init__.cpython-312.pyc,, +pandas/plotting/__pycache__/_core.cpython-312.pyc,, +pandas/plotting/__pycache__/_misc.cpython-312.pyc,, +pandas/plotting/_core.py,sha256=BLIzDrRcaDDYBpXj8nfw3aIXabos6YlwPjondYmh6II,66558 +pandas/plotting/_matplotlib/__init__.py,sha256=jGq_ouunQTV3zzX_crl9kCVX2ztk1p62McqD2WVRnAk,2044 +pandas/plotting/_matplotlib/__pycache__/__init__.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/boxplot.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/converter.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/core.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/groupby.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/hist.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/misc.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/style.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/timeseries.cpython-312.pyc,, +pandas/plotting/_matplotlib/__pycache__/tools.cpython-312.pyc,, +pandas/plotting/_matplotlib/boxplot.py,sha256=AaLBxRNm6ke8J0JnDZtSr9g93LPMVmkgyLLqQ6ovYfU,18385 +pandas/plotting/_matplotlib/converter.py,sha256=EcdgaqQPOqYIO2noB-6J2xkODsBwATamuwA315SCVog,37033 +pandas/plotting/_matplotlib/core.py,sha256=20oTgXZwzTQDfqBY6g_HT9CsGd1RkuNtnu0YE-rtO5U,71826 +pandas/plotting/_matplotlib/groupby.py,sha256=vg8RYC3SxN2Khc-34GDV3UpCVSPnawt4zwYqIuzb5HE,4343 +pandas/plotting/_matplotlib/hist.py,sha256=uljuycUD16A6u3GdktvZwXdU3qMKPfFLFMgYmBX4zQU,16816 +pandas/plotting/_matplotlib/misc.py,sha256=tzbAVRDGc1Ep6BR3QbYAEKEHgkX2vwMBX9k9uwN-j8c,13358 +pandas/plotting/_matplotlib/style.py,sha256=mKDcq4cBmYF9zDrBv3st3fNFvSn-91rYEH5cLXaYiw0,8368 +pandas/plotting/_matplotlib/timeseries.py,sha256=kWTVawvq5tdX1zpSm8vNlYXZgUqKCM_DYxvjUebOQbY,11349 +pandas/plotting/_matplotlib/tools.py,sha256=yH7FSA6FMW0Idrxkg12Ki0SHjbVR7tpYu-R6SHX5gzo,15415 +pandas/plotting/_misc.py,sha256=sbOaqkE9lA5HbikzcFBcXe9tdqHMVAxxMH3V9QfYr-c,20929 +pandas/pyproject.toml,sha256=PIy8v_nQx96MbMDZbj1x_jkfL6x2zsjAu89EagFG9mQ,24666 +pandas/testing.py,sha256=3XTHuY440lezW7rxw4LW9gfxzDEa7s0l16cdnkRYwwM,313 +pandas/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/__pycache__/test_aggregation.cpython-312.pyc,, +pandas/tests/__pycache__/test_algos.cpython-312.pyc,, +pandas/tests/__pycache__/test_common.cpython-312.pyc,, +pandas/tests/__pycache__/test_downstream.cpython-312.pyc,, +pandas/tests/__pycache__/test_errors.cpython-312.pyc,, +pandas/tests/__pycache__/test_expressions.cpython-312.pyc,, +pandas/tests/__pycache__/test_flags.cpython-312.pyc,, +pandas/tests/__pycache__/test_multilevel.cpython-312.pyc,, +pandas/tests/__pycache__/test_nanops.cpython-312.pyc,, +pandas/tests/__pycache__/test_optional_dependency.cpython-312.pyc,, +pandas/tests/__pycache__/test_register_accessor.cpython-312.pyc,, +pandas/tests/__pycache__/test_sorting.cpython-312.pyc,, +pandas/tests/__pycache__/test_take.cpython-312.pyc,, +pandas/tests/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/api/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/api/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/api/__pycache__/test_types.cpython-312.pyc,, +pandas/tests/api/test_api.py,sha256=ZQI3_TgIuolTfuKy-a4eds0io74Q4kvy8fG6NZDoj-M,9394 +pandas/tests/api/test_types.py,sha256=ZR8n_efaY7HWGY6XnRZKNIiRWmaszpNU8p22kvAbyEQ,1711 +pandas/tests/apply/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/apply/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/apply/__pycache__/common.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_frame_apply.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_frame_apply_relabeling.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_frame_transform.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_invalid_arg.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_numba.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_series_apply.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_series_apply_relabeling.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_series_transform.cpython-312.pyc,, +pandas/tests/apply/__pycache__/test_str.cpython-312.pyc,, +pandas/tests/apply/common.py,sha256=A8TqjvKR4h4WaLtovGR9hDULpWs4rV-1Jx_Q4Zz5Dew,298 +pandas/tests/apply/test_frame_apply.py,sha256=eJc1NjbUTgYbhVO-CvdfYVRKD7jheGwPQKuigm_bFfM,54550 +pandas/tests/apply/test_frame_apply_relabeling.py,sha256=jHfewakLcFvc1nartXtElv7HM5eGUIelIcm-McXX2KQ,3772 +pandas/tests/apply/test_frame_transform.py,sha256=bbAcYmXxlfEo8-zPQdxlp26s9LPlRbpVKpQu9yEVkCI,8020 +pandas/tests/apply/test_invalid_arg.py,sha256=g3aYkzdTCoqne8AQ03rCF_SPZtQlTVwwYQQySbfDezs,11176 +pandas/tests/apply/test_numba.py,sha256=dD1s13A3ZmU61dlwI9BjwLuiEut0jvDVS3avi4Y6_CA,4190 +pandas/tests/apply/test_series_apply.py,sha256=JlDktd3rqfzbHl5YTEgQOx7t8ptDKPQdw3XSJ3-ToaM,22467 +pandas/tests/apply/test_series_apply_relabeling.py,sha256=_HkoIybNJQFEpIaafHvD1Q0nx_U9J2aL8ualcwhp5Fs,1510 +pandas/tests/apply/test_series_transform.py,sha256=rrJO-C5HagNKJo542h32eB5TOWVDxirJv1u5PXJkh_I,2404 +pandas/tests/apply/test_str.py,sha256=k34l2s3s5p2NUzwUFOtW6sePl9ureo6Q8EaY5PEqy1w,11043 +pandas/tests/arithmetic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arithmetic/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/common.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_array_ops.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_categorical.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_datetime64.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_interval.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_numeric.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_object.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_period.cpython-312.pyc,, +pandas/tests/arithmetic/__pycache__/test_timedelta64.cpython-312.pyc,, +pandas/tests/arithmetic/common.py,sha256=C_s1Zc2_0U_oBciQNt5xJp-8FaLmkscEdmnX2Nq16UY,4362 +pandas/tests/arithmetic/conftest.py,sha256=uUtu5-T5FBdFQAo21vRLQSHPiNEjWkc69UwH6llpnsM,3473 +pandas/tests/arithmetic/test_array_ops.py,sha256=4lmZRZAlbJEnphzzwfcvsO4kEv1LG9l3uCmaF_8kcAA,1064 +pandas/tests/arithmetic/test_categorical.py,sha256=lK5fXv4cRIu69ocvOHfKL5bjeK0jDdW3psvrrssjDoA,742 +pandas/tests/arithmetic/test_datetime64.py,sha256=f97V90PrRZrFZ_IrBxfEtgDXvYI_JGqMsIl__9b0y9E,90255 +pandas/tests/arithmetic/test_interval.py,sha256=2TG1Lh4VZXaxwjs5y5RjXzIukOfoVetyLfPlOo5h4vQ,10951 +pandas/tests/arithmetic/test_numeric.py,sha256=569JY7Pjl453iXP_txrlktVyUyH1CR_3677due2sfwU,55511 +pandas/tests/arithmetic/test_object.py,sha256=gxf8Wb0jTBUdNN5hYF6tOHKbFZIY03EunT97IaKcedg,13416 +pandas/tests/arithmetic/test_period.py,sha256=uxdkrPIpMM7BWUKmwloViCEE1JtOsxkXKCdfxLQ6E1A,59617 +pandas/tests/arithmetic/test_timedelta64.py,sha256=OH0dD4KNrVEf8FlC75MezthgEDohA8dyk3uxwouF8LM,78911 +pandas/tests/arrays/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/__pycache__/masked_shared.cpython-312.pyc,, +pandas/tests/arrays/__pycache__/test_array.cpython-312.pyc,, +pandas/tests/arrays/__pycache__/test_datetimelike.cpython-312.pyc,, +pandas/tests/arrays/__pycache__/test_datetimes.cpython-312.pyc,, +pandas/tests/arrays/__pycache__/test_ndarray_backed.cpython-312.pyc,, +pandas/tests/arrays/__pycache__/test_period.cpython-312.pyc,, +pandas/tests/arrays/__pycache__/test_timedeltas.cpython-312.pyc,, +pandas/tests/arrays/boolean/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/boolean/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_comparison.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_construction.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_function.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_logical.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_ops.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_reduction.cpython-312.pyc,, +pandas/tests/arrays/boolean/__pycache__/test_repr.cpython-312.pyc,, +pandas/tests/arrays/boolean/test_arithmetic.py,sha256=TS1j3roIOe4g_t-fDVUs920UteSfpI7r2LnV04UVAWo,4177 +pandas/tests/arrays/boolean/test_astype.py,sha256=CWuoHBqqPdF9AqIYQ7_dtA87a1QOYlQbaRNKi_WMFIA,1849 +pandas/tests/arrays/boolean/test_comparison.py,sha256=QIX85ffCwMvtzXtLkWePFQkso_mVtIffWpbgy4ykEz0,1976 +pandas/tests/arrays/boolean/test_construction.py,sha256=1KGaMjJ3FTmoisMbEnKUuxAkylVyzTsfuRXZV5UXlIk,12332 +pandas/tests/arrays/boolean/test_function.py,sha256=eAVsu1XUeokLh7Ko0-bDNUQqmVrGAyOvv9vJdWCQj0M,4061 +pandas/tests/arrays/boolean/test_indexing.py,sha256=BorrK8_ZJbN5HWcIX9fCP-BbTCaJsgAGUiza5IwhYr4,361 +pandas/tests/arrays/boolean/test_logical.py,sha256=7kJTl0KbLA7n8dOV0PZtiZ7gPm65Ggc3p0tHOF5i0d0,9335 +pandas/tests/arrays/boolean/test_ops.py,sha256=iM_FRYMtvvdEpMtLUSuBd_Ww5nHr284v2fRxHaydvIM,975 +pandas/tests/arrays/boolean/test_reduction.py,sha256=eBdonU5n9zsbC86AscHCLxF68XqiqhWWyBJV-7YCOdA,2183 +pandas/tests/arrays/boolean/test_repr.py,sha256=RRljPIDi6jDNhUdbjKMc75Mst-wm92l-H6b5Y-lCCJA,437 +pandas/tests/arrays/categorical/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/categorical/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_algos.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_analytics.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_dtypes.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_map.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_missing.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_operators.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_replace.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_repr.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_sorting.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_subclass.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_take.cpython-312.pyc,, +pandas/tests/arrays/categorical/__pycache__/test_warnings.cpython-312.pyc,, +pandas/tests/arrays/categorical/test_algos.py,sha256=SLguZHlE5eyi14kRoMUGpIohPJM7jQqboKlnTvidpg0,2710 +pandas/tests/arrays/categorical/test_analytics.py,sha256=kjyTe4P84YYRH4FjpxHtDRCc6uJgxDMS4PnwgCo_BE8,13486 +pandas/tests/arrays/categorical/test_api.py,sha256=Ivy3G6MW43fLMYwWn9QdE9wXRxLrpF8IFoUpB-TplCc,19879 +pandas/tests/arrays/categorical/test_astype.py,sha256=vJJohcKkMQpZAfFUEstGn8qymbaFSuqwSqxoAZRfjM8,5543 +pandas/tests/arrays/categorical/test_constructors.py,sha256=cJpXJSP9X1aPu8yA8ss8o8Nx-9pCqLCW4hm12ACIsII,30758 +pandas/tests/arrays/categorical/test_dtypes.py,sha256=h1ZhuPvbHp9aFA4doAkmQ96zQW4A5UX6y6Yv2G5QTb8,5523 +pandas/tests/arrays/categorical/test_indexing.py,sha256=u43KuLMFtxe5ZAs0dphmGqpHsygyxtmTHxdGEfoDVQg,12972 +pandas/tests/arrays/categorical/test_map.py,sha256=TO6GY6B2n2dhkcNRQinbvID9eBfwtVnWsT1yexQg00U,5152 +pandas/tests/arrays/categorical/test_missing.py,sha256=5KdSj982_KUkfB8Cg-l7Jcir5I8n7Gz6SbnHnIqmu8A,7814 +pandas/tests/arrays/categorical/test_operators.py,sha256=NDc6FKDGOrGIdvSDpJ9Mq9O-aE0xw-LoI6L-rcrW0cI,15968 +pandas/tests/arrays/categorical/test_replace.py,sha256=I3jiQGmNSQ2i1WTLgVjIKcH-D919sf9EWTOm-hh_emE,4102 +pandas/tests/arrays/categorical/test_repr.py,sha256=fkE2GAi3ZQYjANLCTjuHOVZGB_9WexvwfhsIHSBeJ48,26936 +pandas/tests/arrays/categorical/test_sorting.py,sha256=gEhLklhDxhqf8UDOB17TMKhrabxS5n0evPg9DWSMd5s,5052 +pandas/tests/arrays/categorical/test_subclass.py,sha256=Y4nURd4hFM0Q3aVET1OO-z11pZzzZ0HFfl2s-9OWemw,903 +pandas/tests/arrays/categorical/test_take.py,sha256=O4g_LYDeK0NzHDId5cBBEp1ns_a762NsYHn088ocYzg,3501 +pandas/tests/arrays/categorical/test_warnings.py,sha256=XqvGeAb9lrXP1VdwKSOvbDuytqDuJ5VSDsLKQAa5gIk,682 +pandas/tests/arrays/datetimes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/datetimes/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/datetimes/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/arrays/datetimes/__pycache__/test_cumulative.cpython-312.pyc,, +pandas/tests/arrays/datetimes/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/arrays/datetimes/test_constructors.py,sha256=xZsxdsUxxbk7UCawlCS3_aAkhsuexX0-uf3XQMlvSA8,11050 +pandas/tests/arrays/datetimes/test_cumulative.py,sha256=X_SHtt9n_WzA_C2wPlRJHRS8LUmjNNmr2-XL6AszJd0,1307 +pandas/tests/arrays/datetimes/test_reductions.py,sha256=Cg1qwq8wASnMeOdZ5_wowrILL6e1ZT_j8m-rIOkwrkg,5787 +pandas/tests/arrays/floating/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/floating/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_comparison.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_concat.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_construction.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_contains.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_function.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_repr.cpython-312.pyc,, +pandas/tests/arrays/floating/__pycache__/test_to_numpy.cpython-312.pyc,, +pandas/tests/arrays/floating/conftest.py,sha256=PkAOd0oDvePBtXL-N0MnmEGCmDMP3_Dw-YwpxgNfl-k,1161 +pandas/tests/arrays/floating/test_arithmetic.py,sha256=olBSoRA2mASEezqxvk_pPiGA_BC3W2FHO6iTFTJSw_c,8311 +pandas/tests/arrays/floating/test_astype.py,sha256=EOcBIsfc44V7lUkNFQwqPnHSBtyEj38nhvNOStBbIcc,4337 +pandas/tests/arrays/floating/test_comparison.py,sha256=C-rwNTv5FtUvo3oWB8XNquCOa_XQHf6R9JRYX6JVAG0,2071 +pandas/tests/arrays/floating/test_concat.py,sha256=-RO-pwRRY93FQnOjBLs1fMVf7uBCoEGRkGWPAdX8ltU,573 +pandas/tests/arrays/floating/test_construction.py,sha256=weDvGh2hSfHmVnQ-6Kc5QmAUaGTF9mvEI3qtZSEHHAk,6455 +pandas/tests/arrays/floating/test_contains.py,sha256=oTsN_kyhRi7hHdKRzi9PzwSu2gHiE3EP4FkuR31BZFM,204 +pandas/tests/arrays/floating/test_function.py,sha256=YiXRdFHEU2iAGXwd68kDyfsjBZ8ztoC8fikZU6AnbRE,6403 +pandas/tests/arrays/floating/test_repr.py,sha256=N_BX7NbU8Pljiz2bouWMzrP22xh_6w_8pHePEB2ycVw,1157 +pandas/tests/arrays/floating/test_to_numpy.py,sha256=d0k_2WXrkIu4JOGkIQlzijmgsm7X-XW2XmobaN_3Q_s,4954 +pandas/tests/arrays/integer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/integer/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_comparison.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_concat.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_construction.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_dtypes.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_function.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_reduction.cpython-312.pyc,, +pandas/tests/arrays/integer/__pycache__/test_repr.cpython-312.pyc,, +pandas/tests/arrays/integer/conftest.py,sha256=TejO1KxvoPETsN-ZdefGePhwJ-szaoYanP9AQXHgY18,1555 +pandas/tests/arrays/integer/test_arithmetic.py,sha256=wKrD5HAwhw_2FOx8JvvwJ-a3yM_oDFSS1fveUbvwy5U,10851 +pandas/tests/arrays/integer/test_comparison.py,sha256=jUr8dmk_6FQsTNjDkYsazWnioHis4cLi94noy4txG54,1212 +pandas/tests/arrays/integer/test_concat.py,sha256=TmHNsCxxvp-KDLD5SaTmeEuWJDzUS51Eg04uSWet9Pg,2351 +pandas/tests/arrays/integer/test_construction.py,sha256=jnzOs0w8i4X55JOrtXc0ylMaiBo8mhRl6uwrnEWr_0o,7768 +pandas/tests/arrays/integer/test_dtypes.py,sha256=r8PuGIbhMUwFtnVzZzmkF6An3MVyBqMzBn3j1DsaZRA,9042 +pandas/tests/arrays/integer/test_function.py,sha256=hCqZIrrISPtn_7mlX92wpQNItAF1o-q-g56W93wnyhI,6627 +pandas/tests/arrays/integer/test_indexing.py,sha256=rgwcafGbwJztl_N4CalvAnW6FKfKVNzJcE-RjcXMpR8,498 +pandas/tests/arrays/integer/test_reduction.py,sha256=XOgHPBOTRNaE7sx-py3K6t_52QZ9iMPlYAoesbFp9ZI,4100 +pandas/tests/arrays/integer/test_repr.py,sha256=fLTZusgFHPXO4orpygmHIOG6JQLzYcdbTJHRvvsN0sM,1652 +pandas/tests/arrays/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/interval/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/interval/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/arrays/interval/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/arrays/interval/__pycache__/test_interval.cpython-312.pyc,, +pandas/tests/arrays/interval/__pycache__/test_interval_pyarrow.cpython-312.pyc,, +pandas/tests/arrays/interval/__pycache__/test_overlaps.cpython-312.pyc,, +pandas/tests/arrays/interval/test_astype.py,sha256=8rb7rssqvIoSztzCfFb5pY4oIH_GjDStKrXkC6bnUZk,776 +pandas/tests/arrays/interval/test_formats.py,sha256=AARSRfiyQa0Fu6jCBdhx83yJOXdCWtfs0q0Yd8mMxwg,317 +pandas/tests/arrays/interval/test_interval.py,sha256=cfZXy6J5AtUqwd5HY4m9lxTyu0m0xsZbD9FlcBebuio,8082 +pandas/tests/arrays/interval/test_interval_pyarrow.py,sha256=PkPTrpsrTLL_3Vd17ENP0I3NFE71XpSQi38HG09hXxo,5202 +pandas/tests/arrays/interval/test_overlaps.py,sha256=4QNJBVY5Fb150Rf3lS5a6p_ScHy8U-sAuWTWetbCmVc,3279 +pandas/tests/arrays/masked/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/masked/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/masked/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/arrays/masked/__pycache__/test_arrow_compat.cpython-312.pyc,, +pandas/tests/arrays/masked/__pycache__/test_function.cpython-312.pyc,, +pandas/tests/arrays/masked/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/arrays/masked/test_arithmetic.py,sha256=wchNK8BesRBPSclagK_egl_EG9J4KPCquzL9iRZOK20,8175 +pandas/tests/arrays/masked/test_arrow_compat.py,sha256=ys0egVa9W8J4sadc5unZlFLB1wFZaUn8hkmieG2p77w,7194 +pandas/tests/arrays/masked/test_function.py,sha256=qkFCkI5KNijaX2SurVoilnhtBFbismLBS4SyEybNXZ8,1954 +pandas/tests/arrays/masked/test_indexing.py,sha256=S1NGbMi6k3YAWfsR4gB83tnXQCCHMgqXmy74bnEHWNo,1915 +pandas/tests/arrays/masked_shared.py,sha256=ANp_CU9Hcly9-NBxknm7g-uWxljstTmriq3S8f5kPsM,5194 +pandas/tests/arrays/numpy_/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/numpy_/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/numpy_/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/arrays/numpy_/__pycache__/test_numpy.cpython-312.pyc,, +pandas/tests/arrays/numpy_/test_indexing.py,sha256=-0lB-Mw-gzM4Mpe-SRCj-w4C6QxLfp3BH65U_DVULNY,1452 +pandas/tests/arrays/numpy_/test_numpy.py,sha256=zFHviwBMXyEi2e6b0SLZ0j39goKpUHbYJ_2wQjwygoU,9726 +pandas/tests/arrays/period/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/period/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/period/__pycache__/test_arrow_compat.cpython-312.pyc,, +pandas/tests/arrays/period/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/arrays/period/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/arrays/period/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/arrays/period/test_arrow_compat.py,sha256=YuEM6oIOfRhdFaTFs5X0um9nLqygEkuxIZGl9V-qQcg,3709 +pandas/tests/arrays/period/test_astype.py,sha256=lKLDDqZSdU7s6PyHbrywkaCJnMJ4TKSphRqmno7BcbU,2344 +pandas/tests/arrays/period/test_constructors.py,sha256=C6J0nmKRSK5nyEja7-gZgf5tCZpPA0aZ9lux-z6gHxA,5089 +pandas/tests/arrays/period/test_reductions.py,sha256=gYiheQK3Z0Bwdo-0UaHIyfXGpmL1_UvoMP9FVIpztlM,1050 +pandas/tests/arrays/sparse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/sparse/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_accessor.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_arithmetics.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_array.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_combine_concat.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_dtype.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_libsparse.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/arrays/sparse/__pycache__/test_unary.cpython-312.pyc,, +pandas/tests/arrays/sparse/test_accessor.py,sha256=EReITkC1ib-_36L6gS5UfjWai_Brp8Iaf4w7WObJZjM,9025 +pandas/tests/arrays/sparse/test_arithmetics.py,sha256=TC2Af6gA4OkRIxDTWy_5jmHNIrgsqWGmOVF707wOn8M,20152 +pandas/tests/arrays/sparse/test_array.py,sha256=XdG2ZIuaerlu2QBe-YLIHPNWSKVNsZDAvqYHr_6Wk6Y,17929 +pandas/tests/arrays/sparse/test_astype.py,sha256=MGW-bxHbKeY7FxpAj-FOFO1kd_wNKmqyEld6t_OuomM,4771 +pandas/tests/arrays/sparse/test_combine_concat.py,sha256=3NMQXaRQc7Bxn5HhSHffcUE24GZi_VYflnFLnixOgbs,2651 +pandas/tests/arrays/sparse/test_constructors.py,sha256=N5GJ8SrwVZ4hNGaM_QlALl283EM13nSVbtO8uBRSAwY,10835 +pandas/tests/arrays/sparse/test_dtype.py,sha256=jic-QgdOK0YEZLoiAEh7zOPupJirfpNAKIeIQohuv70,6126 +pandas/tests/arrays/sparse/test_indexing.py,sha256=8INC1paA06XrCp8L63FSllr0OK48pgiKda5sOgrUhf8,10425 +pandas/tests/arrays/sparse/test_libsparse.py,sha256=_hfr36t-jm-QOhI9Gwbd6sQZI5aVWMMixHY-OYOqKuM,19293 +pandas/tests/arrays/sparse/test_reductions.py,sha256=D7R_jhlFtmH8l-tERmhtP1K3KbcAyPuyIy_Y_gVcN6Q,9721 +pandas/tests/arrays/sparse/test_unary.py,sha256=GtqeMdylKdtu-0HPxmTDVjo32riOcEtqPhjI_XK5LkM,2864 +pandas/tests/arrays/string_/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/string_/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/string_/__pycache__/test_concat.cpython-312.pyc,, +pandas/tests/arrays/string_/__pycache__/test_string.cpython-312.pyc,, +pandas/tests/arrays/string_/__pycache__/test_string_arrow.cpython-312.pyc,, +pandas/tests/arrays/string_/test_concat.py,sha256=6mqREqJWdNEPLIR0jfkiLnOFd6KrcBX7fJ7IOJzfQyI,2744 +pandas/tests/arrays/string_/test_string.py,sha256=VOpQV5D4O2odDd9juJEH-DeGSIBajr__5CkJiri0K-E,30734 +pandas/tests/arrays/string_/test_string_arrow.py,sha256=wporKwrDWw0Ur3KovspMUXk4ZFz5nqrzUoFOxx1kwCI,9712 +pandas/tests/arrays/test_array.py,sha256=wq6yX5hk8C0ldqIMyDlXSatUcrseFqTTV-oPhfq8_Fw,17111 +pandas/tests/arrays/test_datetimelike.py,sha256=iFh52iyFbxtY_gntJgf25kQtBkarf1k131-ultxahSY,46254 +pandas/tests/arrays/test_datetimes.py,sha256=FoODE0J_-8KIBbNS5ROkEWVgNnF3PwaToqJ38YtiAYU,29112 +pandas/tests/arrays/test_ndarray_backed.py,sha256=6unFuF9S6hG5FDJDjiqbKg3rL8ItzJQHwY9vMdju4-0,2331 +pandas/tests/arrays/test_period.py,sha256=S_7TMRLEmVamhGKlVO50qJIj3OFDWRzY_oxEcXzp3zs,5572 +pandas/tests/arrays/test_timedeltas.py,sha256=VdMdnCrOL5_oUa4RxL-gaVre6Qp3iu__qNMaUb7kqfE,10673 +pandas/tests/arrays/timedeltas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/arrays/timedeltas/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/arrays/timedeltas/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/arrays/timedeltas/__pycache__/test_cumulative.cpython-312.pyc,, +pandas/tests/arrays/timedeltas/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/arrays/timedeltas/test_constructors.py,sha256=gwBy_iuOc-EEMusjK2bITGQhCyeeI9OzI9uI8xOact0,4248 +pandas/tests/arrays/timedeltas/test_cumulative.py,sha256=cRR6I-lIsefG95vEZb8TuXdvmw7pdPFedpBneLVKBG8,692 +pandas/tests/arrays/timedeltas/test_reductions.py,sha256=cw6I3Bxi0R2_DD2y1WD-AHTYR_ufAtN9ztCtDGypQnM,6520 +pandas/tests/base/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/base/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/base/__pycache__/common.cpython-312.pyc,, +pandas/tests/base/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/base/__pycache__/test_conversion.cpython-312.pyc,, +pandas/tests/base/__pycache__/test_fillna.cpython-312.pyc,, +pandas/tests/base/__pycache__/test_misc.cpython-312.pyc,, +pandas/tests/base/__pycache__/test_transpose.cpython-312.pyc,, +pandas/tests/base/__pycache__/test_unique.cpython-312.pyc,, +pandas/tests/base/__pycache__/test_value_counts.cpython-312.pyc,, +pandas/tests/base/common.py,sha256=-cLXvhzuQi0XMfU-NdqTQAiruN0MU9A9HE2goo7ZzJQ,266 +pandas/tests/base/test_constructors.py,sha256=Xnvv9P9oREkISvOa3jMX015T_TbRZ6ZIYaG98_Wefeg,5763 +pandas/tests/base/test_conversion.py,sha256=I9aqpcshiLrpfnzfEbtz-UWiP7iNZX21ibCYXUH6zUA,19046 +pandas/tests/base/test_fillna.py,sha256=q9LZhUp2HXaVQw4wSxK0VU4Z9z62WI12r9ivsZu0gOg,1522 +pandas/tests/base/test_misc.py,sha256=_HMhb6XwCJCUqTFspIPwzJOa0sE2JOWXE0lxHqH-Dzo,6053 +pandas/tests/base/test_transpose.py,sha256=138_O_JwwdCmfmyjp47PSVa-4Sr7SOuLprr0PzRm6BQ,1694 +pandas/tests/base/test_unique.py,sha256=6pMua_FmjQ3Ue897IaqR4_xFBv50zakcPhiAWrPfFaY,4255 +pandas/tests/base/test_value_counts.py,sha256=Xu2WOPBcQ81SFcvOyNDBpPnJ6gm2epFctyyT3vCUtJc,11804 +pandas/tests/computation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/computation/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/computation/__pycache__/test_compat.cpython-312.pyc,, +pandas/tests/computation/__pycache__/test_eval.cpython-312.pyc,, +pandas/tests/computation/test_compat.py,sha256=dHstyvdaXybrwm1WQndV9aQBwOsOvCIVZb5pxLXsYfM,872 +pandas/tests/computation/test_eval.py,sha256=tStBFWIoMtIJkeXGqDx8sSUbOYPEfunT2NeldU-q-h8,72075 +pandas/tests/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/config/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/config/__pycache__/test_config.cpython-312.pyc,, +pandas/tests/config/__pycache__/test_localization.cpython-312.pyc,, +pandas/tests/config/test_config.py,sha256=T3PKV_lWTp_4ZU566fpWt_N9_tr3BfsxHlJ_vqnQiiQ,15858 +pandas/tests/config/test_localization.py,sha256=xC7SJfih_Kus5WGpSWZdwyAQR3ttgpsxxlNesbwrYfM,4479 +pandas/tests/construction/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/construction/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/construction/__pycache__/test_extract_array.cpython-312.pyc,, +pandas/tests/construction/test_extract_array.py,sha256=L3fEjATPsAy3a6zrdQJaXXaQ7FvR2LOeiPJMjGNkwKQ,637 +pandas/tests/copy_view/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/copy_view/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_array.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_chained_assignment_deprecation.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_clip.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_core_functionalities.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_functions.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_internals.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_interp_fillna.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_methods.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_replace.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_setitem.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/test_util.cpython-312.pyc,, +pandas/tests/copy_view/__pycache__/util.cpython-312.pyc,, +pandas/tests/copy_view/index/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/copy_view/index/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/copy_view/index/__pycache__/test_datetimeindex.cpython-312.pyc,, +pandas/tests/copy_view/index/__pycache__/test_index.cpython-312.pyc,, +pandas/tests/copy_view/index/__pycache__/test_periodindex.cpython-312.pyc,, +pandas/tests/copy_view/index/__pycache__/test_timedeltaindex.cpython-312.pyc,, +pandas/tests/copy_view/index/test_datetimeindex.py,sha256=Sl224XCNK_lx-N6k9heXS_g2_bwmqCJJyKDv7pE_HQw,1980 +pandas/tests/copy_view/index/test_index.py,sha256=B849E4vf72tsWv11NfixJU6vjX0gpMlyvHRKSBk0V1Q,5363 +pandas/tests/copy_view/index/test_periodindex.py,sha256=qSR4PUuAHEPq1o8NUeif_MSrN43rvSeWQtsmTK6I1a4,653 +pandas/tests/copy_view/index/test_timedeltaindex.py,sha256=L1fGDsy2dmZqf_y3bXVo9mUMr1Jsli9BdScChOEQkns,661 +pandas/tests/copy_view/test_array.py,sha256=hj2nbMOBHCsTswQP6sM0jjKawcC0euW99RrSi03Ycz8,6696 +pandas/tests/copy_view/test_astype.py,sha256=7hVPzcq4eGYBwOBiBUhTvGVQNt7lus-bu1wpnrdp0vs,10185 +pandas/tests/copy_view/test_chained_assignment_deprecation.py,sha256=96HPAYslMpB3S7GzRbE34MFhZb_kj56xX_W0UPCTDfE,8310 +pandas/tests/copy_view/test_clip.py,sha256=m6J1WMcpo97TOhU2UuZjJQN5WT10itnEc_SUJVPd0kc,3202 +pandas/tests/copy_view/test_constructors.py,sha256=M_VB1CUUpnuM2iRwnXmLJ1bq8e_ohLEe2sHZ1fDc3Ow,13952 +pandas/tests/copy_view/test_core_functionalities.py,sha256=M-ExonPcx6W-8z_TLTaP16DJtelSVeQHZKO1aWObSuA,3506 +pandas/tests/copy_view/test_functions.py,sha256=0KVw1BKyrP4EAjPt4x270QYQn95vrVAtka1vLqqHHWs,15734 +pandas/tests/copy_view/test_indexing.py,sha256=4OUGrcgMHlai3p7tQt0sXopNYTrGdEFSUaVf6S7ZzyI,42980 +pandas/tests/copy_view/test_internals.py,sha256=3NbWdjQv6CalasyFPwNqKZXJlkCTCop98T9DeYVg5ik,5063 +pandas/tests/copy_view/test_interp_fillna.py,sha256=q_zHprqxVD8GRZTmA8hK6Lcni15-3dYDZHo0GMlkBow,15499 +pandas/tests/copy_view/test_methods.py,sha256=0umze573YtqYKBSMQO13TDZcCCAfS6-anGTQE0RQA5k,72187 +pandas/tests/copy_view/test_replace.py,sha256=ectDMardFNK1PAuQ6gh4ycM2XLm1byBnawS0LUPkcsU,17665 +pandas/tests/copy_view/test_setitem.py,sha256=ewuJiYuD9VI2wuFZiDjGYVP7gnlP4H9uVFnjjelW55U,4822 +pandas/tests/copy_view/test_util.py,sha256=ClWLprMJhf6okUNu9AX6Ar9IXZgKkY0nNuDzHRO70Hk,385 +pandas/tests/copy_view/util.py,sha256=oNtCgxmTmkiM1DiUxjnzTeAxCj_7jjeewtby-3gdoo0,899 +pandas/tests/dtypes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/dtypes/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/dtypes/__pycache__/test_common.cpython-312.pyc,, +pandas/tests/dtypes/__pycache__/test_concat.cpython-312.pyc,, +pandas/tests/dtypes/__pycache__/test_dtypes.cpython-312.pyc,, +pandas/tests/dtypes/__pycache__/test_generic.cpython-312.pyc,, +pandas/tests/dtypes/__pycache__/test_inference.cpython-312.pyc,, +pandas/tests/dtypes/__pycache__/test_missing.cpython-312.pyc,, +pandas/tests/dtypes/cast/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/dtypes/cast/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_can_hold_element.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_construct_from_scalar.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_construct_ndarray.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_construct_object_arr.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_dict_compat.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_downcast.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_find_common_type.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_infer_datetimelike.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_infer_dtype.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_maybe_box_native.cpython-312.pyc,, +pandas/tests/dtypes/cast/__pycache__/test_promote.cpython-312.pyc,, +pandas/tests/dtypes/cast/test_can_hold_element.py,sha256=2zASUgxB7l8ttG2fKjCpIjtt_TQ7j4NJ2L9xFzcyUPU,2408 +pandas/tests/dtypes/cast/test_construct_from_scalar.py,sha256=INdOiQ7MowXLr6ZReCiq0JykUeFvRWocxk3f-ilk9v0,1780 +pandas/tests/dtypes/cast/test_construct_ndarray.py,sha256=D52osZAHEuY2w3GdzH05y9WD_ghLIySgfKaIJpnLZAw,1316 +pandas/tests/dtypes/cast/test_construct_object_arr.py,sha256=eOmUu4q0ihGTbYpCleoCnYtvwh1TBCEZQQjLeJaUMNA,717 +pandas/tests/dtypes/cast/test_dict_compat.py,sha256=qyn7kP5b14MywtqOUL5C-NOvjf2qK4PsXGpCvqmo-4E,476 +pandas/tests/dtypes/cast/test_downcast.py,sha256=CzuywDTWQ3xTi__4Nd36qgcx6mDs2tpYUsVztduVC9s,2778 +pandas/tests/dtypes/cast/test_find_common_type.py,sha256=c__GbgnRawwgqWut8g5Q928en8-_O3oTZEQVbqQ8MrE,5226 +pandas/tests/dtypes/cast/test_infer_datetimelike.py,sha256=6vor_eqEbMKcBLEkfayXzVzwwf5BZcCvQhFZuqhvyKU,603 +pandas/tests/dtypes/cast/test_infer_dtype.py,sha256=WCLts2TG3Zs4V69O2f_HYmuXEkSHPUXVTIuGpVvICuY,6001 +pandas/tests/dtypes/cast/test_maybe_box_native.py,sha256=uEkoLnSVi4kR8-c5FMhpEba7luZum3PeRIrxIdeGeM4,996 +pandas/tests/dtypes/cast/test_promote.py,sha256=B4dgs3EWIm8qKuoQMn6FNaGGf_qAm_EAm4l2X3cHDMM,20755 +pandas/tests/dtypes/test_common.py,sha256=gqjMq5F57R2eGBnN5TmbgDIKTUCQKWOC_26wpnhZnIY,28706 +pandas/tests/dtypes/test_concat.py,sha256=vlsumyKcJ7b8EdJKONU5txCA34zMaoKDvA0KmcuP8XU,1799 +pandas/tests/dtypes/test_dtypes.py,sha256=5rbj-vzUI9XqwUR-qp0SVjmqb9koN6fUas4c63EmDQs,43844 +pandas/tests/dtypes/test_generic.py,sha256=TzUIinbvMdsyxH_y2VYQ2XCYLQXh005qij9LWWF9bDc,4842 +pandas/tests/dtypes/test_inference.py,sha256=xZSBiUB7W5kUvhvWCTuJmNVLrxDLZjBHq-k_8O89Sq0,71478 +pandas/tests/dtypes/test_missing.py,sha256=1hDyVeUbkBtNCj2d_CVrD5qe1WPKPq_vIY-uLFwvH9s,30736 +pandas/tests/extension/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/extension/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/extension/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_arrow.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_categorical.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_common.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_datetime.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_extension.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_interval.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_masked.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_numpy.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_period.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_sparse.cpython-312.pyc,, +pandas/tests/extension/__pycache__/test_string.cpython-312.pyc,, +pandas/tests/extension/array_with_attr/__init__.py,sha256=bXkwWSW6GRX8Xw221iMyaQOQVaWmyuRP3tGhvjXtiV8,149 +pandas/tests/extension/array_with_attr/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/extension/array_with_attr/__pycache__/array.cpython-312.pyc,, +pandas/tests/extension/array_with_attr/__pycache__/test_array_with_attr.cpython-312.pyc,, +pandas/tests/extension/array_with_attr/array.py,sha256=Vo6gYBpAJHAztlq8m3gH-9GqKUkxSOHg2fk6cApHgFE,2496 +pandas/tests/extension/array_with_attr/test_array_with_attr.py,sha256=TuuBA1lCxjVOgWsWM9jhgc-PyGuXzajO3UWWKZEquZA,1373 +pandas/tests/extension/base/__init__.py,sha256=5OjQDaQnbihqkwRdCBAV-eF-QRE8p3V4frJ764P5-jQ,4353 +pandas/tests/extension/base/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/accumulate.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/base.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/casting.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/constructors.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/dim2.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/dtype.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/getitem.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/groupby.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/index.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/interface.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/io.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/methods.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/missing.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/ops.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/printing.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/reduce.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/reshaping.cpython-312.pyc,, +pandas/tests/extension/base/__pycache__/setitem.cpython-312.pyc,, +pandas/tests/extension/base/accumulate.py,sha256=JHnjvzM2WPD93_WXeay6efj1Pr1vso0llfr5RvQFdAI,1501 +pandas/tests/extension/base/base.py,sha256=aSfTPvuvzzQUxEIrGUASWuwcVv6Uw5bvkFXvqjhRV1M,35 +pandas/tests/extension/base/casting.py,sha256=Xn24h5YqBIi9kmucEUQanmk_IzuABNBJVHaXKePKlBE,3077 +pandas/tests/extension/base/constructors.py,sha256=Y2Pny2SrEj7jsCEUN6KRKi_9G2HA7RIfVs5GVf9Nz5w,5609 +pandas/tests/extension/base/dim2.py,sha256=8Ni4nnBW5wxH3e6f0kX1yTDjecmd12sAZdkBt-1tTss,11992 +pandas/tests/extension/base/dtype.py,sha256=4v3RO3H-2xDIPujcTYdjb0AzWpctqALOXUHLHyHBLDg,4006 +pandas/tests/extension/base/getitem.py,sha256=leq9dxp_KexAv7mhexLCWXcIMKNBPOVfhFv6Nuc5PkQ,15673 +pandas/tests/extension/base/groupby.py,sha256=RzyqdEoOsZzSlf_ucjfMnccSq5nGLiYkQgAFlCHdiOk,6455 +pandas/tests/extension/base/index.py,sha256=fD5Jugbt_39nZ1eVjPNdAgoDRuNXTcnZB9lA4w687vM,517 +pandas/tests/extension/base/interface.py,sha256=nOc3RAOPsmAtDCV3C_tPJvXo2pPPlEcmRuuPgW4mQZs,5999 +pandas/tests/extension/base/io.py,sha256=SNvCa6LXo-4V92Bm6A1RZPXwfDdu3hTWLje8_D3Xwo8,1475 +pandas/tests/extension/base/methods.py,sha256=tpIuCnWD3B_wN1zdQivNPmMx00PTH4CM73xuykpH0RU,26742 +pandas/tests/extension/base/missing.py,sha256=D4by9EHLsc32icNeDutH7JdoGyHE8pD0XPM2o7FiGQU,6606 +pandas/tests/extension/base/ops.py,sha256=qEbUnEkLaXxAE6doTqNhMdFQm2pPyys8xefs3gDv6_c,10760 +pandas/tests/extension/base/printing.py,sha256=pVwGn1id_vO_b9nrz3M9Q_Qh9vqDqC0eZHom0_oGr-A,1109 +pandas/tests/extension/base/reduce.py,sha256=IaF6nI-fMTYzG4fNVUoPei_lf9vCHHIf0NnKCssnYlk,5968 +pandas/tests/extension/base/reshaping.py,sha256=Hf8czQWubrTjZrkYTL3FdOh6h97pCQaN5fK49GbRyRA,13931 +pandas/tests/extension/base/setitem.py,sha256=VcSUUuSqnLftzeeaIlBJIeoo841vVenX_FL5JceS91g,15075 +pandas/tests/extension/conftest.py,sha256=nvR8zq82gsIqh5rbOWj7_sOYLgL8J3M0loXw_L-OGag,5061 +pandas/tests/extension/date/__init__.py,sha256=-pIaBe_vmgnM_ok6T_-t-wVHetXtNw30SOMWVWNDqLI,118 +pandas/tests/extension/date/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/extension/date/__pycache__/array.cpython-312.pyc,, +pandas/tests/extension/date/array.py,sha256=da7NoKcUFxS78IIEAsY6kXzL-mOCrV0yyhFWQUN6p8k,5971 +pandas/tests/extension/decimal/__init__.py,sha256=wgvjyfS3v3AHfh3sEfb5C8rSuOyo2satof8ESijM7bw,191 +pandas/tests/extension/decimal/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/extension/decimal/__pycache__/array.cpython-312.pyc,, +pandas/tests/extension/decimal/__pycache__/test_decimal.cpython-312.pyc,, +pandas/tests/extension/decimal/array.py,sha256=8YbmByqfIzEXW9i3-Ct6VM6M0QkmEEB9CQp79udfmYw,9694 +pandas/tests/extension/decimal/test_decimal.py,sha256=lUadF6G3hW23w9wTCQRX9dOmInb9VxsmIqQlpbMl6Ss,20248 +pandas/tests/extension/json/__init__.py,sha256=JvjCnVMfzIUSoHKL-umrkT9H5T8J3Alt8-QoKXMSB4I,146 +pandas/tests/extension/json/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/extension/json/__pycache__/array.cpython-312.pyc,, +pandas/tests/extension/json/__pycache__/test_json.cpython-312.pyc,, +pandas/tests/extension/json/array.py,sha256=fUQ6NaWW8JRQo9zAyNRJXoF1sNlI34qO3vLlj1JXDh4,9091 +pandas/tests/extension/json/test_json.py,sha256=usY52SN9Yd8lUugiCxI1B7DB06l2Lc8mr9tbxu9iOgI,17951 +pandas/tests/extension/list/__init__.py,sha256=FlpTrgdAMl_5puN2zDjvdmosw8aTvaCD-Hi2GtIK-k0,146 +pandas/tests/extension/list/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/extension/list/__pycache__/array.cpython-312.pyc,, +pandas/tests/extension/list/__pycache__/test_list.cpython-312.pyc,, +pandas/tests/extension/list/array.py,sha256=ngSHFQPRfmOkDOo54sX-l5JjQvr7ZTE9OzS9aPicc3o,4001 +pandas/tests/extension/list/test_list.py,sha256=VFPo5wGu-UvtAOFx3hoxILmRdI9kTOxCIIJM4fqgRBk,671 +pandas/tests/extension/test_arrow.py,sha256=zQxfCpeVhBM9T_i7SFayErr3FlgAAnar8HLhhtkdNjU,117806 +pandas/tests/extension/test_categorical.py,sha256=fI9ImT4bywW5oD6Vi9ZLuruQRB35s-u_eYQNxaVtpMU,6812 +pandas/tests/extension/test_common.py,sha256=4LO2slr0E0zODDK_Es4g9bPBH1U77nI8x9O1Mdddn1U,2975 +pandas/tests/extension/test_datetime.py,sha256=eBTSFWcQp2M1TgYzr01F-KQrdCJLHPrcPMGvuCsIj1s,4614 +pandas/tests/extension/test_extension.py,sha256=eyLZa4imT1Qdd7PCbDX9l0EtDu39T80eCrSre2wmTuE,559 +pandas/tests/extension/test_interval.py,sha256=lZveoqOqya76Cv77vWgCa0GZGAnJDKDgMYd7TqSjHuU,3585 +pandas/tests/extension/test_masked.py,sha256=jrBlSzzwlXMAYj3fYXzDhiOKwUW7WBzyHLp-ce4VDf8,14338 +pandas/tests/extension/test_numpy.py,sha256=eFM6D2CiLgrsmwN5KQm_kYrzIdG7lmFXUuUiNoFrelE,15586 +pandas/tests/extension/test_period.py,sha256=e3RIO2xBPhF-PxPZtPM8VkVhkjYdUNtch9vcoRpHuEE,3528 +pandas/tests/extension/test_sparse.py,sha256=HIUEftSLmtr-LV7xrkP99vKwNj2zyXv4z1Ij_LWJd7Q,18011 +pandas/tests/extension/test_string.py,sha256=gckWLFNn288M1ynMCawmzkLNdhJAFDrj5bmgZdV7pQ8,10085 +pandas/tests/frame/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/frame/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/frame/__pycache__/common.cpython-312.pyc,, +pandas/tests/frame/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_alter_axes.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_arrow_interface.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_block_internals.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_cumulative.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_iteration.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_logical_ops.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_nonunique_indexes.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_npfuncs.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_query_eval.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_repr.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_stack_unstack.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_subclass.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_ufunc.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_unary.cpython-312.pyc,, +pandas/tests/frame/__pycache__/test_validate.cpython-312.pyc,, +pandas/tests/frame/common.py,sha256=BmnEMlREF7G0B5zdaJRsdzqIRdh8diiTisBbCVI6Fp0,1873 +pandas/tests/frame/conftest.py,sha256=rQK_RlKuX3bRr3vv1b05oFili-zJwp0nkBpDXEwl8tE,2616 +pandas/tests/frame/constructors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/frame/constructors/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/frame/constructors/__pycache__/test_from_dict.cpython-312.pyc,, +pandas/tests/frame/constructors/__pycache__/test_from_records.cpython-312.pyc,, +pandas/tests/frame/constructors/test_from_dict.py,sha256=VwZZNOdlTbHQTO4vSUV-s58Bfx2XbsutVd0irNEmhfg,7988 +pandas/tests/frame/constructors/test_from_records.py,sha256=znxVRge8A7XXfbCpQNxiJ5zg4u7HmEKbqcZ8TSAARE8,18570 +pandas/tests/frame/indexing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/frame/indexing/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_coercion.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_delitem.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_get.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_get_value.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_getitem.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_insert.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_mask.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_set_value.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_setitem.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_take.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_where.cpython-312.pyc,, +pandas/tests/frame/indexing/__pycache__/test_xs.cpython-312.pyc,, +pandas/tests/frame/indexing/test_coercion.py,sha256=Xnkwt00jaSc-IxtWgnOl5VcDNRskp80l_WZ_T70QVsw,6099 +pandas/tests/frame/indexing/test_delitem.py,sha256=-YERBfZbhTZ3eKzjmWln8AjoQEO7Yvae6elau4njhM0,1832 +pandas/tests/frame/indexing/test_get.py,sha256=N00_igU25_HjYuvAqDQKqBpqbz6HjB97o9Exvbo9BzM,662 +pandas/tests/frame/indexing/test_get_value.py,sha256=A-GbCHlbDfVPGB10dNGnGg4DtrKrlRbRspYfuDTUmPM,679 +pandas/tests/frame/indexing/test_getitem.py,sha256=9xogr1RzStjgP4HvWm_tm9VWUol660FgSmBwN-wC5Tw,15002 +pandas/tests/frame/indexing/test_indexing.py,sha256=N49g7u38mBgjbVzqzUPguQy4pq-20Iz51xzg_ordj1Y,70655 +pandas/tests/frame/indexing/test_insert.py,sha256=0XsNprKi0XQ9od6dOImwzQwh8YMdgdE0BZFGFHGPEYg,4074 +pandas/tests/frame/indexing/test_mask.py,sha256=1Bql-TBfyBDmlXkECYXk-ZH_y4SPSOZYjCR2Ex7Km1k,4862 +pandas/tests/frame/indexing/test_set_value.py,sha256=2KXYrfi3Pv5zY9j6-Pi9U3q5D0V-_bmGjY-YdeUKmzU,2619 +pandas/tests/frame/indexing/test_setitem.py,sha256=d5r0wINgz274BQTXvQmnC3S3qApCdqZs-3xwXLZOR2Y,55600 +pandas/tests/frame/indexing/test_take.py,sha256=SMBM5BO7ybxTq8gTAX1Qg1UW8vcNiRrHTQwrt1f-Rig,3230 +pandas/tests/frame/indexing/test_where.py,sha256=ZOagnNPqIb2LBr1aNtvzMrx5l7FpJgt-kCZmO9StkWE,38119 +pandas/tests/frame/indexing/test_xs.py,sha256=JGsbJ3zBQYauZyDpSCfrXmRUO4pnH-BIfwODX3qAToM,16012 +pandas/tests/frame/methods/__init__.py,sha256=M6dCS5d750Fzf9GX7xyNka-SZ2wJFCL66y5j-moHhwo,229 +pandas/tests/frame/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_add_prefix_suffix.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_align.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_asfreq.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_asof.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_assign.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_at_time.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_between_time.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_clip.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_combine.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_combine_first.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_compare.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_convert_dtypes.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_copy.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_count.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_cov_corr.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_describe.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_diff.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_dot.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_drop.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_drop_duplicates.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_droplevel.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_dropna.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_dtypes.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_duplicated.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_equals.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_explode.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_fillna.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_filter.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_first_and_last.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_first_valid_index.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_get_numeric_data.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_head_tail.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_infer_objects.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_info.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_interpolate.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_is_homogeneous_dtype.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_isetitem.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_isin.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_iterrows.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_map.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_matmul.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_nlargest.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_pct_change.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_pipe.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_pop.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_quantile.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_rank.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_reindex.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_reindex_like.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_rename.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_rename_axis.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_reorder_levels.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_replace.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_reset_index.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_round.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_sample.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_select_dtypes.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_set_axis.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_set_index.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_shift.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_size.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_sort_index.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_sort_values.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_swapaxes.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_swaplevel.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_csv.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_dict.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_dict_of_blocks.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_numpy.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_period.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_records.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_to_timestamp.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_transpose.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_truncate.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_tz_convert.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_tz_localize.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_update.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_value_counts.cpython-312.pyc,, +pandas/tests/frame/methods/__pycache__/test_values.cpython-312.pyc,, +pandas/tests/frame/methods/test_add_prefix_suffix.py,sha256=iPfzSPx0CArx79na7xcI9ZcPTAwq73IdOCcREVO7k4E,1910 +pandas/tests/frame/methods/test_align.py,sha256=FwQrqdCesXbgkQ8bfYPlf3LfK-Sdvud9pHEC2tCnwQ0,17941 +pandas/tests/frame/methods/test_asfreq.py,sha256=MCJkjukZtOVCauc4FZDbor1h99AvG4eMNfQZW8L1h5c,9341 +pandas/tests/frame/methods/test_asof.py,sha256=bkK2i5xcGvz2oy1MVbf_C1oVixMy_1qYqYcuOg-K2Bk,6732 +pandas/tests/frame/methods/test_assign.py,sha256=xFGREzLhP1wj3MowBimeYbMWBNiII0280DiOXI6WDB0,2982 +pandas/tests/frame/methods/test_astype.py,sha256=GD440ClICMt6ruk5u5TZpkXa2g0-0Cm_QpaHDtUvnyQ,32711 +pandas/tests/frame/methods/test_at_time.py,sha256=JrQYFlNIIyW1xDvgmGE7zRfjXnmKMELh9Stiw0btGbM,4708 +pandas/tests/frame/methods/test_between_time.py,sha256=rD-k1a4LVOa-nMlLXOaZO7iTa3hL_C9tghqt8DWW0Qs,8083 +pandas/tests/frame/methods/test_clip.py,sha256=6h1zwE0SKP-uknyuE5Pi5X9vTS4L5ZBts_iSbs6cSL8,7554 +pandas/tests/frame/methods/test_combine.py,sha256=wNaQqokqHsJmrZ9NQIao58ZT0hSkkTH14I7_Oq8tADs,1359 +pandas/tests/frame/methods/test_combine_first.py,sha256=K0YQAGhGyaK_j5tmP9IbQx8zO56ID9GhbTaT9v-3T1M,19726 +pandas/tests/frame/methods/test_compare.py,sha256=j7Z_-yBVts4-xl1fVsJtOBAXYbLao2hwzI2x3aniFz0,9615 +pandas/tests/frame/methods/test_convert_dtypes.py,sha256=7ccB9iWgl-85QwiG6I405oIKV4wzgfu-AgfnY6ovCfM,7848 +pandas/tests/frame/methods/test_copy.py,sha256=QeDoh44tS__y9LK7LwUBAc-SD5RS-phPA4eYWPl5yIg,1873 +pandas/tests/frame/methods/test_count.py,sha256=avzIu1dZ3pls4SM6g173M7Q4i8zMUzeAVI2EeIzWC0c,1083 +pandas/tests/frame/methods/test_cov_corr.py,sha256=5LkNXu8gJKOvAiMRelx4pZ_awWPh4Ovk_uN9_p6IBMw,17875 +pandas/tests/frame/methods/test_describe.py,sha256=DAY04ar1XixwEscl6taSddki4Y_rYnQnV8zF61-z1ZY,14500 +pandas/tests/frame/methods/test_diff.py,sha256=Dyz4lYFWrLVm5fN_B0Z1xZ_l8gyGFQhzwhmRKMuA6io,10099 +pandas/tests/frame/methods/test_dot.py,sha256=tfZD1HWlbO78DEgdjpBctgjWHtzjC3K9essVl_5XBMA,4623 +pandas/tests/frame/methods/test_drop.py,sha256=41RTmD-suQbCnZjpFcG56VlIx1ZP-ReC-j5YIhpJ3WA,20362 +pandas/tests/frame/methods/test_drop_duplicates.py,sha256=GSJ7VundpGtt6KBhl2mld6CwNc9La_pGRwXuNNiRE9Y,14503 +pandas/tests/frame/methods/test_droplevel.py,sha256=L1gAMjYYPB6eYmSppXfbwPVKa3HCNofqPVUZ3gxLldA,1253 +pandas/tests/frame/methods/test_dropna.py,sha256=9l8GBOLpvmEowzFaq0kRxN3815gJCuNamX4S5dn5Mmw,10315 +pandas/tests/frame/methods/test_dtypes.py,sha256=gDIoveWMjhLegq7RQ2ATkQIDOXDfv3WdDDxBBxF4pLo,5001 +pandas/tests/frame/methods/test_duplicated.py,sha256=1DQFuK4KjfSpsl8W0jXne8PPUsL1nFe3lI_9VYBd33I,3305 +pandas/tests/frame/methods/test_equals.py,sha256=AFmbc9SmfgpQV0PD9hCXuktRCRkNvDF5S1Z7z31E2xE,2996 +pandas/tests/frame/methods/test_explode.py,sha256=oR9-X7VyRM0vZr7PxrKK1iRHwgQUpgoEfBt9fZ8JvSY,9058 +pandas/tests/frame/methods/test_fillna.py,sha256=0hAKOAraIYDLk5lmx9o3ronl2SQk5LnuAaPrkC4qEYI,33417 +pandas/tests/frame/methods/test_filter.py,sha256=oT63-WLaQv3isFsWJFtqZwxiw2J-7xZwyOOxpn-kTNo,5422 +pandas/tests/frame/methods/test_first_and_last.py,sha256=hKvLBnx3YtQLilE_9PlL9804dAI6E7Hk2gHDgXqbcsU,5349 +pandas/tests/frame/methods/test_first_valid_index.py,sha256=DRoZKic0mpCom31NeygnBftZlxc6wsCT4-DN2KV5wWI,2574 +pandas/tests/frame/methods/test_get_numeric_data.py,sha256=0bvZ2Bpa8zaWcrzNd6WRKD1e9IesDhaBASP-vR_Zauw,3368 +pandas/tests/frame/methods/test_head_tail.py,sha256=quuFkpS5IgonJDSb9_Po4eO3Wi5wlcNKq723EMYL6Ns,1935 +pandas/tests/frame/methods/test_infer_objects.py,sha256=LNOf2VJsV17FDT9ogEDba6la414yUmm5z_7B97nLN24,1241 +pandas/tests/frame/methods/test_info.py,sha256=XA4WDItjVnOjnGfQsHloK5YDaGygi45fzhkgMLsFFZA,17923 +pandas/tests/frame/methods/test_interpolate.py,sha256=UnPUFiOlPSkxtImncHswjJXOyNR8tsITRfr3EDhpJm4,20409 +pandas/tests/frame/methods/test_is_homogeneous_dtype.py,sha256=8Ndf_2Z07SAqrN0ookvH0PDAmECGVJkUieeqSaz2aRQ,1455 +pandas/tests/frame/methods/test_isetitem.py,sha256=VoxA-yXow_CRikJ1tlni1PsAAOT1D2X8PtTZyJOGQXU,1428 +pandas/tests/frame/methods/test_isin.py,sha256=P2TVUsL_p366aSxwWcq27VlT9zFstOXlsJSTFlw2n20,7599 +pandas/tests/frame/methods/test_iterrows.py,sha256=hfFRA20tRYmXJAoJZLGI04J131Z7QaaEbINm3FwfVbQ,338 +pandas/tests/frame/methods/test_join.py,sha256=oGHrJh9Gb6k8Cgg1iHNVoJuamkIHqnzs5EoU_XdY9hM,17523 +pandas/tests/frame/methods/test_map.py,sha256=UIY-wd0ozerUNyILMavuJ47qdWwp8dREjeKeeR8zvc8,5994 +pandas/tests/frame/methods/test_matmul.py,sha256=i1BG41S9da2R0nATvc3kZXsiwl5t6MHDFIb0IJ4lAbQ,3137 +pandas/tests/frame/methods/test_nlargest.py,sha256=xqBTJTJHni34Qkgn2YlBUvOngOQNRw4MCGtGXFp4G3M,8192 +pandas/tests/frame/methods/test_pct_change.py,sha256=s0Ho617mHdRHBEV-9cRAz3_Z_Q5BzTd_cd6MuobTlbo,6530 +pandas/tests/frame/methods/test_pipe.py,sha256=ts5ghk8g6PYXKpdsBdovBXxPGO2qq75FEVzBgjAVfRw,1023 +pandas/tests/frame/methods/test_pop.py,sha256=e0CBRelgiASCGdB1NFRMSr04BbaggjyHAZYvmUUh1sM,2223 +pandas/tests/frame/methods/test_quantile.py,sha256=Xod3zoRCKr4D6CYEd6I4HC6q3ERz3vYlwf1D3OvlnGM,36591 +pandas/tests/frame/methods/test_rank.py,sha256=fivZJ_OZxlHb-9VD5PANTxkJbeq1ajZbA9li5sKbGmk,17548 +pandas/tests/frame/methods/test_reindex.py,sha256=tmNvHk4dcGnrZ81EA5UGtPq6LdSa0Y64yQ5MzIZoKP8,48343 +pandas/tests/frame/methods/test_reindex_like.py,sha256=2qgqaHDSEKYO1hwE9MaPTFJhl4m7rejHyuOcrmvqaBg,1187 +pandas/tests/frame/methods/test_rename.py,sha256=P-SIwbh-n6QdPqFns4ebPtGFwdXd7vmeWt5_dwo0Kq4,15354 +pandas/tests/frame/methods/test_rename_axis.py,sha256=90QFtDi0p-8bxEdFfLs75EtJQtJEOTmCdXoiS7h9F-Y,4091 +pandas/tests/frame/methods/test_reorder_levels.py,sha256=VJVEdltyRoz89mQR1Xp0A9yKlTeEFIpsPaKWQujT-C8,2729 +pandas/tests/frame/methods/test_replace.py,sha256=VbZowu325vh80eg6T-1c_m5ns_p8aZRbUdy1qrjZMwA,62755 +pandas/tests/frame/methods/test_reset_index.py,sha256=WRm-L0WeMvJ9zLh000m-4mz4lhp1SbrLgN6rQf__t1k,29156 +pandas/tests/frame/methods/test_round.py,sha256=dcPlBxHqpKJ6JTBJskvw2CE3IYfa-Xt020jfSslwLjs,7978 +pandas/tests/frame/methods/test_sample.py,sha256=vPDSUU6oBD5X2C5rKUhIHk6o2xftm0zzMTwvuipelRM,13431 +pandas/tests/frame/methods/test_select_dtypes.py,sha256=XkJjUP9hSdsOKvMJUdsoUJKk8rJh2boknHibajJS5xg,18181 +pandas/tests/frame/methods/test_set_axis.py,sha256=xiyZyjgDIO0B5HWGLeV_fVDyXj3YMDBfLyEDh5rQvcw,4608 +pandas/tests/frame/methods/test_set_index.py,sha256=DNZMKbX0xDqAbf9wzQKwHlR7mdBO7a1ECSAuXUo5CEQ,26570 +pandas/tests/frame/methods/test_shift.py,sha256=unBlSwoV0OwFfysSr8ZKrqrrfoH7FRbPlGp18XW84OQ,27731 +pandas/tests/frame/methods/test_size.py,sha256=zFzVSvOpjHkA9_tEB2mPnfq9PJIBuBa4lCi6BvXbBDE,571 +pandas/tests/frame/methods/test_sort_index.py,sha256=BbCjfh_Zke1R7M9fPoRASORNfXS2KZ0IgWOF6jNnor0,34826 +pandas/tests/frame/methods/test_sort_values.py,sha256=NTmGhvm_flc6gzdtOeAOXsO3ai6K3peyH476Sj-qfLA,32982 +pandas/tests/frame/methods/test_swapaxes.py,sha256=-IuPIvjEz7X8-qxnWy1no5hG2WklPn6qERkmQQ-gAv0,1466 +pandas/tests/frame/methods/test_swaplevel.py,sha256=Y8npUpIQM0lSdIwY7auGcLJaF21JOb-KlVU3cvSLsOg,1277 +pandas/tests/frame/methods/test_to_csv.py,sha256=ph8z03KVeulvnYXX0vEHVZ2i4dY38oU6aMlw6xeUT8M,51560 +pandas/tests/frame/methods/test_to_dict.py,sha256=BEKNs7rUFnd_cZZ7wQz0AmKJ7U-7KsEI6V3eApb1chw,18640 +pandas/tests/frame/methods/test_to_dict_of_blocks.py,sha256=gbiXpvTckh8rspweNjNng1oDalTnbfV487tQ_0BdJU0,2641 +pandas/tests/frame/methods/test_to_numpy.py,sha256=axcJ87gIlMRd2HER_tBgm-Y3mwM4n4pRIHNCQ8jwk-c,1914 +pandas/tests/frame/methods/test_to_period.py,sha256=Xiebi3IA_vUKrFNftLBkhF4N0gMbpI76ZCQpqhgO4iU,2863 +pandas/tests/frame/methods/test_to_records.py,sha256=35K3btxiApCcRVPG429FZAqqXIKRHKx4bVc8Sg3DCmE,18553 +pandas/tests/frame/methods/test_to_timestamp.py,sha256=1j6yjp4_WlxcDXSBKOk-IfrEbWtC4HvbIIHeM2x25ys,5866 +pandas/tests/frame/methods/test_transpose.py,sha256=JNhwvci37DlDMYHBaJz4Km998vw8NGfl7f4UYwwnsmM,6830 +pandas/tests/frame/methods/test_truncate.py,sha256=ZTnK8yZYqEhG3pe8KVwmJf4K890RMu8a60A4nC_qznM,5216 +pandas/tests/frame/methods/test_tz_convert.py,sha256=vsJm9M19ciCPqG0t5d_BlxuCmDphDkgb75SuYPtOhmE,4707 +pandas/tests/frame/methods/test_tz_localize.py,sha256=rMvd0K3W7N24qn7Q_tTkvbz7dOemIv3w89hthc6c5Y0,2084 +pandas/tests/frame/methods/test_update.py,sha256=piYdB_B4VhkigQqLFiWJzNV4Geyiml1gJokdMNF36sM,6888 +pandas/tests/frame/methods/test_value_counts.py,sha256=YpYs0AZ8YgJE75W84O1KMfhd5oqpiuIJvLjz_YIz2KE,5556 +pandas/tests/frame/methods/test_values.py,sha256=ASljAwM9CEBMX6bA3FqWoSv4sOcRjuz8ZTfLSjo_F6Y,9406 +pandas/tests/frame/test_alter_axes.py,sha256=yHyCho1zs84UETsGGtw-gf3eTIyPj9zYUUA7wHTdRVk,873 +pandas/tests/frame/test_api.py,sha256=e6ABLjgP8f-1XVZlDVDn3cDU1nOelOTIx4fSublI6ac,12454 +pandas/tests/frame/test_arithmetic.py,sha256=9ZF2pr9Df5N3JNGKlgQ_HABoUD2Q1SajydyhzhFmD3U,73489 +pandas/tests/frame/test_arrow_interface.py,sha256=Ze1AfIL3VcJ6bnoyyUvNff-mkaZq3RFysoi7M1I1hTU,1505 +pandas/tests/frame/test_block_internals.py,sha256=wcnPGvD6dZ9vVBVSgb8yY5T858Epqvmm9oHh_XC8cX4,16228 +pandas/tests/frame/test_constructors.py,sha256=m6Pb0rFZw1sLrZXGuMVL8rqNqDr6AH-TDymJiOoi2RU,124866 +pandas/tests/frame/test_cumulative.py,sha256=Ku20LYWW1hrycH8gslF8oNwXMv88RmaJC7x0a5GPbYw,2389 +pandas/tests/frame/test_iteration.py,sha256=BuyW6QePxoNZl-Cgxp5WLah_e-kSK2hsN8Gud_g0aoc,5077 +pandas/tests/frame/test_logical_ops.py,sha256=zqJcMKCJhzWC2ZCa7RLc_bS7Plw5uS3foyoEXjHLgAg,7305 +pandas/tests/frame/test_nonunique_indexes.py,sha256=wtBZpClv_46EwBSk59H1iXay2SR6Wv7m4ajh0tjisJg,11937 +pandas/tests/frame/test_npfuncs.py,sha256=DRLl7MSP7e5vRrVs3FgOooI4pZNmECurbVqkAAqvlUI,2751 +pandas/tests/frame/test_query_eval.py,sha256=Tkrwx7qKLqJIJq_uPxG2YDRfH3wQFZ6kobStZS0knPI,55314 +pandas/tests/frame/test_reductions.py,sha256=Una20S8mvVGHlNtxsG2Vu-E0YspgrDgsi4g1x2BKGnw,76542 +pandas/tests/frame/test_repr.py,sha256=TZgR3zpUAumCTltt-pbI1Ha2Zdaox38a4g3T9yuMfwA,16818 +pandas/tests/frame/test_stack_unstack.py,sha256=Mgn_NzEdU7qMzqWcfmx_4FeaPrEMGF_2sRWxXoWaoUk,97558 +pandas/tests/frame/test_subclass.py,sha256=ESRHM3XZ5Wu5oInFbnVXjjJv9eWRYGwa6kcyvcJ8dto,28093 +pandas/tests/frame/test_ufunc.py,sha256=YcUXnFE2n7lO5XN9aUvOJfeJyGqIDui0VhH-H1gUf1I,10554 +pandas/tests/frame/test_unary.py,sha256=4MEWi-fkt8iv8WEDvSP05Lamo1HiyzE8IIPfWpFb1nA,6287 +pandas/tests/frame/test_validate.py,sha256=hSQAfdZOKBe2MnbTBgWULmtA459zctixj7Qjy6bRg20,1094 +pandas/tests/generic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/generic/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/generic/__pycache__/test_duplicate_labels.cpython-312.pyc,, +pandas/tests/generic/__pycache__/test_finalize.cpython-312.pyc,, +pandas/tests/generic/__pycache__/test_frame.cpython-312.pyc,, +pandas/tests/generic/__pycache__/test_generic.cpython-312.pyc,, +pandas/tests/generic/__pycache__/test_label_or_level_utils.cpython-312.pyc,, +pandas/tests/generic/__pycache__/test_series.cpython-312.pyc,, +pandas/tests/generic/__pycache__/test_to_xarray.cpython-312.pyc,, +pandas/tests/generic/test_duplicate_labels.py,sha256=-t-hhIiI3E1Byv1-jjvXDRAS8_tJzZaOIf-EsK6hrXg,14506 +pandas/tests/generic/test_finalize.py,sha256=HWv668IFuaSNElG3g1J5DL-wMHpU5T_iQYTOkaJA80U,28852 +pandas/tests/generic/test_frame.py,sha256=h6r5f3L-_V4JV5pP0AoFyvjtJP1ng7DJplN6Rrx4gzI,7332 +pandas/tests/generic/test_generic.py,sha256=MUhx9EVhCuo-fTOYRH2nzhQH8ip9-5QaNMjEPWx-NI4,17447 +pandas/tests/generic/test_label_or_level_utils.py,sha256=PhsVWjYjOHPZRqX4mwUc7jlOH3tnd7p9pkMFh87CtKU,10244 +pandas/tests/generic/test_series.py,sha256=oyFxVdh9G2GCBiTQktXNuafAw0wrbXs6Af8UnwUUiow,5677 +pandas/tests/generic/test_to_xarray.py,sha256=jSkLcl5jcZRZm3M2c6Iyv8hoT_YzcrEbgu2LuZ7SRqc,4782 +pandas/tests/groupby/__init__.py,sha256=O41hwVGLyFtIhv-zbe2JBZiqD3heGA7LOk10RuxfcKc,659 +pandas/tests/groupby/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_all_methods.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_apply.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_apply_mutate.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_bin_groupby.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_categorical.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_counting.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_cumulative.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_filters.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_groupby.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_groupby_dropna.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_groupby_subclass.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_grouping.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_index_as_string.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_libgroupby.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_missing.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_numba.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_numeric_only.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_pipe.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_raises.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/groupby/__pycache__/test_timegrouper.cpython-312.pyc,, +pandas/tests/groupby/aggregate/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/groupby/aggregate/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_aggregate.cpython-312.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_cython.cpython-312.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_numba.cpython-312.pyc,, +pandas/tests/groupby/aggregate/__pycache__/test_other.cpython-312.pyc,, +pandas/tests/groupby/aggregate/test_aggregate.py,sha256=cRJLOfa-LPIyg33d19mfF3o9N1skMym9Tt6TZQanttM,55550 +pandas/tests/groupby/aggregate/test_cython.py,sha256=CaKQJHZvqIlhxyQzvrDpE2QUX_NMnWB86MIM57jy8aI,12866 +pandas/tests/groupby/aggregate/test_numba.py,sha256=vAaSk-oXue7xqZgmnYJxsg2nmFeyo9d-12m0oi-j1A0,13366 +pandas/tests/groupby/aggregate/test_other.py,sha256=oiP7HVIV27eBNIshYC8JTENGUWg2kCBd5dnki4u32YE,20708 +pandas/tests/groupby/conftest.py,sha256=uxnebcMXbaC_tH4Pg2wRZvXlWMZ_WnNIUeX8ftK7gWo,4785 +pandas/tests/groupby/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/groupby/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_corrwith.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_describe.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_groupby_shift_diff.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_is_monotonic.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_nlargest_nsmallest.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_nth.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_quantile.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_rank.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_sample.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_size.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_skew.cpython-312.pyc,, +pandas/tests/groupby/methods/__pycache__/test_value_counts.cpython-312.pyc,, +pandas/tests/groupby/methods/test_corrwith.py,sha256=nseP6eDkLjiNIOSxm2EDFTkemTqNFUNqvvNJpMiNZVY,615 +pandas/tests/groupby/methods/test_describe.py,sha256=QTB1arYxilSCU75763T4aIwz91X6zmq1rARtQJZc8k0,9884 +pandas/tests/groupby/methods/test_groupby_shift_diff.py,sha256=4XMAhqV0JrGeXQn1_07ec9Nu25Dy1LOcDfojo4qEhNI,7925 +pandas/tests/groupby/methods/test_is_monotonic.py,sha256=OpnlOamR5gX1S7MVtZFGxnbt1Fem_wWH1Irc5aqkdq4,2566 +pandas/tests/groupby/methods/test_nlargest_nsmallest.py,sha256=MFS6cWChs3aBw3vb-n234pOV8_YYet2jOdDNN0lrMkg,3401 +pandas/tests/groupby/methods/test_nth.py,sha256=uk9H3hZiNlusb668TxiIXCoB0v9J2-w0tv-pyytRWEc,28225 +pandas/tests/groupby/methods/test_quantile.py,sha256=Sb6khJ8w4BM7s91CETO5jDI56d8YShzJyi8xsNfZ_Ng,16372 +pandas/tests/groupby/methods/test_rank.py,sha256=NE_ciV_TwLbTGoq1OFUFX5yadyiYoP3m5ppVOoD5264,24263 +pandas/tests/groupby/methods/test_sample.py,sha256=n_dLYblQo9MWnpngMRIIGLZFGEGOeAfEqsL9c9gLCKg,5155 +pandas/tests/groupby/methods/test_size.py,sha256=0ngo1qbGS47ItFlAnLXhU6778J7bVwV1uIjUiDjYN0A,4138 +pandas/tests/groupby/methods/test_skew.py,sha256=_FTlnXtE_fic6ZZ322S583IXUY5hEQggi-3Xbuboahw,841 +pandas/tests/groupby/methods/test_value_counts.py,sha256=D7AlJkbUdXv7i21-7wBxPY6ZaBJFMx1yzWVTs9_ipSg,40439 +pandas/tests/groupby/test_all_methods.py,sha256=eQsLKoyDyGZNPecbxC1HRzdIwW_DBEp0x_r3gD620pw,3077 +pandas/tests/groupby/test_api.py,sha256=IpMVl4g9F2317jWVTSiHoAsZKaOQWFx0Oi_jLWfv_DQ,8481 +pandas/tests/groupby/test_apply.py,sha256=BdpB3VlgEAPr7ri_kFsZfSaZGZIGuXTRjsR5js4uNa0,54516 +pandas/tests/groupby/test_apply_mutate.py,sha256=l8KQ2vAP7VmZ4NZ8Orp1Ro_KC0pzb9VRlgwYLl3K-fI,5012 +pandas/tests/groupby/test_bin_groupby.py,sha256=nZGe01NsuZmS88cMqq8fGFbKl-umvmWjXd8BGmR3jTo,1769 +pandas/tests/groupby/test_categorical.py,sha256=2cbx778NTsWjSjzqCo3BSpUIp9zEJcKXET8JQ2GheX4,75076 +pandas/tests/groupby/test_counting.py,sha256=iQGu2WgK3xv66rkaKXGHZz01KgzCSQ48Hgt84jzUges,13618 +pandas/tests/groupby/test_cumulative.py,sha256=c6C7ZNo0O5DH9SowsAXp4j_SF-wskjrUlNtfDJomjxQ,10588 +pandas/tests/groupby/test_filters.py,sha256=uFvXjXF2fpQJSwZUhGOUfguyJk7xoXYyL0ShN2KfXx8,21870 +pandas/tests/groupby/test_groupby.py,sha256=fqAmXemWVwmSF-2eVrovj9rFyy88NBAkrC_BT7QGruo,108961 +pandas/tests/groupby/test_groupby_dropna.py,sha256=SUb7WSeAvOrpm3Lx-UcfqsHfjavVqb_fK-fBoOXYSa0,23509 +pandas/tests/groupby/test_groupby_subclass.py,sha256=f9_-wjEExdKD0QAbBnAwl2Vapts-3uiJGTLpKXC4oI4,4580 +pandas/tests/groupby/test_grouping.py,sha256=NWYkL7jIwViNMYwk6jx1nD6_cSlqwPeK1DdlELYvIX8,45896 +pandas/tests/groupby/test_index_as_string.py,sha256=bwAMXa4aSzVDUY1t3HmzK4y-jO5jIwbbRu85Jmb8-U0,2274 +pandas/tests/groupby/test_indexing.py,sha256=Ln_43WnuxtAVrWoaUHWh1IqUSY0i42nY9VnEnw86oXg,9521 +pandas/tests/groupby/test_libgroupby.py,sha256=xiFJcUw_cwTUpQh6E9L47EZm8HopmDrKuYSTI0gHnDs,10457 +pandas/tests/groupby/test_missing.py,sha256=u6mv6_D1ydhkK3jLXqfvidDlOXYdUsN44ySzFksaIlU,5358 +pandas/tests/groupby/test_numba.py,sha256=5jmlxFYdHb9uUw0VWEPNor0KI_2IFTx_WFWXYliNg34,3558 +pandas/tests/groupby/test_numeric_only.py,sha256=dL95cqPjfbA7bTdJioGjdRFF1I2MsO5qYAHZ-TG4HFk,19188 +pandas/tests/groupby/test_pipe.py,sha256=P_n3xXvve-lpjxr1K80dt3co8WTqovjfsetlG2iqrOw,2082 +pandas/tests/groupby/test_raises.py,sha256=0E0Cn1ovzq1FdPE7VHXic2EzE5P0hbYchZ_Io9z5-s4,23764 +pandas/tests/groupby/test_reductions.py,sha256=eEwz3aTCJtS5H1pEOz0yC9FfbnGS-I9M2C3U8QssBTA,40292 +pandas/tests/groupby/test_timegrouper.py,sha256=xSS8uzHq5hXmW6xMeTMmYlq5FGTD-oFC_n6gjYHeNg8,34900 +pandas/tests/groupby/transform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/groupby/transform/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/groupby/transform/__pycache__/test_numba.cpython-312.pyc,, +pandas/tests/groupby/transform/__pycache__/test_transform.cpython-312.pyc,, +pandas/tests/groupby/transform/test_numba.py,sha256=xANgwGOItK0qFyoIQKbaBIV2YjkUNcawYY8SXlsj5v0,10011 +pandas/tests/groupby/transform/test_transform.py,sha256=zGPQ5b3ZXxW1laE1lveRyvg19E7nJ7WK7dRviCE-ypk,57512 +pandas/tests/indexes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_any_index.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_base.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_common.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_datetimelike.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_engines.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_frozen.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_index_new.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_numpy_compat.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_old_base.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/__pycache__/test_subclass.cpython-312.pyc,, +pandas/tests/indexes/base_class/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/base_class/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_pickle.cpython-312.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_reshape.cpython-312.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/base_class/__pycache__/test_where.cpython-312.pyc,, +pandas/tests/indexes/base_class/test_constructors.py,sha256=yMGZGvGyBUH42aJu2DsJp7-ZcIBCjFOjYdDuU9GnZU0,2710 +pandas/tests/indexes/base_class/test_formats.py,sha256=mxZ2qfK-2k0GMQMovUZOcWzh_TNARa80JbggsXLFHIM,6305 +pandas/tests/indexes/base_class/test_indexing.py,sha256=1zbBHv-nJCIfXRicDPXPtyLBL3Iy-LvH5bkamnoFGrI,3687 +pandas/tests/indexes/base_class/test_pickle.py,sha256=ANKn2SirZRA2AHaZoCDHCB1AjLEuUTgXU2mXI6n3Tvw,309 +pandas/tests/indexes/base_class/test_reshape.py,sha256=PerLCLY_vi5wySNUAfD3P4Y6esET-WBqx4vSAEeifYk,3304 +pandas/tests/indexes/base_class/test_setops.py,sha256=X84dGTmkrEJ2oSQfr-WfozQA3moGUpnmbhkTYzJWH7k,9076 +pandas/tests/indexes/base_class/test_where.py,sha256=uq7oB-lk7rsgYQer8qeUsqD5aSECtRPSEUfKzn91BiE,341 +pandas/tests/indexes/categorical/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/categorical/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_append.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_category.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_equals.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_fillna.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_map.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_reindex.cpython-312.pyc,, +pandas/tests/indexes/categorical/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/categorical/test_append.py,sha256=LjLMq8GkNrsIVNfTrujLv_TlKo79oA_XbpNUFs-pqVQ,2191 +pandas/tests/indexes/categorical/test_astype.py,sha256=mQjQ9hbRf940DjzvC9OD6t8BzwphBXJdrROyEul1tzU,2860 +pandas/tests/indexes/categorical/test_category.py,sha256=_BMLTPgf7wLGxw4FUV3XcZUFiK-l_6P-KhfZXH9qYAw,14542 +pandas/tests/indexes/categorical/test_constructors.py,sha256=g3hEVtOS576z11miVwakwud3cLXkFI2ErImUaFW9N6U,5536 +pandas/tests/indexes/categorical/test_equals.py,sha256=AIrr-W5WeqDj5KbELqjHm3-hqqx3q8YxBrv1z2oco94,3569 +pandas/tests/indexes/categorical/test_fillna.py,sha256=sH68aWCabI2qy5dbgxQCXeTfvn1NQgDfM1OT4ojFmaU,1850 +pandas/tests/indexes/categorical/test_formats.py,sha256=AA5dyUaCUlbSKTsskrQ5MXfe375SZJXSKq3ZXnNMLik,6281 +pandas/tests/indexes/categorical/test_indexing.py,sha256=zBvryPgX3VF5P4HqUQ1h1FD2warHLfSvb0nBq6rxjrc,14978 +pandas/tests/indexes/categorical/test_map.py,sha256=VHsSFGWEBmgQLvvquC6-y3QDq3lwzSpqPWZHTLiGdzw,4664 +pandas/tests/indexes/categorical/test_reindex.py,sha256=vPCV9O582vxJpubqCm33UHcaOKMZNg8OMzDF3lQQDiM,2938 +pandas/tests/indexes/categorical/test_setops.py,sha256=YiBoQN3Dor2p32HCUColWIZBH620H1aPa4easA5FMgc,462 +pandas/tests/indexes/conftest.py,sha256=aP9iTl0n1HpZWIP_02i__XxFnSMJF8iCM5Ein2MRK80,987 +pandas/tests/indexes/datetimelike_/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/datetimelike_/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_drop_duplicates.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_equals.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_is_monotonic.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_nat.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_sort_values.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/__pycache__/test_value_counts.cpython-312.pyc,, +pandas/tests/indexes/datetimelike_/test_drop_duplicates.py,sha256=UEmTzsZerSOIE6mPfaw4kQd7UFEo02H-EW5GOPpDTKU,2600 +pandas/tests/indexes/datetimelike_/test_equals.py,sha256=7Jnk1MjPYvI-I_YMRNRF29-g5CLaFmU3ZqQ6aO9KqIE,6348 +pandas/tests/indexes/datetimelike_/test_indexing.py,sha256=QoTXbCiqjK4tBDHUbq1TKPp0NroYkeheFjRq-VxlsP0,1310 +pandas/tests/indexes/datetimelike_/test_is_monotonic.py,sha256=_5PXF7mVilu1S4EJv7F-XMYIoz40kBkdSs4RJ8jTVdI,1522 +pandas/tests/indexes/datetimelike_/test_nat.py,sha256=6-Yr-n4JskfsjbaEPFgaRPKX4S7R-LhQOEQSC7cBybw,1335 +pandas/tests/indexes/datetimelike_/test_sort_values.py,sha256=iIhZOW7CEwVD3KuJUFEOM2z18KORCx04W09bwsdKSNs,11463 +pandas/tests/indexes/datetimelike_/test_value_counts.py,sha256=o090A9QuhmahJjH0WgKBIxXdBVxPkAc8vikXqZLuoD4,3150 +pandas/tests/indexes/datetimes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/datetimes/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_date_range.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_datetime.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_freq_attr.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_iter.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_npfuncs.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_ops.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_partial_slicing.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_pickle.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_reindex.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_scalar_compat.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/datetimes/__pycache__/test_timezones.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/datetimes/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_asof.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_delete.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_factorize.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_fillna.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_insert.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_isocalendar.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_map.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_normalize.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_repeat.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_resolution.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_round.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_shift.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_snap.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_frame.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_julian_date.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_period.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_pydatetime.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_to_series.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_tz_convert.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_tz_localize.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/__pycache__/test_unique.cpython-312.pyc,, +pandas/tests/indexes/datetimes/methods/test_asof.py,sha256=gd-nBXLe-Dc5Voc_Ksgmq9mOU6S_I5ZZqlXcapgKzfE,738 +pandas/tests/indexes/datetimes/methods/test_astype.py,sha256=23E4v71mBkSd_WTYy9L1u9ljV-BjBkBtGW5m1uJaTW4,12342 +pandas/tests/indexes/datetimes/methods/test_delete.py,sha256=JaaHDwYuTarkta3Qd2fbteZd9k0oOzJsWCPEHUHHG4k,4441 +pandas/tests/indexes/datetimes/methods/test_factorize.py,sha256=Mif09gcfRfIO2uhCqNN9OC_NXggKizbuwaz6ScGzMUE,4468 +pandas/tests/indexes/datetimes/methods/test_fillna.py,sha256=eESnVTQ8J3iBL24bWKt7TmHxC5FJiLZMpKjw1V376qY,2004 +pandas/tests/indexes/datetimes/methods/test_insert.py,sha256=StmxdK3meNNEDO_CGzVIqltbXxwfX0pQxsngnPQfdtA,9343 +pandas/tests/indexes/datetimes/methods/test_isocalendar.py,sha256=JEABIm6LNySCbSUq6HLS-_qTGK3HgVcScSXLpDsrJ8o,908 +pandas/tests/indexes/datetimes/methods/test_map.py,sha256=1JR2lb_zk_8aIgRqnuWHfeXRPZBsFtdT4tRXeTDNqsQ,1358 +pandas/tests/indexes/datetimes/methods/test_normalize.py,sha256=rztamd3kwUZMcVQjeR1JcaIKr7pT0ACFcU4-FFynZkA,3041 +pandas/tests/indexes/datetimes/methods/test_repeat.py,sha256=GN-wTWws2sjodNibctZOi_NDX85y36Lr2BBmAs3LLMM,2740 +pandas/tests/indexes/datetimes/methods/test_resolution.py,sha256=RzkIL8IX63X1fgwr8o4_xuKvdOtPHdodPbsS75u9BRM,785 +pandas/tests/indexes/datetimes/methods/test_round.py,sha256=Ic1FFoRHdPv4TF1dSnOWVzVX90GowbXumbuNgTFPYlM,7822 +pandas/tests/indexes/datetimes/methods/test_shift.py,sha256=NhyUs0PMDuzSM573tqUamx3THf03WUNKz0nSOzDta5M,5933 +pandas/tests/indexes/datetimes/methods/test_snap.py,sha256=smwfWvN33B6UgLagKaBQkllTuGAm7Wiaq87M9nxu8g8,1305 +pandas/tests/indexes/datetimes/methods/test_to_frame.py,sha256=C6glyGdxSs-hMDQSt9jkftmRlTGPMCGdIQlfChR9iGk,998 +pandas/tests/indexes/datetimes/methods/test_to_julian_date.py,sha256=u6JLYazILIdltbe1uZE3iBAqE_ixXwx0oqwS6T-Mpng,1608 +pandas/tests/indexes/datetimes/methods/test_to_period.py,sha256=IIzHPLsk8BR43Ib5-8-EVxLQc_rkTcGBSk1M4-9OhYw,7986 +pandas/tests/indexes/datetimes/methods/test_to_pydatetime.py,sha256=sM22b33Cxwrpc5nShAp5QH2KQPOlEpi5d8G6fM3vVI8,1345 +pandas/tests/indexes/datetimes/methods/test_to_series.py,sha256=8ZW3AxMkHj3IV1wVgM797SH_rRLKQ9zld1UVkhk1C8Q,493 +pandas/tests/indexes/datetimes/methods/test_tz_convert.py,sha256=-Tuxq1egpSCBnBB7E_rAj1FudFgTm2DDYQ_wPMKgzwQ,11295 +pandas/tests/indexes/datetimes/methods/test_tz_localize.py,sha256=Q7A54lsovDxBDEqU7XNBJql3PoNLF7NVeXwvMFgrVI0,14830 +pandas/tests/indexes/datetimes/methods/test_unique.py,sha256=qZorAPI_oWcz5WdBEr0nQuT_mrApTgShqg3JVlzpVKU,2096 +pandas/tests/indexes/datetimes/test_arithmetic.py,sha256=l2q_n3zBT98OvI4gV7XZOZMCvo54xgM9frByNKCsbyU,1796 +pandas/tests/indexes/datetimes/test_constructors.py,sha256=zzICypvVbu8_PCfL3jiDGjSJWSflWjJbpqS5iNkd1kA,43922 +pandas/tests/indexes/datetimes/test_date_range.py,sha256=2CECH8fOYUP7LxyqlehEHVme2oSN4ZvEl3hjH8t-TDY,61363 +pandas/tests/indexes/datetimes/test_datetime.py,sha256=Q_dwJTXtSuVYTlMmnGhiNGCRrqHONu9wu2N5wgZw4pY,7305 +pandas/tests/indexes/datetimes/test_formats.py,sha256=rN90ZOq3e83t7X6uyd-cR1czM4A01nr3z_GIJJ0sy0k,12738 +pandas/tests/indexes/datetimes/test_freq_attr.py,sha256=oX_cweTcpKd27ywN976KCYpg0oFe77MeDWqnRJQwVRo,1732 +pandas/tests/indexes/datetimes/test_indexing.py,sha256=MncSVI_l914qEW2CUg_livQrJ6AcOxvzmaiNOdzlOoA,25241 +pandas/tests/indexes/datetimes/test_iter.py,sha256=7r3wuHLeCBHfX8kaHNK-4Ecr6ZqR89Dhzkisx2C7jOI,2590 +pandas/tests/indexes/datetimes/test_join.py,sha256=mFxTvHONYg4ELXArFDBo_qPO2_7JO5NoIWgYcCSDtRw,4915 +pandas/tests/indexes/datetimes/test_npfuncs.py,sha256=YJihZytss-MVNprp4p5pAL_emeC5pb3hBwtaS3yMCcU,384 +pandas/tests/indexes/datetimes/test_ops.py,sha256=h9MI1sM5I_T4a7kEPdZs2QuXTdlcnvKQJdI5jh6j4h4,1340 +pandas/tests/indexes/datetimes/test_partial_slicing.py,sha256=OlC1IDbJ2y_qjp-HCFERReBOHb07DnlPZ3lMlhwMSLA,16495 +pandas/tests/indexes/datetimes/test_pickle.py,sha256=cpuQl8fsaqJhP4qroLU0LUQjqFQ0uaX3sHql2UYOSg4,1358 +pandas/tests/indexes/datetimes/test_reindex.py,sha256=s1pt3OlK_JdWcaHsxlsvSh34mqFsR4wrONAwFBo5yVw,2145 +pandas/tests/indexes/datetimes/test_scalar_compat.py,sha256=pJz6r8-pnr5nl_KkUaCkTu2A3SGzJbH_0dpTFRjUUz8,11156 +pandas/tests/indexes/datetimes/test_setops.py,sha256=HThtofPALvrCNqwnFk-tqdvCIe_ij2f-VOObJfZQ93w,23574 +pandas/tests/indexes/datetimes/test_timezones.py,sha256=LfELNHXgQN5-7zwBW5OweUZm6y8Ogtm-ir7l-RQAJpQ,8046 +pandas/tests/indexes/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/interval/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_equals.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_interval.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_interval_range.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_interval_tree.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_pickle.cpython-312.pyc,, +pandas/tests/indexes/interval/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/interval/test_astype.py,sha256=G1mQrK3eS_zG7LMYuwyCvkph9ZoNkbQMLpI0nhI5tjI,9002 +pandas/tests/indexes/interval/test_constructors.py,sha256=THCXDlRG7AncX5wzRlp9w1RNrYA0bTpWmzErMVfT0-w,19853 +pandas/tests/indexes/interval/test_equals.py,sha256=a7GA_whLbOiS4WxUdtDrqKOUhsfqq3TL0nkhqPccuss,1226 +pandas/tests/indexes/interval/test_formats.py,sha256=1QwWNVu3bZWSULSfNza2_vhfCfzdXjLdyJEXW5ERAE8,3880 +pandas/tests/indexes/interval/test_indexing.py,sha256=OEO2u5o44t3xKNvDshIviQG8HMZH3fMUrF-QYiul4-s,25425 +pandas/tests/indexes/interval/test_interval.py,sha256=L4Zo4GWIMVzHpOQ3Q09-GH_0Ixtge5ATR6kIgMYYjoc,34741 +pandas/tests/indexes/interval/test_interval_range.py,sha256=z_ZiNlL_7esHwH4Kd77k2gPm5Ev0Zy_NgACSkKoy4vA,13758 +pandas/tests/indexes/interval/test_interval_tree.py,sha256=yHyolu5v8YRazksfOBRgWd3O3eFVtzPc6NePpcV0ceU,7560 +pandas/tests/indexes/interval/test_join.py,sha256=HQJQLS9-RT7de6nBHsw50lBo4arBmXEVZhVMt4iuHyg,1148 +pandas/tests/indexes/interval/test_pickle.py,sha256=Jsmm_p3_qQpfJ9OqCpD3uLMzBkpsxufj1w6iUorYqmk,435 +pandas/tests/indexes/interval/test_setops.py,sha256=nwBz1MHuHiM7JQc74w2doEpgTSwg3NYfGwGbQFXWKw8,8346 +pandas/tests/indexes/multi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/multi/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_analytics.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_compat.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_conversion.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_copy.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_drop.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_duplicates.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_equivalence.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_get_level_values.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_get_set.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_integrity.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_isin.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_lexsort.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_missing.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_monotonic.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_names.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_partial_indexing.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_pickle.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_reindex.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_reshape.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_sorting.cpython-312.pyc,, +pandas/tests/indexes/multi/__pycache__/test_take.cpython-312.pyc,, +pandas/tests/indexes/multi/conftest.py,sha256=42mdJqtqvX3PlBSdch1Y6jRBvhe0IzZxOoLt-BGX03Q,698 +pandas/tests/indexes/multi/test_analytics.py,sha256=FeKERG9vHP-fAeGhlrzKO3IfAFpOOQnxQD7fRu2ycLY,6710 +pandas/tests/indexes/multi/test_astype.py,sha256=YmTnPF6qXwvYY82wZfQ8XFwVwOYYsIls3LSrdADDW-4,924 +pandas/tests/indexes/multi/test_compat.py,sha256=q53DVV5fYOKRVEQBl_2ws6WXrNsrGr5w4FXvXLUBeuQ,3918 +pandas/tests/indexes/multi/test_constructors.py,sha256=xheN8wi7feG8ycx3IsPfx-cCwsrPf2WNG15MWHmrTww,26798 +pandas/tests/indexes/multi/test_conversion.py,sha256=XbgxHZRkjGYjj2M-EKCGRAY7Yghuly9Umd4isj8Q6MI,6172 +pandas/tests/indexes/multi/test_copy.py,sha256=9Xperk7a4yBTQKo8fgk3gCa2SwJr30mH2JYYMYWguWY,2405 +pandas/tests/indexes/multi/test_drop.py,sha256=Mv5FB-riRSuwwvVFJ60GwxRGbuFkU_LU5DPW8KY8NTk,6089 +pandas/tests/indexes/multi/test_duplicates.py,sha256=7_FP6fYuzDdffF2Wvgl8VKW4Auzq0xJ5ZVfp5Evnm3A,11559 +pandas/tests/indexes/multi/test_equivalence.py,sha256=LKBMAg82PbzkuMMy18u6Iktjzuavo1PIY-IxtPGBpZE,8530 +pandas/tests/indexes/multi/test_formats.py,sha256=Ra7L6T0N4zh6rZUg3gFP6bGC902uhBKV4kyLku7HCuI,9538 +pandas/tests/indexes/multi/test_get_level_values.py,sha256=WFSDmHIAXZ1RvDl-mK2HtXmWRO6IwSX5F0J7j5z0cm8,3971 +pandas/tests/indexes/multi/test_get_set.py,sha256=RAqTkYhqTOAgWEqcboZqNUwBWu8Epxk1I2w5dfCuPX0,12870 +pandas/tests/indexes/multi/test_indexing.py,sha256=lbx9kPQFf5EFfdCZ-yg1nGSqmJOYcpuHCBMC6vs_ZvA,36399 +pandas/tests/indexes/multi/test_integrity.py,sha256=VzyV3RrhWkQxwWzzLeLT6Lmc-njl4FnpoAIshI1BFW8,9031 +pandas/tests/indexes/multi/test_isin.py,sha256=OtlwJ9zZDvwgZOgbeY_oidWPOUmii_JBCCBpHnLw8us,3426 +pandas/tests/indexes/multi/test_join.py,sha256=aRp18UCIgoSXazdYdirOwGV0k8Gj4o5eNRJL56p56Bc,8440 +pandas/tests/indexes/multi/test_lexsort.py,sha256=KbwMnYF6GTIdefQ7eACQusNNuehbtiuqzBMqsOSfDU0,1358 +pandas/tests/indexes/multi/test_missing.py,sha256=hHjKWxl5vkG5k9B9fxglrYB4eQldKamkMbACAu6OvUY,3348 +pandas/tests/indexes/multi/test_monotonic.py,sha256=5xlESrQOEcFWdr0iB3OipJtA6-RzriU3Yq2OQGgP0M4,7007 +pandas/tests/indexes/multi/test_names.py,sha256=zx_8kapVXzDS_SsylRzTFia2OrNJeEq3kmNHUA4RVPM,6601 +pandas/tests/indexes/multi/test_partial_indexing.py,sha256=sVNIk9_NxMDsHuRQzPCernPmchTF5INAUFkzQV7t8T0,4765 +pandas/tests/indexes/multi/test_pickle.py,sha256=ZJVZo0DcXDtV6BAUuPAKbwMV8aGfazJLU7Lw6lRmBcw,259 +pandas/tests/indexes/multi/test_reindex.py,sha256=ww8fSIx426wfqBTogkJrKS533CjKorf-B4bhyKdEnD4,5856 +pandas/tests/indexes/multi/test_reshape.py,sha256=yRcnTGS0M5749jUZGEZA8_UxSZ-CeOeCsWYBbTS0nTY,6711 +pandas/tests/indexes/multi/test_setops.py,sha256=aPlm3AXfjUxPJKojiFLA8_kIAZGCqewAxGwxcDMqYT4,25460 +pandas/tests/indexes/multi/test_sorting.py,sha256=69C8BENuzyUvnQXEbjVvADmBAr5G6wzM-ELHOMLV2Do,10745 +pandas/tests/indexes/multi/test_take.py,sha256=4MaxPM4ZJQPXJKiqgwEwhZ71TyH4KQfIs5LgS40vvLM,2487 +pandas/tests/indexes/numeric/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/numeric/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_numeric.cpython-312.pyc,, +pandas/tests/indexes/numeric/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/numeric/test_astype.py,sha256=P19W9zZl8tN0EK-PaEi2gIFHLwCbruTMEUm7_ALGH9Q,3618 +pandas/tests/indexes/numeric/test_indexing.py,sha256=nDzkrokWvcmHkeHWjE8umPfxX4lR6AnQorAV7ppElCI,22761 +pandas/tests/indexes/numeric/test_join.py,sha256=OuSnYPH-jIM4UZRUKQ9NFxxd8Ot1HEP7KA3_ZpPX3Ks,15039 +pandas/tests/indexes/numeric/test_numeric.py,sha256=mEAFY8sSQdkVA0rJCTZb8cqjVAsTvL6mXzQSEXyxEgc,18586 +pandas/tests/indexes/numeric/test_setops.py,sha256=nO-3m7tb_ytjXx0Z8SqBkPSAnPVDz_PL3r2fzWtE7fg,5874 +pandas/tests/indexes/object/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/object/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/object/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/object/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/object/test_astype.py,sha256=p1EwqKDlOHAlSOpzxLaUDnAEm6yAQ0VIGnN-hhieCks,368 +pandas/tests/indexes/object/test_indexing.py,sha256=_kv5xtayKpuAj6DBz7V3ZNg2LE3zHv0Ua5LJzQHilEE,6442 +pandas/tests/indexes/period/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/period/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_freq_attr.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_monotonic.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_partial_slicing.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_period.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_period_range.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_pickle.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_resolution.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_scalar_compat.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_searchsorted.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/period/__pycache__/test_tools.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/period/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_asfreq.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_factorize.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_fillna.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_insert.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_is_full.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_repeat.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_shift.cpython-312.pyc,, +pandas/tests/indexes/period/methods/__pycache__/test_to_timestamp.cpython-312.pyc,, +pandas/tests/indexes/period/methods/test_asfreq.py,sha256=PAqk5Zktd2OvLYwNoUGeXOh39HIIz9-5FqXnzrH6rtA,7080 +pandas/tests/indexes/period/methods/test_astype.py,sha256=vz7aRsoeDLXvQ_bhob7hNq1B_3gs4n_rCkD-sW5atAc,5671 +pandas/tests/indexes/period/methods/test_factorize.py,sha256=FXQh6VmGkuGkB2IAT4Y-2V5UaD2LCUNjQZ6amfBao80,1425 +pandas/tests/indexes/period/methods/test_fillna.py,sha256=jAYnaWGMuUaG993yxLwr1eT6J1ut43CcBaKds4Ce3-0,1125 +pandas/tests/indexes/period/methods/test_insert.py,sha256=JT9lBhbF90m2zRgIwarhPqPtVbrvkLiihZxO-4WHvTU,482 +pandas/tests/indexes/period/methods/test_is_full.py,sha256=RqIErBofIn5Ewh-MomVePHOn0hViZbe4laMC2vh8nPs,570 +pandas/tests/indexes/period/methods/test_repeat.py,sha256=1Nwn-ePYBEXWY4N9pFdHaqcZoKhWuinKdFJ-EjZtFlY,772 +pandas/tests/indexes/period/methods/test_shift.py,sha256=P7XDpMkLEYarH06RLBglFJKoGPkax4oLdiuI676KLek,4405 +pandas/tests/indexes/period/methods/test_to_timestamp.py,sha256=DCFf_Dt5cNsuSWJnYQAGfJrx1y2Z0GQiSTh0ajQJhjA,4888 +pandas/tests/indexes/period/test_constructors.py,sha256=LkRK-O65VdhX3EDQJHDdeGVQHfA6BQHT_PCi97M4xIs,27175 +pandas/tests/indexes/period/test_formats.py,sha256=DFLAMAPFzX2DI1iAAEjVY_nM9TuoYmCje3m7Q17A0EU,13259 +pandas/tests/indexes/period/test_freq_attr.py,sha256=KL1xaip5r7nY-3oLW16bmogfkYljsGJEJGKxn6w72Fo,646 +pandas/tests/indexes/period/test_indexing.py,sha256=jms77VvgkIgm0bSCHX-IMOtYuR0w2jd5uW3UoC2fm_4,27893 +pandas/tests/indexes/period/test_join.py,sha256=mwVL-OKx7tKTvMeSLNTh8jv6ViU6-NXcWr5O4hCmkOc,1835 +pandas/tests/indexes/period/test_monotonic.py,sha256=9Sb4WOykj99hn3MQOfm_MqYRxO5kADZt6OuakhSukp4,1258 +pandas/tests/indexes/period/test_partial_slicing.py,sha256=gXvS-qB0jPHYLKvjaP2rBW4p2UAm-ahM6KCCpT-u7ns,7433 +pandas/tests/indexes/period/test_period.py,sha256=91AawBQiPn_J3b6aG4sEzU24VaNJBTMn8shm_qkcE2g,7861 +pandas/tests/indexes/period/test_period_range.py,sha256=PB_VIuobx3NgnGOSmYZ0fyk79Zpoop22oYDP-TW-36Y,8979 +pandas/tests/indexes/period/test_pickle.py,sha256=l9A79u5PTcoa70g26wFPLTGnbvYpe76hPk1Iv334gb0,692 +pandas/tests/indexes/period/test_resolution.py,sha256=0TmnJeZCOaTWneeWA66DlxKgaUZJTfP0jKgLAY1jiyg,571 +pandas/tests/indexes/period/test_scalar_compat.py,sha256=CJuW0w6SdwDPtlk2Dl14g0ewuCcsIKPwtnmIMBSYEuc,1350 +pandas/tests/indexes/period/test_searchsorted.py,sha256=_u7DlvBnFx0_c8u3FIKYVOUcjlvN7p0gojLl9fZDkMQ,2604 +pandas/tests/indexes/period/test_setops.py,sha256=BcwDXv1-fnqOJLtzNqY2rEOye97Smyk2iXMnZx_IQE8,12547 +pandas/tests/indexes/period/test_tools.py,sha256=DFoxBsCYRWqodmNaDNPnQrZTTXiaSvwNZkwrybe7cl0,1361 +pandas/tests/indexes/ranges/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/ranges/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_range.cpython-312.pyc,, +pandas/tests/indexes/ranges/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/ranges/test_constructors.py,sha256=ceX79fbjGyc5VNkmz29Q1N7WGXLj40BvTuz5PfNAw4I,5328 +pandas/tests/indexes/ranges/test_indexing.py,sha256=WCJFjnEzFIqQUv_i2cy-wHRQ4Txfi8uq4UBp20s4LRw,5171 +pandas/tests/indexes/ranges/test_join.py,sha256=lniHRyuEJWY7UGc0TpJ20xzUftn6BpYJbZQPo2I0dxE,6268 +pandas/tests/indexes/ranges/test_range.py,sha256=AaoOQ_PufgrgnOmS7ARYRydbdU1jsb6-DKu2oX52LuI,20937 +pandas/tests/indexes/ranges/test_setops.py,sha256=yuiXAKlZJ5c3LkjPzFltAKFQmhVqaBleiJ7nzXs4_eA,17534 +pandas/tests/indexes/string/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/string/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/string/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/string/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/string/test_astype.py,sha256=r2hLBYI1NQu3KD6daxOC-m6hYp3FhvMcPPPHZrvfXMs,722 +pandas/tests/indexes/string/test_indexing.py,sha256=vrbnnCMOQaIVkIUUlpbcW2Fgy6XGMr2BrefVBDp95F0,7850 +pandas/tests/indexes/test_any_index.py,sha256=KVBtWYaXj_qyCfSDgCeO7wc4uj0lkJrm-yiBJEu_nxU,5143 +pandas/tests/indexes/test_base.py,sha256=FTlZOGsF-ryZUz-FnDPSAtq33jTCDq5xK-jLZToe0FY,60527 +pandas/tests/indexes/test_common.py,sha256=UMs10zvX5OpUe3OicDGBO2wGz2b84zZA9TVWb36Xp6A,17972 +pandas/tests/indexes/test_datetimelike.py,sha256=6ue74lBTp8Es6PZoE1e_5Fo6k3j7Hq_HkpLnBjAYspE,5598 +pandas/tests/indexes/test_engines.py,sha256=rq3JzDXNc2mZS5ZC2mQLpTeydheOX9OLoq1FLR53wbI,6699 +pandas/tests/indexes/test_frozen.py,sha256=ocwmaa3rzwC7UrU2Ng6o9xxQgxc8lDnrlAhlGNvQE0E,3125 +pandas/tests/indexes/test_index_new.py,sha256=6tO12VIGCoGKN3uk1SlPdPXn5vQaOJ9tECa3oVyWC8c,14923 +pandas/tests/indexes/test_indexing.py,sha256=BtO0njTwDFrXNr3nMKq_p8PDhPzH9RfzCrnLkJxz5fw,11518 +pandas/tests/indexes/test_numpy_compat.py,sha256=fnrc8fNrV7v3BRTY7Huu9cyrBw2aNUrv5i4UUEublFE,5776 +pandas/tests/indexes/test_old_base.py,sha256=Ama73MdyBWXYZiw6vVpOxN_mnNMwcSIQg5PqzWPSFLY,40117 +pandas/tests/indexes/test_setops.py,sha256=OKZqVmEihDGdzqJVrdc1PxVdBQoaJFrrxjdpyZRJDg4,33496 +pandas/tests/indexes/test_subclass.py,sha256=lmZHuQ8OSlwP3xcR8Xy2Mfvjxp2ry2zUL4DO2P4hbnk,1058 +pandas/tests/indexes/timedeltas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/timedeltas/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_delete.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_freq_attr.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_ops.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_pickle.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_scalar_compat.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_searchsorted.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_setops.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_timedelta.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/__pycache__/test_timedelta_range.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexes/timedeltas/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_factorize.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_fillna.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_insert.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_repeat.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/__pycache__/test_shift.cpython-312.pyc,, +pandas/tests/indexes/timedeltas/methods/test_astype.py,sha256=xbvKmv20EHrDvBcjJnUpJfiPkfOCPiFrOn7TMS2H_s8,6331 +pandas/tests/indexes/timedeltas/methods/test_factorize.py,sha256=aqhhwRKZvfGxa3v09X5vZ7uBup8n5OjaUadfJpV6FoI,1292 +pandas/tests/indexes/timedeltas/methods/test_fillna.py,sha256=F7fBoEG-mnu16ypWYmK5wbIovQJKL0h86C1MzGkhPoE,597 +pandas/tests/indexes/timedeltas/methods/test_insert.py,sha256=fDYCuOIefgjNBJ7zhAUYniNVl5SltSs275XaNoL0S-s,4713 +pandas/tests/indexes/timedeltas/methods/test_repeat.py,sha256=vPcNBkY4H2RxsykW1bjTg-FSlTlQ2H1yLb-ZsYffsEg,926 +pandas/tests/indexes/timedeltas/methods/test_shift.py,sha256=MzVVupnLHEvuwlVCn6mR7LQ9pLeNiWM2lWwNlIwoo98,2756 +pandas/tests/indexes/timedeltas/test_arithmetic.py,sha256=YocDQIovXnrpXEzz3Ac-3l2PdGaDf2_sF8UPcLVF1Z8,1561 +pandas/tests/indexes/timedeltas/test_constructors.py,sha256=atU_oy_1oyUtMWRg47A94j3S4nPJbDRRgUhDCW6TO6M,10600 +pandas/tests/indexes/timedeltas/test_delete.py,sha256=-5uYhDUCD55zv5I3Z8aVFEBzdChSWtbPNSP05nqUEiA,2398 +pandas/tests/indexes/timedeltas/test_formats.py,sha256=4yUVmL5NEabGi9AXPA5isM3c4F3Rgslk4zqcfS-ua3s,3807 +pandas/tests/indexes/timedeltas/test_freq_attr.py,sha256=gYGl9w9UdtcfN26KUx1QyY4mjh6A0m4Csk3gsCIcdos,2176 +pandas/tests/indexes/timedeltas/test_indexing.py,sha256=9C-U4bwBd7D1GnaKgi51Jlgod7KhONIlgrA9t7jSQ80,12160 +pandas/tests/indexes/timedeltas/test_join.py,sha256=7JUirtgNGJMRL1-k2gekrvondwYuIVvuI2548v4nfIo,1396 +pandas/tests/indexes/timedeltas/test_ops.py,sha256=nfGyNJvNy7_jmWebKjevLKhyAMNvI5jytkZTNlpEC-g,393 +pandas/tests/indexes/timedeltas/test_pickle.py,sha256=QesBThE22Ba17eUdG21lWNqPRvBhyupLnPsXueLazHw,302 +pandas/tests/indexes/timedeltas/test_scalar_compat.py,sha256=hldSSTxREuBBuLAhvLTjX7FUmJ9DzcJxmMqzaClnErg,4573 +pandas/tests/indexes/timedeltas/test_searchsorted.py,sha256=kCE0PkuPk1CxkZHODe3aZ54V-Hc1AiHkyNNVjN5REIM,967 +pandas/tests/indexes/timedeltas/test_setops.py,sha256=Y6OwY82XC1hDgME55I_9q_UzGZdKhAhI1sxXS8bzr1w,9503 +pandas/tests/indexes/timedeltas/test_timedelta.py,sha256=UxobS6Dhfoqy4bnoAuMlLO8acpNrCDGsYWl4vGbDO8Q,1934 +pandas/tests/indexes/timedeltas/test_timedelta_range.py,sha256=tZqv_j045dPD3K2sbqdhdvEb-qE7szf9S7DJNX5Ri3o,6220 +pandas/tests/indexing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexing/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/common.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_at.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_categorical.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_chaining_and_caching.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_check_indexer.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_coercion.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_datetime.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_floats.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_iat.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_iloc.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_indexers.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_loc.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_na_indexing.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_partial.cpython-312.pyc,, +pandas/tests/indexing/__pycache__/test_scalar.cpython-312.pyc,, +pandas/tests/indexing/common.py,sha256=LtCDO4TeMhLWAiTGiJET3YP8RO6T3OQqmdpJ8JH391g,1021 +pandas/tests/indexing/conftest.py,sha256=9C84qvdnHzbM5C0KIVw3ueQhHzuUMoAlw07dVJqCAmQ,2677 +pandas/tests/indexing/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexing/interval/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexing/interval/__pycache__/test_interval.cpython-312.pyc,, +pandas/tests/indexing/interval/__pycache__/test_interval_new.cpython-312.pyc,, +pandas/tests/indexing/interval/test_interval.py,sha256=pB8gTluRFlmZZVCcRDtjXUygjSJegI3YRYI3XIPgsy0,7482 +pandas/tests/indexing/interval/test_interval_new.py,sha256=IkPyCHTHvwyHf25ljz4o6Q0CnHVpnLD2jVUF3TbtLS4,7976 +pandas/tests/indexing/multiindex/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/indexing/multiindex/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_chaining_and_caching.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_datetime.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_getitem.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_iloc.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_indexing_slow.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_loc.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_multiindex.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_partial.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_setitem.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_slice.cpython-312.pyc,, +pandas/tests/indexing/multiindex/__pycache__/test_sorted.cpython-312.pyc,, +pandas/tests/indexing/multiindex/test_chaining_and_caching.py,sha256=hPcMvvPamIHI8AeSL7xvqs3eOT-5ONMjLy2XK2Mgt4Q,2922 +pandas/tests/indexing/multiindex/test_datetime.py,sha256=tl1yr3h50R0t7uvwTcfsRW-jt1n9vsqf4BWp4dNTdd8,1234 +pandas/tests/indexing/multiindex/test_getitem.py,sha256=wNftnfXLfiyjduEYeq8MSfE8K1OKaZG0WpmKWBqWk6o,13230 +pandas/tests/indexing/multiindex/test_iloc.py,sha256=G2CUPRhd5pRImZpH0uOVIPid7fzB4OuJZjH8arQMrE0,4918 +pandas/tests/indexing/multiindex/test_indexing_slow.py,sha256=nMfW1LQn7YlJauNceeR-uo_yPxRG2E8hcbgqTBMxaH4,3335 +pandas/tests/indexing/multiindex/test_loc.py,sha256=zFaOquvsDx_cVqnhxRZBtPgTqfkMd1k3jo3K6D_4YBM,33044 +pandas/tests/indexing/multiindex/test_multiindex.py,sha256=bIihrEIUXO1s8wAnKof9ATiwqAvwuLIWzE_oZlMxlOs,8065 +pandas/tests/indexing/multiindex/test_partial.py,sha256=05MXMJmAevJ31bqHIVikEL14x6s7IUASxLaw62w44mQ,8858 +pandas/tests/indexing/multiindex/test_setitem.py,sha256=cn0FPeh4oKRpI0o01tFx24VOoNQr90GCiKIMo8cBaE0,19840 +pandas/tests/indexing/multiindex/test_slice.py,sha256=7JcyCAq91OpruPy1awmdQmblxPzQF4UrnUN2XHrahbY,27104 +pandas/tests/indexing/multiindex/test_sorted.py,sha256=xCdmS_0DBN2yoTVcSB-x6Ecwcw93p6erw3bTiU6_J3s,5192 +pandas/tests/indexing/test_at.py,sha256=eQhts-_Z5PWS7BpwfC3-e3YUEBm2pHsxcUY781OVQfg,8092 +pandas/tests/indexing/test_categorical.py,sha256=JPn8mSo7FSTuFaHzpiELgVBwTsqmjISLnGoxloy6SjU,19699 +pandas/tests/indexing/test_chaining_and_caching.py,sha256=-T0e9bh8ktgrHrB8CXd-MjcvLnckuiSSyBC8Cr6q-uE,23479 +pandas/tests/indexing/test_check_indexer.py,sha256=tfr2a1h6uokN2MJDE7TKiZ0iRaHvfSWPPC-86RqaaDU,3159 +pandas/tests/indexing/test_coercion.py,sha256=pJcNUByiuyinv0bKk9jRTLSitvNcpjt4wgyuHMAjkDE,32668 +pandas/tests/indexing/test_datetime.py,sha256=Gj5Fo4ywd4md3H-zbk11bSbNEmktbnlHORVRzBfN0oE,5703 +pandas/tests/indexing/test_floats.py,sha256=KG_T_POIEc5nnVL7Zi8zSwamhahbfjUxBYrC3ilRlEI,20603 +pandas/tests/indexing/test_iat.py,sha256=cQrMr1MYQv5LZS5E34NumdqqeK8hvcN6duLRTaeZ6Go,1492 +pandas/tests/indexing/test_iloc.py,sha256=gbyA7dTpvnkQKxJZmofFUJmsU863ZR4bsZqaOiBlZ7c,53929 +pandas/tests/indexing/test_indexers.py,sha256=agN_MCo403fOvqapKi_WYQli9AkDFAk4TDB5XpbJ8js,1661 +pandas/tests/indexing/test_indexing.py,sha256=WmiWSmvp5BTP8fJvYz8pYJ4TUZVUS9rkd4hj6hzZLFk,40123 +pandas/tests/indexing/test_loc.py,sha256=2-XFvrBo7IdCx8lUU9lQnKfaNZnuU-iO3SfDogORDpo,121267 +pandas/tests/indexing/test_na_indexing.py,sha256=Ek_7A7ctm_WB-32NePbODbQ5LDMZBAmCvDgPKbIUOcg,2322 +pandas/tests/indexing/test_partial.py,sha256=asE_jBG-hieXfCmExu3scGpJgtJuSb07FHkPNFqojp8,25088 +pandas/tests/indexing/test_scalar.py,sha256=BuLsr0F1OA4IeA816BzuLFiSNGppPoALpieV2_8Nfg8,9643 +pandas/tests/interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/interchange/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/interchange/__pycache__/test_impl.cpython-312.pyc,, +pandas/tests/interchange/__pycache__/test_spec_conformance.cpython-312.pyc,, +pandas/tests/interchange/__pycache__/test_utils.cpython-312.pyc,, +pandas/tests/interchange/test_impl.py,sha256=bZd6UAQeRFlo067t7w0P0w7vNyMNv-p98sFNChcjar0,20214 +pandas/tests/interchange/test_spec_conformance.py,sha256=JnE2kQOLr4EjUCH6Nzc1fCEXhbZ52WzKbioW6f6EVxo,5593 +pandas/tests/interchange/test_utils.py,sha256=15liIDJirQDoP7TxxQkmZJ9gCAVNCd2BwShW_GlwL2A,2965 +pandas/tests/internals/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/internals/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/internals/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/internals/__pycache__/test_internals.cpython-312.pyc,, +pandas/tests/internals/__pycache__/test_managers.cpython-312.pyc,, +pandas/tests/internals/test_api.py,sha256=7s-n3jyp-e0ikVxkIqxf3xRtxk3aBV4h5FsnMIcStMY,2166 +pandas/tests/internals/test_internals.py,sha256=2Lo6SX0HQSCiFuSRm-5-pqJWC3rJovjFsn5NuiAO_qE,49639 +pandas/tests/internals/test_managers.py,sha256=uIuBmkOCjbFuGGNOodZ7ITijw4CfsG4aOUqRLCEfg-s,3556 +pandas/tests/io/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/io/__pycache__/generate_legacy_storage_files.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_clipboard.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_common.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_compression.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_feather.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_fsspec.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_gbq.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_gcs.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_html.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_http_headers.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_orc.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_parquet.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_pickle.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_s3.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_spss.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_sql.cpython-312.pyc,, +pandas/tests/io/__pycache__/test_stata.cpython-312.pyc,, +pandas/tests/io/conftest.py,sha256=hGdKIxz9wKnphU200sfKZKe2FBKwcd3x3BSvlFrDOHU,6041 +pandas/tests/io/excel/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/excel/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_odf.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_odswriter.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_openpyxl.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_readers.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_style.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_writers.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_xlrd.cpython-312.pyc,, +pandas/tests/io/excel/__pycache__/test_xlsxwriter.cpython-312.pyc,, +pandas/tests/io/excel/test_odf.py,sha256=DoE6DfjKkIKGJtRUG8uvBNNGBOvoqVZnL8Jr_I1vOLQ,1999 +pandas/tests/io/excel/test_odswriter.py,sha256=2SmPARRnXiOAstiUaEFaVfGu2kVQ5vVHGODlozrlUFI,3268 +pandas/tests/io/excel/test_openpyxl.py,sha256=wnADQLARvjB4BMYgd2fMs5jsvYm8DQvqFngJVnhSH1Q,15227 +pandas/tests/io/excel/test_readers.py,sha256=UEWss38RW7dRAkAqAiHNdQMQCXr5XYOiR5p2pG8feeg,62778 +pandas/tests/io/excel/test_style.py,sha256=mQ7roFc4ZfBfrjc4Das0lNnYXIcV1cO1AOuXVRw1Dqw,11284 +pandas/tests/io/excel/test_writers.py,sha256=FTFRB9-fV6m9INqiysVkZtUTHvxphDJ4bvxk4rkFZw0,54972 +pandas/tests/io/excel/test_xlrd.py,sha256=e5QrByVFVm6rEZbdSifYBBCY-czTzWZZ5y7OyfrPksw,1977 +pandas/tests/io/excel/test_xlsxwriter.py,sha256=DUmibvRcUD6O2OcD_YcMymQPvMgkckIH92NjYsamyOE,2773 +pandas/tests/io/formats/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/formats/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_console.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_css.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_eng_formatting.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_format.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_ipython_compat.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_printing.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_to_csv.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_to_excel.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_to_html.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_to_latex.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_to_markdown.cpython-312.pyc,, +pandas/tests/io/formats/__pycache__/test_to_string.cpython-312.pyc,, +pandas/tests/io/formats/style/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/formats/style/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_bar.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_exceptions.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_format.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_highlight.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_html.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_matplotlib.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_non_unique.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_style.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_to_latex.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_to_string.cpython-312.pyc,, +pandas/tests/io/formats/style/__pycache__/test_tooltip.cpython-312.pyc,, +pandas/tests/io/formats/style/test_bar.py,sha256=E07H6L-Sa3sgEGzy2oGnuZCs24P-HtsjSUDAk-G5jAM,12049 +pandas/tests/io/formats/style/test_exceptions.py,sha256=qm62Nu_E61TOrGXzxMSYm5Ciqm7qKhCFaTDP0QJmjJo,1002 +pandas/tests/io/formats/style/test_format.py,sha256=9siaXSHvCrA-YEuRI0-zun0gwQf2fVZwSPMIrb7CLTE,21154 +pandas/tests/io/formats/style/test_highlight.py,sha256=p2vRhU8aefAfmqLptxNO4XYbrVsccERvFQRd1OowC10,7003 +pandas/tests/io/formats/style/test_html.py,sha256=FvW0Zh6U8CkOKo0Plvz8W-udOgsczg9qawyVq-xzKqc,32702 +pandas/tests/io/formats/style/test_matplotlib.py,sha256=KPTvs_DbJlT5u7xQiQW3Ct-0jmpFHuah_lfQgZkiuQw,11649 +pandas/tests/io/formats/style/test_non_unique.py,sha256=JG_rE5A5Zk5exlfivZHnOI3Upzm8dJjmKKHkwEje4LQ,4366 +pandas/tests/io/formats/style/test_style.py,sha256=x7r8-nhnYdifw_PjopT0a4t99MTGzlOBv-g38HOHxik,58095 +pandas/tests/io/formats/style/test_to_latex.py,sha256=EbsBCluJ-2eVLSxXHgLo6Uus6VsnrbzqO9sYaRuewgs,33008 +pandas/tests/io/formats/style/test_to_string.py,sha256=w1GvLm3FtKQd9t2nwN3vF55X5f0GQKGCGXpYFZxITpA,1910 +pandas/tests/io/formats/style/test_tooltip.py,sha256=GMqwXrXi9Ppp0khfZHEwgeRqahwju5U2iIhZan3ndZE,2899 +pandas/tests/io/formats/test_console.py,sha256=jAk1wudhPiLBhhtydTNRlZ43961LqFu3uYt6cVA_jV0,2435 +pandas/tests/io/formats/test_css.py,sha256=YFHK3UFe2jcnz6AhmOFb7ZU1jd5Y_LYxIx5PBrJXNLQ,8669 +pandas/tests/io/formats/test_eng_formatting.py,sha256=QqFZJMUBVnU5SpZB63tCOHX3CqZbjgesOZc6nxbhp4c,8454 +pandas/tests/io/formats/test_format.py,sha256=ln-Q4RriF9nAh6xe8oyJMUXxFS0ZBRjItyukl5vbGLs,83129 +pandas/tests/io/formats/test_ipython_compat.py,sha256=pRAOUIZ3Vsb2LVYywzk30d834GzqLH9N8kjTGlf2MXc,3055 +pandas/tests/io/formats/test_printing.py,sha256=hLBoT3FE7J2VjxCJIAS_N24g6pMoQcyQphGTnwt0Ehc,4499 +pandas/tests/io/formats/test_to_csv.py,sha256=mThYTrnKefL4fWiqsLmJP9nsJcKx9ejdPNXndW6ADzo,27541 +pandas/tests/io/formats/test_to_excel.py,sha256=ecNeSrVd2mSPsdIqm3lM911b4mPwLIVkoz3MnJFZE3g,15320 +pandas/tests/io/formats/test_to_html.py,sha256=elbKQSMvV8p3qWEFVFA_nneSjdXl432QYDlha1cGVGw,38699 +pandas/tests/io/formats/test_to_latex.py,sha256=xxVzNxFQ6D824p0FRJ5Gu5UqSPPwvUwAnmt6rIiAqmE,41622 +pandas/tests/io/formats/test_to_markdown.py,sha256=2DUY7KrRVUu_OU6q4biW8rNFEINN6fPSkqs8VzY8rlE,2757 +pandas/tests/io/formats/test_to_string.py,sha256=IJR-u9WLmPTMltFqZSFnIZX3FAmmNj0I3wPij6UlbdM,39355 +pandas/tests/io/generate_legacy_storage_files.py,sha256=arKCOsudw84kCaRY8gxmtsgS1B0hYZrtrG_1wfl9YOc,10247 +pandas/tests/io/json/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/json/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_compression.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_deprecated_kwargs.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_json_table_schema.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_json_table_schema_ext_dtype.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_normalize.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_pandas.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_readlines.cpython-312.pyc,, +pandas/tests/io/json/__pycache__/test_ujson.cpython-312.pyc,, +pandas/tests/io/json/conftest.py,sha256=Zp83o90PvZ56MbhNRr1NZEPTpho7jRHcLYiEA9R_BZw,205 +pandas/tests/io/json/test_compression.py,sha256=PNaQlGwVdCL8K6ujRinmALn9O28tNZbxgelGcK-6MSo,4506 +pandas/tests/io/json/test_deprecated_kwargs.py,sha256=DKuEh2V2IkJOu-BnurWvax8Mq5EcQHtG-K-zncGZRpo,690 +pandas/tests/io/json/test_json_table_schema.py,sha256=Bl1IHG8QmHW32edobvKflEC4VxJ-mYiW6745YbQAir4,30672 +pandas/tests/io/json/test_json_table_schema_ext_dtype.py,sha256=v8ynj1IQWGM15kL48VJc9iRJeH4WeXsKBq9sy4fzeo8,9515 +pandas/tests/io/json/test_normalize.py,sha256=eOQoJQBGjAqFcswdNBipHoGMGBgLiwLFNIzTuZ5XSkI,30816 +pandas/tests/io/json/test_pandas.py,sha256=Pj7sFTAbRRwams8VLREUU7_Ui3GSgze6hI-K52YEbU8,77668 +pandas/tests/io/json/test_readlines.py,sha256=NaIeCB9w7iM_Ptamx4IoLMRwIG9eUQxsTJpU2cBB5y0,18819 +pandas/tests/io/json/test_ujson.py,sha256=UYh87hxO7ySZ60Q8ycDjbEqzcbBD51mV9qIlMCDA_Fc,36424 +pandas/tests/io/parser/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_c_parser_only.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_comment.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_compression.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_concatenate_chunks.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_converters.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_dialect.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_encoding.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_header.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_index_col.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_mangle_dupes.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_multi_thread.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_na_values.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_network.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_parse_dates.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_python_parser_only.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_quoting.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_read_fwf.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_skiprows.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_textreader.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_unsupported.cpython-312.pyc,, +pandas/tests/io/parser/__pycache__/test_upcast.cpython-312.pyc,, +pandas/tests/io/parser/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/common/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_chunksize.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_common_basic.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_data_list.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_decimal.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_file_buffer_url.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_float.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_index.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_inf.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_ints.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_iterator.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_read_errors.cpython-312.pyc,, +pandas/tests/io/parser/common/__pycache__/test_verbose.cpython-312.pyc,, +pandas/tests/io/parser/common/test_chunksize.py,sha256=X2yrC5STddTg8ITNYdjFb2ZvGZNsQ2kGaQvFysmrmz0,11287 +pandas/tests/io/parser/common/test_common_basic.py,sha256=EgyGjcaLEPflKhC54NGwZB89bpRaOwqd9asreeojAdk,31043 +pandas/tests/io/parser/common/test_data_list.py,sha256=XTWzTbtaLRGFdrjfRTJH3TTedD8Y0uCWRzji1qnrdk4,2228 +pandas/tests/io/parser/common/test_decimal.py,sha256=6WZy1C7G2vNpSo165GZAoRFGiy9OMgKygAIEYNalQ-Y,1932 +pandas/tests/io/parser/common/test_file_buffer_url.py,sha256=4PbVEGwOYJh5z7ht6kgn2tdHv0F9eSEjT8Wi6dMeoaQ,13951 +pandas/tests/io/parser/common/test_float.py,sha256=5XM0Cndv31L4_7ER2MOB-Bnk9_GELTpakFp1-dNRjyM,2582 +pandas/tests/io/parser/common/test_index.py,sha256=on6ur2EUBnLPqhb8w-8KgASkETTSarsQf8zOUuRU7mQ,8269 +pandas/tests/io/parser/common/test_inf.py,sha256=yXUF6DrDhiPKEfEXJLnb71bZnycbo4CKXkl14Vyv3QY,2114 +pandas/tests/io/parser/common/test_ints.py,sha256=K49T03jXs77ktsxIFFQqBisPI3z042A8GATZcn1Tq44,7243 +pandas/tests/io/parser/common/test_iterator.py,sha256=FljWxY67UNOCedqg_as_nY4GtkU4HDwqwgpLkxU00Aw,3702 +pandas/tests/io/parser/common/test_read_errors.py,sha256=Aas1e5CM0ohMBXNQ2tSZao7jZbWTk9LA85FglJ8CRLE,9592 +pandas/tests/io/parser/common/test_verbose.py,sha256=kil5N51khhQifV9az-x2ijMr3wGtddKrU5oAbr0b1hs,2339 +pandas/tests/io/parser/conftest.py,sha256=JVRpaE0BXy7SZIN3Af0x7vvoqsZhAR-aVRU5QC0tAho,9144 +pandas/tests/io/parser/dtypes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/dtypes/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/parser/dtypes/__pycache__/test_categorical.cpython-312.pyc,, +pandas/tests/io/parser/dtypes/__pycache__/test_dtypes_basic.cpython-312.pyc,, +pandas/tests/io/parser/dtypes/__pycache__/test_empty.cpython-312.pyc,, +pandas/tests/io/parser/dtypes/test_categorical.py,sha256=H8HO6IYwkJryJV87hKep0rtyx4XmXAHh1ICuprkmYjM,9836 +pandas/tests/io/parser/dtypes/test_dtypes_basic.py,sha256=Q1WorhNT3B9pC5I6iqL62bUOkFEw3B1crPBJsHUsZjY,18821 +pandas/tests/io/parser/dtypes/test_empty.py,sha256=bFuG8P_48stM0rEB8J0pF-sRl3kezS-9wB3fycgCjFo,5258 +pandas/tests/io/parser/test_c_parser_only.py,sha256=CmyzHEkAccoHIvd1rShqZwaxqcUE-cC5eq6nm0GyPlY,20721 +pandas/tests/io/parser/test_comment.py,sha256=QO0E262p5tnOpm9oxqTO1rwl0KU-mKMP_jydlahyFMM,7560 +pandas/tests/io/parser/test_compression.py,sha256=hW1GxllxvM8sUQhmTVibkkqdj0JcAAR9b7nKCxuXblk,6403 +pandas/tests/io/parser/test_concatenate_chunks.py,sha256=RD1MUklgLBtBNvJu5J92cVZbrO3n38UzdQvh4BAvAqI,1128 +pandas/tests/io/parser/test_converters.py,sha256=orNhBxEjmQ8N6J-ERcprjtW24INL1yQwD9FyQWoD8W8,7437 +pandas/tests/io/parser/test_dialect.py,sha256=tgsdnhEkYBtjIKd-9BKAyQ8ATTSivnzIkiWiuLi513M,5844 +pandas/tests/io/parser/test_encoding.py,sha256=Og-q60V-nd-8xl5VBWDPtYqxGeemrs8rYCoCCWKdjmc,10782 +pandas/tests/io/parser/test_header.py,sha256=zvSu-S51vJaIGPOdZgdC2IeHd2Y_1FTId-QGJc_7BWU,21029 +pandas/tests/io/parser/test_index_col.py,sha256=5iKYLUProGUcrw-dUZgrt_6VagzsOp_K9TroSX7FLEk,11514 +pandas/tests/io/parser/test_mangle_dupes.py,sha256=sK5nKy43zOyORKabRypzh0iTz7JLpd2rCFWCEmApM70,5440 +pandas/tests/io/parser/test_multi_thread.py,sha256=x40FWVAiCprn9T83Tu7cVaiUcGIcSSOgp7lauIUsdjo,4315 +pandas/tests/io/parser/test_na_values.py,sha256=IWNdqBlWB0nkgXoQF8lPs2Mcn7uoOBCCgfkTh5u68ns,22460 +pandas/tests/io/parser/test_network.py,sha256=8bNvzZHJ6r_m1WEJ7qt6fZtUbxLkxWP_aGqGnrtk_Po,12319 +pandas/tests/io/parser/test_parse_dates.py,sha256=o0-4VDf5XD2KK_MP-OcLhNgQ2GZ3DYh67l3_kohVoGs,69728 +pandas/tests/io/parser/test_python_parser_only.py,sha256=kMe1FjsvSkdP6j-Yg8_MUsqXoE9QPAzZczH_xoA67PY,15979 +pandas/tests/io/parser/test_quoting.py,sha256=IFsX5BhGI4JwGQUkyyztbp_UJq0gDP9aylvigGrc2V8,6540 +pandas/tests/io/parser/test_read_fwf.py,sha256=uYXrP1lpAQS-y7auRDgEYxEXTUk3mUUfJPccmdL4ZPg,29873 +pandas/tests/io/parser/test_skiprows.py,sha256=D0dm01x-53YqSXXvj1jczRV5SWEDNkNP87tquehyn9w,9457 +pandas/tests/io/parser/test_textreader.py,sha256=R_yeB-k6g45i6ZTQ-PdF8DIJYdodhH059OGrRdM8IOM,10672 +pandas/tests/io/parser/test_unsupported.py,sha256=149HYApTOEJP9xEXuXuncyS2zq_lpF_AyBfu_SIjjes,7986 +pandas/tests/io/parser/test_upcast.py,sha256=XEjHUvgExlKwxTCSjSfWMxjwge0HeW9q2BMIQGuxfTk,3141 +pandas/tests/io/parser/usecols/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/parser/usecols/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/parser/usecols/__pycache__/test_parse_dates.cpython-312.pyc,, +pandas/tests/io/parser/usecols/__pycache__/test_strings.cpython-312.pyc,, +pandas/tests/io/parser/usecols/__pycache__/test_usecols_basic.cpython-312.pyc,, +pandas/tests/io/parser/usecols/test_parse_dates.py,sha256=7PYxerT3Eok6kVV6dfU2e-qlBpde-gfCGMg1NEht8cM,5469 +pandas/tests/io/parser/usecols/test_strings.py,sha256=-ZUBWSpxMgoxqRfGAa0mgb5motUoKveF06V9LUH-nQg,2588 +pandas/tests/io/parser/usecols/test_usecols_basic.py,sha256=BKr0EIu8g1aLiF6a_g61zF2NHPVY8Cl6CRcNnHLQ_4o,17646 +pandas/tests/io/pytables/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/pytables/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/common.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_append.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_categorical.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_compat.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_complex.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_errors.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_file_handling.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_keys.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_put.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_pytables_missing.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_read.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_retain_attributes.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_round_trip.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_select.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_store.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_subclass.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_time_series.cpython-312.pyc,, +pandas/tests/io/pytables/__pycache__/test_timezones.cpython-312.pyc,, +pandas/tests/io/pytables/common.py,sha256=m3IH26TCzLDpS8ctvzJKLA8x414ur5jlX3sdT4sB4m8,1264 +pandas/tests/io/pytables/conftest.py,sha256=vQgspEHypJUvbAU3P0I5BDBW2vRK4CgmcNqY5ZXksns,136 +pandas/tests/io/pytables/test_append.py,sha256=lT_tan65e42PSG7M7LVZvjx85iShUYCfYrBo0bIFEmQ,37420 +pandas/tests/io/pytables/test_categorical.py,sha256=TYTP10caIxfERCGETR5mYHxCim-BSLda6BbpJxL8b-4,6996 +pandas/tests/io/pytables/test_compat.py,sha256=qsaDgIDMQOOMA_ZYv7r9r9sBUUbA9Fe2jb2j8XAeY_s,2547 +pandas/tests/io/pytables/test_complex.py,sha256=CUEEEU3zJh6pmj-gws7ahyhsHJTxO0W9MKraXeFg89A,5948 +pandas/tests/io/pytables/test_errors.py,sha256=9d7ko8t8HCOBUfVD0vKO-xxOuzClCMSRjzDncrO8EU0,8549 +pandas/tests/io/pytables/test_file_handling.py,sha256=PKkJkwDY1FKumbziLxxNN_TeqjldQHxic54d1_h-V5k,15572 +pandas/tests/io/pytables/test_keys.py,sha256=m7SyZ2O_KPSCIl1yofM6QTOwQHneHymz8RgrDDa0IOQ,2673 +pandas/tests/io/pytables/test_put.py,sha256=SIDAxDDn1B1hPE9-TW92BzlB1SPhLSCu3e0G9l5CCmE,14053 +pandas/tests/io/pytables/test_pytables_missing.py,sha256=mK_l-tuF_TeoK4gZqRncm-FCe2PUgk2AS3q6q0M1YIU,345 +pandas/tests/io/pytables/test_read.py,sha256=RS9j9Dy_KOPZcp3Su6tqGxCSOfHLUKIGeyhYeDk5KiU,13520 +pandas/tests/io/pytables/test_retain_attributes.py,sha256=WY5rbnlT_NqERl4OSJ9C2iWLtFpZZCW57iNiF-UbZDM,2970 +pandas/tests/io/pytables/test_round_trip.py,sha256=IlqLWUdnD4c29oPEELeoKH7chMsl28XQtUh38k9qZzM,18936 +pandas/tests/io/pytables/test_select.py,sha256=gYDOGDi9srGKY7-d-8RvjVYV0A-5jpEkd9GtVNcSrhY,36832 +pandas/tests/io/pytables/test_store.py,sha256=Gbnlaee0d720CtnIxUm5togcE_qkYgru6ThLkPYF2lA,37523 +pandas/tests/io/pytables/test_subclass.py,sha256=fgiunpfa4hECpAXsZrq4nB1a1z5txJxEj9MqyOBI3fQ,1369 +pandas/tests/io/pytables/test_time_series.py,sha256=hduw-GMBvahyZHh6JVrLKrxvU3NR0vl0cWTWamlgZw4,2481 +pandas/tests/io/pytables/test_timezones.py,sha256=3wUurqaoR-UdgndFKyPxmluEzl4euTPBFDcL6nV2IqM,11804 +pandas/tests/io/sas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/sas/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/sas/__pycache__/test_byteswap.cpython-312.pyc,, +pandas/tests/io/sas/__pycache__/test_sas.cpython-312.pyc,, +pandas/tests/io/sas/__pycache__/test_sas7bdat.cpython-312.pyc,, +pandas/tests/io/sas/__pycache__/test_xport.cpython-312.pyc,, +pandas/tests/io/sas/test_byteswap.py,sha256=fIqzF9LZs3TLm7JI4tEk4JxkynmWqZ5TydCmc12sGQs,1987 +pandas/tests/io/sas/test_sas.py,sha256=M9OeR39l3-DGJSBr84IVmnYMpMs_3xVfCgSSR8u7m-k,1057 +pandas/tests/io/sas/test_sas7bdat.py,sha256=Rrn8lpz3mzmrF-l5p4LhXKpMnUgX8d1X5OsTYHnh2vw,14942 +pandas/tests/io/sas/test_xport.py,sha256=-gNRR9_2QZS2dQ7Zu756Omg5Bpaz-2I5nCovqEqJVwU,5728 +pandas/tests/io/test_clipboard.py,sha256=0VmCX6RFBDGCuXanRJ5rWHf6T781edTLpgnKMTD_DtU,13092 +pandas/tests/io/test_common.py,sha256=H-eQmvCPWIbBm1C2uQfZ6XAm9m2z0HNAtC_xah5j6QY,23849 +pandas/tests/io/test_compression.py,sha256=P4xMmSJ5vv4A1xj6VnShtftj0-eDXv9_Lq67RveZQ2s,12259 +pandas/tests/io/test_feather.py,sha256=czpkrEup3qADg7PgKAC_9wegBlv55a-76gJMm0L4Z_A,10210 +pandas/tests/io/test_fsspec.py,sha256=6WW0sO9flDQSnSAiqQyAb-PgyccS2l1emacL9QnyGl8,10547 +pandas/tests/io/test_gbq.py,sha256=9tA62qL0uGbSKMZdxMwNjANpxaNB4buEdKfqAQej0HQ,401 +pandas/tests/io/test_gcs.py,sha256=xvRhJDVYU7jMrbpYGmzkLW4VoIugwgjLqOgBKnEFcSk,7334 +pandas/tests/io/test_html.py,sha256=2ldWTDWQO1w-QofitXU8PDNjghiCn9cSJSSDuDEM9WU,56525 +pandas/tests/io/test_http_headers.py,sha256=PvNDukQ37JbZj8jKispzfmJRkfnGdFxzprj0ckuaT-o,4885 +pandas/tests/io/test_orc.py,sha256=dBeiHQhMqEDphbtxEDVlrW2-CNJiRh-Bpk2KZk4-t0Q,14261 +pandas/tests/io/test_parquet.py,sha256=WCqkmQHpru8iz9_6SJ4Wgw3nMrxdCeqb7VbztS9Cj-8,53124 +pandas/tests/io/test_pickle.py,sha256=2I56KjtjujGOA3w7woPDNNcTDc7HuQZr0TMBApDbj6Q,20949 +pandas/tests/io/test_s3.py,sha256=vLi6EkvAGMKudRcbxcosxHV7z_q6GbknZuYdEisHjy4,1181 +pandas/tests/io/test_spss.py,sha256=9ITQlg0e6JZ7Kkg5S7HN-cvdt2o2_KYG7qZ9lrHckhk,6432 +pandas/tests/io/test_sql.py,sha256=5xLp3y79QHuG2d339XAd0qZvz6fd0rph2C6yBhgpD2Y,144483 +pandas/tests/io/test_stata.py,sha256=-_rvlVopGVooActyZuoQzl9cqVQko_XVoD92TGYX3zk,92899 +pandas/tests/io/xml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/io/xml/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/io/xml/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/io/xml/__pycache__/test_to_xml.cpython-312.pyc,, +pandas/tests/io/xml/__pycache__/test_xml.cpython-312.pyc,, +pandas/tests/io/xml/__pycache__/test_xml_dtypes.cpython-312.pyc,, +pandas/tests/io/xml/conftest.py,sha256=ex3IgyE-7MBC_y5T2gJphlfUex7nqRG5VfX62mTbe5E,850 +pandas/tests/io/xml/test_to_xml.py,sha256=IxG7rT8KV0BghiUMvVMyd5GkbDR9xqWSmSDqT3CUAKM,35612 +pandas/tests/io/xml/test_xml.py,sha256=PjUkQVamI9Q4Cl7wRfBnyThppHURy01jJU1fINzPEKE,60641 +pandas/tests/io/xml/test_xml_dtypes.py,sha256=z8unMuhwvcrDUQ-7j4PBKBzr55QXNprA7qALGW7vYw0,13266 +pandas/tests/libs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/libs/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/libs/__pycache__/test_hashtable.cpython-312.pyc,, +pandas/tests/libs/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/libs/__pycache__/test_lib.cpython-312.pyc,, +pandas/tests/libs/__pycache__/test_libalgos.cpython-312.pyc,, +pandas/tests/libs/test_hashtable.py,sha256=4rXFphd6C9bf5AVIqOohTwsJ7mA14SZmq3hcWtC7m-w,26091 +pandas/tests/libs/test_join.py,sha256=z5JeLRMmF_vu4wwOpi3cG6k-p6lkhjAKPad6ShMqS30,10811 +pandas/tests/libs/test_lib.py,sha256=ToabC3h3DJGZ1xoTjwHy9P752nrdSovxlJsGMyEqjVg,11066 +pandas/tests/libs/test_libalgos.py,sha256=saDyCbchGU690HmrfZUJ6q1iCLNeW4x50Y-A2o1fgrg,5322 +pandas/tests/plotting/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/plotting/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/common.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_backend.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_boxplot_method.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_common.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_converter.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_datetimelike.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_groupby.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_hist_method.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_misc.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_series.cpython-312.pyc,, +pandas/tests/plotting/__pycache__/test_style.cpython-312.pyc,, +pandas/tests/plotting/common.py,sha256=6oADaI21vWLSPgHVqckoLiPFWsrGXw71fel7HHxJyZc,16871 +pandas/tests/plotting/conftest.py,sha256=WGxjahxQkw-Gk4DlnLW0rDsei0dmuoCuZusNMepwty0,1531 +pandas/tests/plotting/frame/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/plotting/frame/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame.cpython-312.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_color.cpython-312.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_groupby.cpython-312.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_legend.cpython-312.pyc,, +pandas/tests/plotting/frame/__pycache__/test_frame_subplots.cpython-312.pyc,, +pandas/tests/plotting/frame/__pycache__/test_hist_box_by.cpython-312.pyc,, +pandas/tests/plotting/frame/test_frame.py,sha256=BcGzSi6p1RSFhJeudyFanYfKYjvvuS7eKSolRO3afCg,99390 +pandas/tests/plotting/frame/test_frame_color.py,sha256=gBkX_6DMH-joE-4GjwZpIYgWHJkrWPPDJ8R9gKuHqH8,28488 +pandas/tests/plotting/frame/test_frame_groupby.py,sha256=JNd4J9E4BEtcU5ed47_SZK5p77P6vthENn_shRPbAJQ,2547 +pandas/tests/plotting/frame/test_frame_legend.py,sha256=10NvOjyNdV703r-9mLhYXIxeyZJFq_-24N9XNkNReJw,10443 +pandas/tests/plotting/frame/test_frame_subplots.py,sha256=kRVFvweJSAwzh9gNIzoifuy6_U2d9mZ-K7zXR_K5otw,28986 +pandas/tests/plotting/frame/test_hist_box_by.py,sha256=8jqVQfLrE5AKvn7iKMX7L5Gbe7e4rv6Ic8MnNp7NALI,10969 +pandas/tests/plotting/test_backend.py,sha256=rE7SNyeJiSUOWwkvxndq3qtpUEOYkUetCwdO_ey-eWM,3382 +pandas/tests/plotting/test_boxplot_method.py,sha256=fxvMv2V5JHPQg1uJZFNXCsMJwnUOufLEkOZK8XboR58,30159 +pandas/tests/plotting/test_common.py,sha256=if9WnxryRdUhub-3yjdTEKO2PME-Yhf5YIG8e2nvAXU,1869 +pandas/tests/plotting/test_converter.py,sha256=pC3IZ6pfKITbmzTZBwoPwG1abGtPT6Sp1YLMuKLDKG8,13251 +pandas/tests/plotting/test_datetimelike.py,sha256=Jvsqdvr_SKrdzgRYwoTlNJeS_NWMSTD183sQF-lQMAs,66544 +pandas/tests/plotting/test_groupby.py,sha256=mcM2bOmfvJteLz9H0qMawxN3Yef-Nj2zCa_MUUBWF_c,5735 +pandas/tests/plotting/test_hist_method.py,sha256=2Rkk6DlGz9I4rXDjs6qBrZiRvUNWiBDCIKk44m0mrxw,34972 +pandas/tests/plotting/test_misc.py,sha256=_IoHRNT_OSGTyFfIu5giv5BnaUFWENQH36VKN8q32tI,25201 +pandas/tests/plotting/test_series.py,sha256=73VoBpLMLjKHwIaZKM50rGpOSx1kBsCxlxxNSsPwh8k,35318 +pandas/tests/plotting/test_style.py,sha256=3YMcq45IgmIomuihBowBT-lyJfpJR_Q8fbMOEQXUkao,5172 +pandas/tests/reductions/__init__.py,sha256=vflo8yMcocx2X1Rdw9vt8NpiZ4ZFq9xZRC3PW6Gp-Cs,125 +pandas/tests/reductions/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/reductions/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/reductions/__pycache__/test_stat_reductions.cpython-312.pyc,, +pandas/tests/reductions/test_reductions.py,sha256=ALTUdj4Dw0eyrU2tTHr8qaeHqNfLeqEB7lsef-HjKBE,59096 +pandas/tests/reductions/test_stat_reductions.py,sha256=Q-sfitViCm3-oQQVHWDwjKKia1ZuUX6079cGmv3i3oU,9722 +pandas/tests/resample/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/resample/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/resample/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/resample/__pycache__/test_base.cpython-312.pyc,, +pandas/tests/resample/__pycache__/test_datetime_index.cpython-312.pyc,, +pandas/tests/resample/__pycache__/test_period_index.cpython-312.pyc,, +pandas/tests/resample/__pycache__/test_resample_api.cpython-312.pyc,, +pandas/tests/resample/__pycache__/test_resampler_grouper.cpython-312.pyc,, +pandas/tests/resample/__pycache__/test_time_grouper.cpython-312.pyc,, +pandas/tests/resample/__pycache__/test_timedelta.cpython-312.pyc,, +pandas/tests/resample/conftest.py,sha256=XXj72zj-3AH2jPBUacVV6GSpY9Y4in_38g8cSf8UfYg,3355 +pandas/tests/resample/test_base.py,sha256=h9icUuaLYD0JRpICdBEE7sZem5UXJ0lS3L1BbfywzG4,13762 +pandas/tests/resample/test_datetime_index.py,sha256=afIwoNQkATamYQPvGHc58QhGiWXpaJS2qu8Yt4LKllA,74234 +pandas/tests/resample/test_period_index.py,sha256=rp1ogpWfYMS-xxz98abR_7JZkuFOebvCJPc1c4xptT8,41199 +pandas/tests/resample/test_resample_api.py,sha256=dQxrmryu6D4qHKyqflxYjofEooz6xXB9rjntuQgIe4Q,34616 +pandas/tests/resample/test_resampler_grouper.py,sha256=iZunzxnP3qB8t7jcCcmOYBB20ciH_fVp7rY5t4ADUaE,23938 +pandas/tests/resample/test_time_grouper.py,sha256=T8O-K63k5XzECD-6tBDsqkzCnVb-cR_X0d_HKZPDOus,11832 +pandas/tests/resample/test_timedelta.py,sha256=H_ZjEJhXN6fhWbpwEwuPsxFDWQermDwUvsM7oaE2pG0,7469 +pandas/tests/reshape/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/reshape/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_crosstab.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_cut.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_from_dummies.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_get_dummies.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_melt.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_pivot.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_pivot_multilevel.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_qcut.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_union_categoricals.cpython-312.pyc,, +pandas/tests/reshape/__pycache__/test_util.cpython-312.pyc,, +pandas/tests/reshape/concat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/reshape/concat/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_append.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_append_common.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_categorical.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_concat.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_dataframe.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_datetimes.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_empty.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_index.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_invalid.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_series.cpython-312.pyc,, +pandas/tests/reshape/concat/__pycache__/test_sort.cpython-312.pyc,, +pandas/tests/reshape/concat/conftest.py,sha256=s94n_rOGHsQKdP2KbCAQEfZeQpesYmhH_d-RNNTkvYc,162 +pandas/tests/reshape/concat/test_append.py,sha256=mCBndbLvwmM8qTbwH7HoyZjFGLQWOsOMGjn1I1Mz8PA,14299 +pandas/tests/reshape/concat/test_append_common.py,sha256=Z2hBl4TyKpIJ-staPnWVmAbRMv9Wg0tQK_W8YpcIMXQ,27866 +pandas/tests/reshape/concat/test_categorical.py,sha256=TGmBQ_2bzyuDrijDJcCqOgCcIVKujynMAKNG9MYXPhQ,9491 +pandas/tests/reshape/concat/test_concat.py,sha256=wRvTAqUMfzv4fLatEDNk7W8oqvxt5MnDpwbipg5HHM4,32672 +pandas/tests/reshape/concat/test_dataframe.py,sha256=-vObBDtkJ7N_eeIFgjpOVVrMJf_bB9KKknHZg1DbG7k,8864 +pandas/tests/reshape/concat/test_datetimes.py,sha256=dZc65JXlR1l5ulBaQrVzkLv0z8LgwXBlrBFxOxRSBZk,21584 +pandas/tests/reshape/concat/test_empty.py,sha256=UVrgKBTL16wdXjJI5znbOdd2yVEJ5hdxGVOxoH3oMgA,10385 +pandas/tests/reshape/concat/test_index.py,sha256=B3cn9vzq8oumFE_M91KcyLnTb7ok4jiflzZHUJABthE,17395 +pandas/tests/reshape/concat/test_invalid.py,sha256=E7InfrzodepcICRP_zFyg11CMs-2SmNrxFY3f8bhqjA,1608 +pandas/tests/reshape/concat/test_series.py,sha256=af0lLNaUEvGml86Ziy-VLJt-wQ-rwQZuQoFROulm9Z8,6061 +pandas/tests/reshape/concat/test_sort.py,sha256=RuXIJduLa56IJDmUQaCwyYOz_U0KXMDWf04WEzi8y7E,4350 +pandas/tests/reshape/merge/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/reshape/merge/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/reshape/merge/__pycache__/test_join.cpython-312.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge.cpython-312.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_asof.cpython-312.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_cross.cpython-312.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_index_as_string.cpython-312.pyc,, +pandas/tests/reshape/merge/__pycache__/test_merge_ordered.cpython-312.pyc,, +pandas/tests/reshape/merge/__pycache__/test_multi.cpython-312.pyc,, +pandas/tests/reshape/merge/test_join.py,sha256=Fm_AUg0C7RPddejw-ZpOpKHE3ggutyXvJg-CdbjmcXs,37848 +pandas/tests/reshape/merge/test_merge.py,sha256=wOTlq12eFn-1nS5NaKs4HDXuART5tSnUKny-Xj8i8Gs,106343 +pandas/tests/reshape/merge/test_merge_asof.py,sha256=_4S4geWz_OqvhrR_2zcL7cGtkLpPDuanFR6vMJAIL-A,121465 +pandas/tests/reshape/merge/test_merge_cross.py,sha256=9BVH6HWJRh-dHKDTBy8Q2it97gjVW79FgPC99HNLIc4,3146 +pandas/tests/reshape/merge/test_merge_index_as_string.py,sha256=w_9BccpqfB7yPhy_TBlMGx2BPOBwPhfg-pYRKA4HEC8,5357 +pandas/tests/reshape/merge/test_merge_ordered.py,sha256=Y4GLA6hxUoUdo6XhJ5inFBf867JJ8XqiaMi7GY4tsNY,7731 +pandas/tests/reshape/merge/test_multi.py,sha256=kV5tUCNAljJ78IPNrhaeDX9AyKtN2KdF8ZpNMTeDyzY,31130 +pandas/tests/reshape/test_crosstab.py,sha256=fJTqrjVg45YUp8aPCcpgRzrNEoXibZIAz8Tmz2cTM7k,32578 +pandas/tests/reshape/test_cut.py,sha256=Gy0V1j0oxa_6fdlc5VxTzrqPDQMmlKIR6UbSrTYJXlg,24641 +pandas/tests/reshape/test_from_dummies.py,sha256=FDxrh7plJqD4XQO0-qX5Y9K_359Ld7EiwjLTYrOa5lo,13343 +pandas/tests/reshape/test_get_dummies.py,sha256=p52Tdo8-IokYJrogSz-ArG0phyBPQaf-ELS3dnpzPTs,27605 +pandas/tests/reshape/test_melt.py,sha256=oF90mvWtuli9SIZ4d1IVQu7kA4h2F4UHLPUykrvOISk,42675 +pandas/tests/reshape/test_pivot.py,sha256=3BkrRLVGpiBUXvbBRWxEpYCWWAvRcn54Ft70RAWKcRM,93813 +pandas/tests/reshape/test_pivot_multilevel.py,sha256=DYp3BZ0h80UEgqFs0sNVqnUWBWgYU4622wp62SdCDdI,7549 +pandas/tests/reshape/test_qcut.py,sha256=0XO-B9XmAGiWLhEFW8wujFo-VR1r62SZP7MT-DBz1VE,8477 +pandas/tests/reshape/test_union_categoricals.py,sha256=UvadOpYUCmkJ-cGmATHVBmVu8LajVsWjMlyS4rAI9hk,15301 +pandas/tests/reshape/test_util.py,sha256=mk60VTWL9YPWNPAmVBHwkOAOtrHIDU6L3EAnlasx6IQ,2897 +pandas/tests/scalar/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/scalar/__pycache__/test_na_scalar.cpython-312.pyc,, +pandas/tests/scalar/__pycache__/test_nat.cpython-312.pyc,, +pandas/tests/scalar/interval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/interval/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/scalar/interval/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/scalar/interval/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/scalar/interval/__pycache__/test_contains.cpython-312.pyc,, +pandas/tests/scalar/interval/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/scalar/interval/__pycache__/test_interval.cpython-312.pyc,, +pandas/tests/scalar/interval/__pycache__/test_overlaps.cpython-312.pyc,, +pandas/tests/scalar/interval/test_arithmetic.py,sha256=qrUOEDp9dOkOoEfuuUHhmzKTZuPbj727p2PxO1kgxxM,5937 +pandas/tests/scalar/interval/test_constructors.py,sha256=DI5iRKoIg51lI_-FysKQyyaJnwrd8CqLjk7b7iqFIp0,1599 +pandas/tests/scalar/interval/test_contains.py,sha256=MSjo5U7KLuqugnEtURC8znpldI3-cLIfXQlIhNvQLI4,2354 +pandas/tests/scalar/interval/test_formats.py,sha256=Ep7692gGQMdrYiCxxudqXX-CA6S1sO3L2P2I4NHIreo,344 +pandas/tests/scalar/interval/test_interval.py,sha256=W54SKFbFSlsvFwoXkNhb6JK52klz8is2ww2ZQ7AIjUs,2656 +pandas/tests/scalar/interval/test_overlaps.py,sha256=2FHG23scoclsfZZAngK9sesna_3xgbjgSKoUzlMxHro,2274 +pandas/tests/scalar/period/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/period/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/scalar/period/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/scalar/period/__pycache__/test_asfreq.cpython-312.pyc,, +pandas/tests/scalar/period/__pycache__/test_period.cpython-312.pyc,, +pandas/tests/scalar/period/test_arithmetic.py,sha256=YYt1270I1WxtnQqGck_49ECYtrpw__lX8qx8t-GuIZM,16775 +pandas/tests/scalar/period/test_asfreq.py,sha256=dbmg35zwFwPSiYR-5OuSA790slBEct8N6C1jkEXchBs,38445 +pandas/tests/scalar/period/test_period.py,sha256=AHqAY3fNfW8p4xUu4tS3muNg7ol8a751v7tYyi7srdo,40263 +pandas/tests/scalar/test_na_scalar.py,sha256=0t4r9nDTQtXUSeXRBxDfgWegznLM6TvMk2pK0gLScJc,7227 +pandas/tests/scalar/test_nat.py,sha256=pUhNNUxLBv4_D-l2tsHICFiT5ruDjvlj24oEkNZycxk,19972 +pandas/tests/scalar/timedelta/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timedelta/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/scalar/timedelta/__pycache__/test_timedelta.cpython-312.pyc,, +pandas/tests/scalar/timedelta/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timedelta/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/scalar/timedelta/methods/__pycache__/test_as_unit.cpython-312.pyc,, +pandas/tests/scalar/timedelta/methods/__pycache__/test_round.cpython-312.pyc,, +pandas/tests/scalar/timedelta/methods/test_as_unit.py,sha256=Ut-_d5xcdAq9eD5_dknpSsnhjndzRyilGuT7PxOYl5s,2518 +pandas/tests/scalar/timedelta/methods/test_round.py,sha256=kAqNhW8GJMKvaACF1b6eKhO9DOvYUJuRrMyoxG2-nHM,6338 +pandas/tests/scalar/timedelta/test_arithmetic.py,sha256=mYTdK4okwMitWPPh335LY3wzy5hXncEXPnxLd1XrDXA,38156 +pandas/tests/scalar/timedelta/test_constructors.py,sha256=49f8ARiuEAbImuDasW9-NowtijVRPyoY6ARtX6iuNnM,22433 +pandas/tests/scalar/timedelta/test_formats.py,sha256=_5svunXjM1H4X5tMqgT7aO9CoDR96XgybUYHXNdcyDo,4161 +pandas/tests/scalar/timedelta/test_timedelta.py,sha256=VAEnw5O0egqtlazzAy6oJkgFGHCKDXp3NwRyBEQ19as,23413 +pandas/tests/scalar/timestamp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timestamp/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_comparisons.cpython-312.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_timestamp.cpython-312.pyc,, +pandas/tests/scalar/timestamp/__pycache__/test_timezones.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/scalar/timestamp/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_as_unit.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_normalize.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_replace.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_round.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_timestamp_method.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_to_julian_date.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_to_pydatetime.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_convert.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_localize.cpython-312.pyc,, +pandas/tests/scalar/timestamp/methods/test_as_unit.py,sha256=Od0YhrglrVPaad4kzpjPKoVf-pBz0_lTbdaj7cpD7eU,2706 +pandas/tests/scalar/timestamp/methods/test_normalize.py,sha256=NMQXgPRwSB8Z8YtQLrU4qNbxhaq1InqKqwS8veJ_Cts,831 +pandas/tests/scalar/timestamp/methods/test_replace.py,sha256=JT-qoGosdZa0tgjg2AtKrniJnT6-o1YIXQrq-pFDL5E,7055 +pandas/tests/scalar/timestamp/methods/test_round.py,sha256=mA1FyUI8-J14yZ1Vf5Se0OeW2u4nv9-1s0r9eOmOxnE,13027 +pandas/tests/scalar/timestamp/methods/test_timestamp_method.py,sha256=JlFBfEixuZiw96lRZc88wXR9-5uOt74gBCUql321H6w,1017 +pandas/tests/scalar/timestamp/methods/test_to_julian_date.py,sha256=izPqS1f7lJ3Tqkiz65t3NjZqtgxu1_jbSg-LmZheiD4,810 +pandas/tests/scalar/timestamp/methods/test_to_pydatetime.py,sha256=duSR43OjYJiMOHjt7lLVrSdBZa74GQRqwJz5RPdbQ5M,2871 +pandas/tests/scalar/timestamp/methods/test_tz_convert.py,sha256=yw1GiCOn7F8ZDof9d7IvG6T28e6nsB-_XswfO0HN-Dc,1710 +pandas/tests/scalar/timestamp/methods/test_tz_localize.py,sha256=drtq_N4h6E-25vsQuJJO4Sc5dUXyCwIWTHM0ozIc8gI,12774 +pandas/tests/scalar/timestamp/test_arithmetic.py,sha256=4exZrHW0m6i4mCzKVFhehECC232IJYyc3IW1f-YzPbM,10852 +pandas/tests/scalar/timestamp/test_comparisons.py,sha256=zxzSqDtYxP7Fc4vXcIqxYq0Yg7KeKEdAn3iwbgAv-ns,10059 +pandas/tests/scalar/timestamp/test_constructors.py,sha256=LlD72eyf8hgSFc4ib-nYVLSMehFyPfEMHqsNwlOKYDk,39714 +pandas/tests/scalar/timestamp/test_formats.py,sha256=TKn4H02mIrLpoWm4YuDsA3gUy87bYVqNLu8SgnckZA0,6864 +pandas/tests/scalar/timestamp/test_timestamp.py,sha256=c0ZhIgkRq9JfpohnixtM-n2frtyF2fR2pnUFjFER8fY,31042 +pandas/tests/scalar/timestamp/test_timezones.py,sha256=dXCPtLiGfQ9B2pg_s_YK7fvWwUW-CbVOPYUn9paFosk,666 +pandas/tests/series/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/series/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_arithmetic.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_constructors.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_cumulative.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_formats.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_iteration.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_logical_ops.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_missing.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_npfuncs.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_reductions.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_subclass.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_ufunc.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_unary.cpython-312.pyc,, +pandas/tests/series/__pycache__/test_validate.cpython-312.pyc,, +pandas/tests/series/accessors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/series/accessors/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/series/accessors/__pycache__/test_cat_accessor.cpython-312.pyc,, +pandas/tests/series/accessors/__pycache__/test_dt_accessor.cpython-312.pyc,, +pandas/tests/series/accessors/__pycache__/test_list_accessor.cpython-312.pyc,, +pandas/tests/series/accessors/__pycache__/test_sparse_accessor.cpython-312.pyc,, +pandas/tests/series/accessors/__pycache__/test_str_accessor.cpython-312.pyc,, +pandas/tests/series/accessors/__pycache__/test_struct_accessor.cpython-312.pyc,, +pandas/tests/series/accessors/test_cat_accessor.py,sha256=1-ZRI4h_lsBclkXljCrYFwGIYXbhrpE1iET-MjNKngk,9611 +pandas/tests/series/accessors/test_dt_accessor.py,sha256=FONy17Hl7ZWxgYSB-fTrL6bLfY3Fp3mZmwezLuJd89w,29877 +pandas/tests/series/accessors/test_list_accessor.py,sha256=7OsgwSCkXFDSRh81g5WKniPsv_zcTosuGicGPSemBqo,3425 +pandas/tests/series/accessors/test_sparse_accessor.py,sha256=yPxK1Re7RDPLi5v2r9etrgsUfSL9NN45CAvuR3tYVwA,296 +pandas/tests/series/accessors/test_str_accessor.py,sha256=M29X62c2ekvH1FTv56yye2TLcXyYUCM5AegAQVWLFc8,853 +pandas/tests/series/accessors/test_struct_accessor.py,sha256=Yg_Z1GjJf92XaXOnT0aUaeEtp7AOcQqWPT4guJKGfEg,5443 +pandas/tests/series/indexing/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/series/indexing/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_datetime.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_delitem.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_get.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_getitem.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_indexing.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_mask.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_set_value.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_setitem.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_take.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_where.cpython-312.pyc,, +pandas/tests/series/indexing/__pycache__/test_xs.cpython-312.pyc,, +pandas/tests/series/indexing/test_datetime.py,sha256=1_yUGMkSFYGh7TJOeDN_-5FvqsVyV-rGdgBzOnyqqNk,14752 +pandas/tests/series/indexing/test_delitem.py,sha256=IVd1S6LV2DIELVikf8uw30lNFuFNRIfe1Mg3MbCIyYc,1969 +pandas/tests/series/indexing/test_get.py,sha256=-FooS4ocg7uqbXYDNEZwMvRpTCar5LJCgCqi_CpDoo0,5758 +pandas/tests/series/indexing/test_getitem.py,sha256=2ABFEn1IsIFvV3tBqdlDu8D0cpXY4Ilbyo1QgDzr3pk,24390 +pandas/tests/series/indexing/test_indexing.py,sha256=XQ80NM09JH29NOZI_5m_WxTNA535aDK-WcMzklxGThs,16940 +pandas/tests/series/indexing/test_mask.py,sha256=ecPdJ-CM8HbaaZoGUfwcoOuo0eIz7aEq-x8wL0PZWbE,1711 +pandas/tests/series/indexing/test_set_value.py,sha256=UwVNpW3Fh3PKhNiFzZiVK07W871CmFM2fGtC6CTW5z0,991 +pandas/tests/series/indexing/test_setitem.py,sha256=MME-RirkwcjxHa-pnJXSmEh6q5PCN2agqQEcHgSCysM,59864 +pandas/tests/series/indexing/test_take.py,sha256=574cgL0w0fj-YnZma9b188Y0mTWs-Go6ZzB9zQSdpAk,1353 +pandas/tests/series/indexing/test_where.py,sha256=30D5XOV1OpmSUgdUpps4L91YdlWxXoN_9lzZtbDy4ac,13398 +pandas/tests/series/indexing/test_xs.py,sha256=8EKGIgnK86_hsBjPIY5lednYnzatv14O6rq3LjR_KxI,2760 +pandas/tests/series/methods/__init__.py,sha256=zVXqGxDIQ-ebxxcetI9KcJ9ZEHeIC4086CoDvyc8CNM,225 +pandas/tests/series/methods/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_add_prefix_suffix.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_align.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_argsort.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_asof.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_astype.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_autocorr.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_between.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_case_when.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_clip.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_combine.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_combine_first.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_compare.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_convert_dtypes.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_copy.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_count.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_cov_corr.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_describe.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_diff.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_drop.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_drop_duplicates.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_dropna.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_dtypes.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_duplicated.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_equals.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_explode.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_fillna.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_get_numeric_data.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_head_tail.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_infer_objects.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_info.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_interpolate.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_is_monotonic.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_is_unique.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_isin.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_isna.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_item.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_map.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_matmul.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_nlargest.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_nunique.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_pct_change.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_pop.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_quantile.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_rank.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_reindex.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_reindex_like.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_rename.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_rename_axis.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_repeat.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_replace.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_reset_index.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_round.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_searchsorted.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_set_name.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_size.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_sort_index.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_sort_values.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_to_csv.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_to_dict.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_to_frame.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_to_numpy.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_tolist.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_truncate.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_tz_localize.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_unique.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_unstack.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_update.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_value_counts.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_values.cpython-312.pyc,, +pandas/tests/series/methods/__pycache__/test_view.cpython-312.pyc,, +pandas/tests/series/methods/test_add_prefix_suffix.py,sha256=PeUIeDHa9rGggraEbVJRtLi2GcnNcXkrXb0otlthOC4,1556 +pandas/tests/series/methods/test_align.py,sha256=5No9fM2t4kaftnqVPm030TNWTwDhqnOVcAdGmPPGaio,8290 +pandas/tests/series/methods/test_argsort.py,sha256=GSvtMvfeUktQkrOsl-bF4di5w8QPCo9GPza1OmeofeM,2871 +pandas/tests/series/methods/test_asof.py,sha256=CqRdyeXFhE7zVdkJB-TxVqK3XPyBNvtOAfb6_a0VGgM,6324 +pandas/tests/series/methods/test_astype.py,sha256=-s-DqP7zgYlEKs2aandCmXUfftowGadYkP3wPp_XxG4,25745 +pandas/tests/series/methods/test_autocorr.py,sha256=SnxELB9bcE8H68tYUDN3UKMMPu-sEfbwTlLUn8WirV8,1015 +pandas/tests/series/methods/test_between.py,sha256=9w_8uWI5kcJOTfMwbEwmjGpU2j2cyuMtCYw4MrvgSM0,2584 +pandas/tests/series/methods/test_case_when.py,sha256=0YC-SaigIaoSO2l7h9sO4ebzCrxq0ma5FtiZKiwDMRs,4223 +pandas/tests/series/methods/test_clip.py,sha256=PuUarzkVXrwdYBF6pKqKbRw_GUuXdYsSPoNomgSDyzc,5220 +pandas/tests/series/methods/test_combine.py,sha256=ye8pwpjolpG_kUKSFTC8ZoRdj3ze8qtJXvDUZ5gpap4,627 +pandas/tests/series/methods/test_combine_first.py,sha256=n4Qc7xPR-qWXudzPpWnTX5S2Ov2kPaf0jnF9fngoXOA,5479 +pandas/tests/series/methods/test_compare.py,sha256=uRA4CKyOTPSzW3sihILLvxpxdSD1hb7mHrSydGFV2J4,4658 +pandas/tests/series/methods/test_convert_dtypes.py,sha256=fbzEQstPFv3J2lmJWssbJINuNXXXZzIVtccbHbAexcc,9915 +pandas/tests/series/methods/test_copy.py,sha256=im14SuY4pXfqYHvd4UamQSSTiXsK8GOP7Ga-5w-XRFs,3164 +pandas/tests/series/methods/test_count.py,sha256=mju3vjyHXg8qRH85cRLWvRL8lFnF7HGdETjt2e_pK7M,938 +pandas/tests/series/methods/test_cov_corr.py,sha256=NfmwlBV_Umm50xTwfuhJhKtNPmrUVEaJOt9GWTsb3DQ,5709 +pandas/tests/series/methods/test_describe.py,sha256=brDSZ2qicnLANI2ReYiYQiXzu6m9VxFr4DVULEyGgSA,6646 +pandas/tests/series/methods/test_diff.py,sha256=vEBvVglFS1cSDpllOLEZ9Dkdv1E02IYP9y6s6nsL6es,2538 +pandas/tests/series/methods/test_drop.py,sha256=nqTXYfvY76BZ2cl46kUb8mkkll5StdCzBaTn_YkGfIk,3394 +pandas/tests/series/methods/test_drop_duplicates.py,sha256=P6jHz77EAtuiI2IE25pNjBx3pXteUc0JUMoj2mWo8T4,9235 +pandas/tests/series/methods/test_dropna.py,sha256=fezc4siTNn-uOEQtOhaqNAOLYBoWN3Rh6STHAtOdk8U,3577 +pandas/tests/series/methods/test_dtypes.py,sha256=IkYkFl0o2LQ5qurobwoPgp4jqi2uKU7phoAk3oZtiYo,209 +pandas/tests/series/methods/test_duplicated.py,sha256=ACzVs9IJY4lC2SQb6frHVe4dGd6YLFID5UAw4BuZa7c,2059 +pandas/tests/series/methods/test_equals.py,sha256=qo8h305o5ktv9ooQ7pMbMUnQFjzOGLWc5TwxL9wD5zg,4182 +pandas/tests/series/methods/test_explode.py,sha256=FFXACDZNqbwR4qkee2osU7N_WeJOeHm5GWX6tXZIQZs,5329 +pandas/tests/series/methods/test_fillna.py,sha256=tjuKAfrmByzwY1H_xez3xSwKkZUDac1aSt47ZHP7llI,39985 +pandas/tests/series/methods/test_get_numeric_data.py,sha256=UPWNlzpl2a9Zez1JSfFP2EwsYfs4U4_Re4yOkqGpsl8,1178 +pandas/tests/series/methods/test_head_tail.py,sha256=1EWojjTzcLvYH34VvyvEHxczDy7zL3dMTyayFHsVSzY,343 +pandas/tests/series/methods/test_infer_objects.py,sha256=w0UyAVk4bHlCBX8Ot8BiV6Y0flw-70XiENsh0jsgyhg,1903 +pandas/tests/series/methods/test_info.py,sha256=zHHlqQFUJinvEJDVAElYdo6Q49XC5MQTggiuuLQyrkw,5205 +pandas/tests/series/methods/test_interpolate.py,sha256=Y0pZXAceQWfdEylQi0Q78g3LLSvwv9qTr0ur9z-SED8,34267 +pandas/tests/series/methods/test_is_monotonic.py,sha256=vvyWZFxiSybq88peF0zN5dM16rH2SgCEEA-gT2rRSSY,838 +pandas/tests/series/methods/test_is_unique.py,sha256=d3aLS5q491IVZkfKx8HTc4jkgTtuN0SOaUVfkyBTImE,953 +pandas/tests/series/methods/test_isin.py,sha256=iOwKDqYVh8mFnkwcdc9oRiJVlxfDF87AwL2i7kBugqQ,8343 +pandas/tests/series/methods/test_isna.py,sha256=TzNID2_dMG6ChWSwOMIqlF9AWcc1UjtjCHLNmT0vlBE,940 +pandas/tests/series/methods/test_item.py,sha256=z9gMBXHmc-Xhpyad9O0fT2RySMhlTa6MSrz2jPSUHxc,1627 +pandas/tests/series/methods/test_map.py,sha256=TQfCY97aXxLLrrw5IogRHmtWFGk4vadDa-ZnqGuurZo,18550 +pandas/tests/series/methods/test_matmul.py,sha256=cIj2nJctMnOvEDgTefpB3jypWJ6-RHasqtxywrxXw0g,2767 +pandas/tests/series/methods/test_nlargest.py,sha256=oIkyZ6Z2NiUL09sSTvAFK7IlcfQDiVgwssFe6NtsyIE,8442 +pandas/tests/series/methods/test_nunique.py,sha256=6B7fs9niuN2QYyxjVNX33WLBJvF2SJZRCn6SInTIz0g,481 +pandas/tests/series/methods/test_pct_change.py,sha256=C_WTtvjTsvfT94CUt22jYodJCHd18nUrkCLorQPf_d8,4523 +pandas/tests/series/methods/test_pop.py,sha256=xr9ZuFCI7O2gTW8a3WBr-ooQcOhBzoUK4N1x0K5G380,295 +pandas/tests/series/methods/test_quantile.py,sha256=DrjNLdKWpR-Sy8htHn2roHNI4roGKtR-ziZ77mPBVo8,8284 +pandas/tests/series/methods/test_rank.py,sha256=7t3MDhD_weTZ8542gybDB_zH3nPED5gVSnwl_Rko-pc,19937 +pandas/tests/series/methods/test_reindex.py,sha256=3Qi_Lk4WyHpWYMnOjGpky7bEyrfytigtQKm64uZ07CE,14417 +pandas/tests/series/methods/test_reindex_like.py,sha256=e_nuGo4QLgsdpnZrC49xDVfcz_prTGAOXGyjEEbkKM4,1245 +pandas/tests/series/methods/test_rename.py,sha256=tpljCho07Y03tq8lgy_cxGVPoF6G14vJvBv34cH1e0g,6303 +pandas/tests/series/methods/test_rename_axis.py,sha256=TqGeZdhB3Ektvj48JfbX2Jr_qsCovtoWimpfX_ViJyg,1520 +pandas/tests/series/methods/test_repeat.py,sha256=WvER_QkoVNYU4bg5hQbLdCXIWxqVnSmJ6K3_3OLLLAI,1274 +pandas/tests/series/methods/test_replace.py,sha256=soK8LijtDJGXHAB2BVjlppmvCk0VPMA_YFvz_j6o8xI,32110 +pandas/tests/series/methods/test_reset_index.py,sha256=4VUB-OdAnMtEAyfOze1Pj71R030J5H7A8vc9rI2vhsk,7845 +pandas/tests/series/methods/test_round.py,sha256=1-6IboBKwz7QCZHgo-nbgrYAB0orCMA2dNraHDiAlPs,2888 +pandas/tests/series/methods/test_searchsorted.py,sha256=2nk-hXPbFjgZfKm4bO_TiKm2xjd4hj0L9hiqR4nZ2Ss,2493 +pandas/tests/series/methods/test_set_name.py,sha256=rt1BK8BnWMd8D8vrO7yQNN4o-Fnapq5bRmlHyrYpxk4,595 +pandas/tests/series/methods/test_size.py,sha256=3-LfpWtTLM_dPAHFG_mmCxAk3dJY9WIe13czw1d9Fn4,566 +pandas/tests/series/methods/test_sort_index.py,sha256=XIiu2aL5NayZoQDsBRdBbx6po5_pW4pq4us2utrSY2c,12634 +pandas/tests/series/methods/test_sort_values.py,sha256=jIvHYYMz-RySUtJnB9aFLR88s-M20-B5E5PwK9VQhns,9372 +pandas/tests/series/methods/test_to_csv.py,sha256=1kQxhBUR6jb4_KqAQHaf29ztVqOGaSgHGT28gwH-Ksg,6346 +pandas/tests/series/methods/test_to_dict.py,sha256=XGdcF1jD4R0a_vWAQXwal3IVJoNwEANa1tU7qHtpIGA,1178 +pandas/tests/series/methods/test_to_frame.py,sha256=nUkHQTpMTffkpDR7w3EcQvQAevEfflD6tHm3pTBxpTI,1992 +pandas/tests/series/methods/test_to_numpy.py,sha256=pEB2B08IdIPRYp5n7USYFX9HQbClJl4xOegjVd7mYLc,1321 +pandas/tests/series/methods/test_tolist.py,sha256=5F0VAYJTPDUTlqb5zDNEec-BeBY25ZjnjqYHFQq5GPU,1115 +pandas/tests/series/methods/test_truncate.py,sha256=suMKI1jMEVVSd_b5rlLM2iqsQ08c8a9CbN8mbNKdNEU,2307 +pandas/tests/series/methods/test_tz_localize.py,sha256=chP4Dnhzfg5zphKiHwZpN-43o_p6jf0wqgid3a-ZB-Y,4336 +pandas/tests/series/methods/test_unique.py,sha256=MQB5s4KVopor1V1CgvF6lZNUSX6ZcOS2_H5JRYf7emU,2219 +pandas/tests/series/methods/test_unstack.py,sha256=ATn0kTNCEa2eAhGTFkMXPfDLl29Ee5cQvAPd3EcdQWY,5102 +pandas/tests/series/methods/test_update.py,sha256=ulLUeLuXA2dhC9PGwJKas1nrIgqL-48BOPKnahPf2UU,5475 +pandas/tests/series/methods/test_value_counts.py,sha256=LNmYx4OpzjjbLsjYHOrd4vxJZjKm9pEntq63I3mWttc,10109 +pandas/tests/series/methods/test_values.py,sha256=Q2jACWauws0GxIc_QzxbAOgMrJR6Qs7oyx_6LK7zVt8,747 +pandas/tests/series/methods/test_view.py,sha256=JipUTX6cC-NU4nVaDsyklmpRvfvf_HvUQE_fgYFqxPU,1851 +pandas/tests/series/test_api.py,sha256=1MYheb8We7ah2C-rDcSZJjS4rKqZdi_IEdM8GeyQnF4,10301 +pandas/tests/series/test_arithmetic.py,sha256=5JIztNGFA9nfAXccmhJGkpqpoZEGOpBQRKquOtcNH5A,33281 +pandas/tests/series/test_constructors.py,sha256=7DVF042GP9dET-JjJZoY64BgM0tAvym_DdaLrwP51j8,85825 +pandas/tests/series/test_cumulative.py,sha256=BdSWkvuS_fG-XA6gT7nfrRWRp0Ucq722Bs693_s4e0k,7949 +pandas/tests/series/test_formats.py,sha256=fo-CKyIaIq6JpmDx988P7MiYGYuvlS_IKsWDBMg5FKw,16706 +pandas/tests/series/test_iteration.py,sha256=LKCUh0-OueVvxOr7uEG8U9cQxrAk7X-WDwfgEIKUekI,1408 +pandas/tests/series/test_logical_ops.py,sha256=oCxV6DbXARdLc8N-6W66YK-prtDCmzo-SYJg5EJdyBc,20938 +pandas/tests/series/test_missing.py,sha256=6TtIBFZgw-vrOYqRzSxhYCIBngoVX8r8-sT5jFgkWKM,3277 +pandas/tests/series/test_npfuncs.py,sha256=BxhxkI2uWC-ygB3DJK_-FX2TOxcuqDUHX4tRQqD9CfU,1093 +pandas/tests/series/test_reductions.py,sha256=HdmQ4H-gycB2Nz6HjyemDLwZjsI8PLIoauje3snur9g,6518 +pandas/tests/series/test_subclass.py,sha256=aL5tgGGXZPPIXWIgpCPBrc7Q5KS8h1ipZNKCwciw-jY,2667 +pandas/tests/series/test_ufunc.py,sha256=uo0FJLsk2WFgOIMfKBlsuySEKzwkGYtcTPCRPmJt2qY,14758 +pandas/tests/series/test_unary.py,sha256=Xktw6w940LXm38OKLW-LRqpMZSA9EB5feCt9FMLh-E4,1620 +pandas/tests/series/test_validate.py,sha256=ziCmKi_jYuGyxcnsVaJpVgwSCjBgpHDJ0dbzWLa1-kA,668 +pandas/tests/strings/__init__.py,sha256=bXy3OI--skxWsx5XSeisvRlIrXiyNmNvUZPzTSa-82s,587 +pandas/tests/strings/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/strings/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_case_justify.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_cat.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_extract.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_find_replace.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_get_dummies.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_split_partition.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_string_array.cpython-312.pyc,, +pandas/tests/strings/__pycache__/test_strings.cpython-312.pyc,, +pandas/tests/strings/conftest.py,sha256=M-9nIdAAynMJ7FvFFTHXJEUZFT8uOTbizf5ZOnOJ-Tk,3960 +pandas/tests/strings/test_api.py,sha256=_zxkxArja09rqqFoxITZ8Dy7NFOGxhlBDh0oba8UnR0,6609 +pandas/tests/strings/test_case_justify.py,sha256=X_Wap9pwqH-XUXi3xSOVfAIk033c1KcHFx9ksYWJrxg,13361 +pandas/tests/strings/test_cat.py,sha256=zCJBBRtmaOxMGwXeS4evfDtAVccO3EmloEUn-dMi0ho,13575 +pandas/tests/strings/test_extract.py,sha256=LuGkboI2Q6d60kQgwMDudy-5eEbixaaCGP78CwHli6c,26463 +pandas/tests/strings/test_find_replace.py,sha256=IayKxI4h3808k2nqzhsn4wFQq6_lA6KLcmV9anhtr7E,46809 +pandas/tests/strings/test_get_dummies.py,sha256=LyWHwMrb5pgX69t4b9ouHflXKp4gBXadTCkaZSk_HB4,1608 +pandas/tests/strings/test_split_partition.py,sha256=r3i4HITEpxEM0ZLMBkz6DeJpy5tZM5o0yaYpeyD9K2A,23250 +pandas/tests/strings/test_string_array.py,sha256=yGTtAjj0U8ovvhhiuJ6HS9yLE_fBZIw-7rA9qtDeWLo,3514 +pandas/tests/strings/test_strings.py,sha256=yiwHl--LRVsP-7ogN5HKmpzBnh4PR9k8C4KafnMP9Xg,29688 +pandas/tests/test_aggregation.py,sha256=-9GlIUg7qPr3Ppj_TNbBF85oKjSIMAv056hfcYZvhWw,2779 +pandas/tests/test_algos.py,sha256=63SRKWH30MEGmSh22zsdLQ_ROE-NknsdmKXP7dgUGPg,78613 +pandas/tests/test_common.py,sha256=SHkM8XyjSNxUJquSiEDa3lqE0GJ7tLsfwdro0x2leAg,7695 +pandas/tests/test_downstream.py,sha256=U-x1_RsBX0sSHNU_M3fyGcM6nLIq0BwJL1py2cU_M7Y,10856 +pandas/tests/test_errors.py,sha256=4WVxQSyv6okTRVQC9LC9thX5ZjXVMrX-3l93bEd9KZ8,2789 +pandas/tests/test_expressions.py,sha256=fyTafylKNf7Wb3qzwlvIGbM4MdlJB7V4yGJrgiMRE5w,14256 +pandas/tests/test_flags.py,sha256=Dsu6pvQ5A6Manyt1VlQLK8pRpZtr-S2T3ubJvRQaRlA,1550 +pandas/tests/test_multilevel.py,sha256=3-Gmz-7nEzWFDYT5k_nzRL17xLCj2ZF3q69dzHO5sL8,12206 +pandas/tests/test_nanops.py,sha256=NWzcF6_g_IT0HQRG9ETV3kimAAKVmoFohuGymqsDLPI,42042 +pandas/tests/test_optional_dependency.py,sha256=wnDdNm9tlr2MFSOwB9EWAPUf1_H3L0GUTbGeZyGUqL8,3159 +pandas/tests/test_register_accessor.py,sha256=L2cU-H7UU1M36_7DU7p69SvGEFWZXpMpUJ8NZS2yOTI,2671 +pandas/tests/test_sorting.py,sha256=0rqJWWFq1kVX8m-W0X7dXdl9XoaYxZKuGHtBiJIn3nQ,16595 +pandas/tests/test_take.py,sha256=YSMLvpggEaY_MOT3PkVtQYUw0MfwN4bVvI3EgmOgxfA,11539 +pandas/tests/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tools/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/tools/__pycache__/test_to_datetime.cpython-312.pyc,, +pandas/tests/tools/__pycache__/test_to_numeric.cpython-312.pyc,, +pandas/tests/tools/__pycache__/test_to_time.cpython-312.pyc,, +pandas/tests/tools/__pycache__/test_to_timedelta.cpython-312.pyc,, +pandas/tests/tools/test_to_datetime.py,sha256=eB_4J3D7Fyh1Mra5uwBzn7YCQV2172HDY8YkNQvRHUg,147496 +pandas/tests/tools/test_to_numeric.py,sha256=R9fTxZIebRQp-yNh2oDsHYF8xgszrVLNqlVDYGwnajM,29480 +pandas/tests/tools/test_to_time.py,sha256=e-QmGu5nAe9clT8n9bda5aEwHBH4ZaXqBzs5-mKWMYQ,2417 +pandas/tests/tools/test_to_timedelta.py,sha256=sA-q01yavNfamRKB0JZ08ou3PN-G38PZ1Tuk5KOL8iI,12454 +pandas/tests/tseries/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/tseries/frequencies/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/frequencies/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/tseries/frequencies/__pycache__/test_freq_code.cpython-312.pyc,, +pandas/tests/tseries/frequencies/__pycache__/test_frequencies.cpython-312.pyc,, +pandas/tests/tseries/frequencies/__pycache__/test_inference.cpython-312.pyc,, +pandas/tests/tseries/frequencies/test_freq_code.py,sha256=hvQl37z3W6CwcLOAqrgc2acqtjOJIbqVbnXkEUBY4cM,1727 +pandas/tests/tseries/frequencies/test_frequencies.py,sha256=tyI9e6ve7sEXdALy9GYjMV3mAQHmQF2IqW-xFzPdgjY,821 +pandas/tests/tseries/frequencies/test_inference.py,sha256=o8bZEapedbcC1zoj_slbggdZkzxX9Z1oh6VuCly8PU4,15111 +pandas/tests/tseries/holiday/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/holiday/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_calendar.cpython-312.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_federal.cpython-312.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_holiday.cpython-312.pyc,, +pandas/tests/tseries/holiday/__pycache__/test_observance.cpython-312.pyc,, +pandas/tests/tseries/holiday/test_calendar.py,sha256=SdMzzgTizQ88wJBRVTmVIgxE8E20_sgLFunP3WHlkZU,3622 +pandas/tests/tseries/holiday/test_federal.py,sha256=ukOOSRoUdcfUOlAT10AWVj8uxiD-88_H8xd--WpOsG0,1948 +pandas/tests/tseries/holiday/test_holiday.py,sha256=0NsEkl5wr2ckwvGiXnrYhluZZRpCc_Ede6SqdrFGc7I,11173 +pandas/tests/tseries/holiday/test_observance.py,sha256=GJBqIF4W6QG4k3Yzz6_13WMOR4nHSVzPbixHxO8Tukw,2723 +pandas/tests/tseries/offsets/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tseries/offsets/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/common.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_day.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_hour.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_month.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_quarter.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_business_year.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_common.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_custom_business_day.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_custom_business_hour.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_custom_business_month.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_dst.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_easter.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_fiscal.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_index.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_month.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_offsets.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_offsets_properties.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_quarter.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_ticks.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_week.cpython-312.pyc,, +pandas/tests/tseries/offsets/__pycache__/test_year.cpython-312.pyc,, +pandas/tests/tseries/offsets/common.py,sha256=D3D8mcwwzW2kSEB8uX8gO6ARX4dB4PEu3_953APlRmk,900 +pandas/tests/tseries/offsets/test_business_day.py,sha256=dqOwIoAq3Mcxrc0EEeqJnnDvJYCFz5lA0JewVuODhBc,6808 +pandas/tests/tseries/offsets/test_business_hour.py,sha256=PV5Ddc4vEsQXrXhCKyDIcKptcNhXgIe-KiY14zsbVE0,58452 +pandas/tests/tseries/offsets/test_business_month.py,sha256=ZQlcBF15WTMq5w8uC7QeQ6QYVWN8hmfu1PtJvW-ebYU,6717 +pandas/tests/tseries/offsets/test_business_quarter.py,sha256=Tvp5J5r5uDBh8Y9yW65JItTp-B5fdJ4T9G0fxelHYaw,12591 +pandas/tests/tseries/offsets/test_business_year.py,sha256=OBs55t5gGKSPhTsnGafi5Uqsrjmq1cKpfuwWLUBR8Uo,6436 +pandas/tests/tseries/offsets/test_common.py,sha256=HpiuRR_ktnWLWSoFtMe87AVUCedpRcqxoTeVrfCg7is,7406 +pandas/tests/tseries/offsets/test_custom_business_day.py,sha256=YNN53-HvTW4JrbLYwyUiM10rQqIof1iA_W1uYkiHw7w,3180 +pandas/tests/tseries/offsets/test_custom_business_hour.py,sha256=UXa57Q-ZYPDMv307t7UKQGOIE32CH_FmCNY3hX8dcN4,12312 +pandas/tests/tseries/offsets/test_custom_business_month.py,sha256=WBgCVPO6PUa4oX0bDSDk_UE5hOeYbIo2sduIM9X3ASI,13362 +pandas/tests/tseries/offsets/test_dst.py,sha256=0s6bpzEFkVfUKN6lAkeFTiyzMwYRQwrZs49WAu-LK4o,9139 +pandas/tests/tseries/offsets/test_easter.py,sha256=oZlJ3lESuLTEv6A_chVDsD3Pa_cqgbVc4_zxrEE7cvc,1150 +pandas/tests/tseries/offsets/test_fiscal.py,sha256=p_rXA9wPnKZwDp40kaB8uGjq2fpHPCRU5PFF-1rClbA,26732 +pandas/tests/tseries/offsets/test_index.py,sha256=aeW6vyuME-22oikOhiE6q6nrLkIc22TjV3wPxpWXjIk,1147 +pandas/tests/tseries/offsets/test_month.py,sha256=EHsmRpEhG_CLSNEUOtA48auiJxFnr8sPsHQTyZeuu2g,23243 +pandas/tests/tseries/offsets/test_offsets.py,sha256=0yEFO27kh9uvdu4-MYW9bp5OX9Wb3lIKdiC4Jcna-2o,40623 +pandas/tests/tseries/offsets/test_offsets_properties.py,sha256=P_16zBX7ocaGN-br0pEQBGTlewfiDpJsnf5R1ei83JQ,1971 +pandas/tests/tseries/offsets/test_quarter.py,sha256=VBRsOqNS6xzYV63UVrPU3Z3_eAZQw4WefK2gPNfKork,11839 +pandas/tests/tseries/offsets/test_ticks.py,sha256=1n9PC1iEDQwnUKJivCaC6Wms3r8Je8ZKcGua_ySLLqE,11548 +pandas/tests/tseries/offsets/test_week.py,sha256=EUTDq6l4YT8xbBhQb0iHyNfJEme2jVZdjzaeg-Qj75g,12330 +pandas/tests/tseries/offsets/test_year.py,sha256=EM9DThnH2c6CMw518YpxkrpJixPmH3OVQ_Qp8iMIHPQ,10455 +pandas/tests/tslibs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/tslibs/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_array_to_datetime.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_ccalendar.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_conversion.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_fields.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_libfrequencies.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_liboffsets.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_np_datetime.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_npy_units.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_parse_iso8601.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_parsing.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_period.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_resolution.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_strptime.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_timedeltas.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_timezones.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_to_offset.cpython-312.pyc,, +pandas/tests/tslibs/__pycache__/test_tzconversion.cpython-312.pyc,, +pandas/tests/tslibs/test_api.py,sha256=ooEY2RyO9oL8Wcbsc958sGrBjveqTQZPauLeBN3n9xc,1525 +pandas/tests/tslibs/test_array_to_datetime.py,sha256=uQOT4gOHQr35s3R6d8GxDdCH21db6rJZzXKQYrh89y0,11871 +pandas/tests/tslibs/test_ccalendar.py,sha256=Rl2OjoB8pHaOyXW5MmshsHmm8nNMuHQvS_Du1L6ODqw,1903 +pandas/tests/tslibs/test_conversion.py,sha256=rgtB7pIs6VvpkNakcew9PFQ8oVHtwCwwBtu2gCFqbh4,4555 +pandas/tests/tslibs/test_fields.py,sha256=BQKlBXOC4LsXe7eT2CK5mRGR_25g9qYykQZ6ojoGjbE,1352 +pandas/tests/tslibs/test_libfrequencies.py,sha256=Ai6deDiGlwUHR9mVvlkIbXYzWZADHuPLlaBjDK0R2wU,717 +pandas/tests/tslibs/test_liboffsets.py,sha256=958cVv4vva5nawrYcmSinfu62NIL7lYOXOHN7yU-gAE,5108 +pandas/tests/tslibs/test_np_datetime.py,sha256=n7MNYHw7i03w4ZcVTM6GkoRN7Y7UIGxnshjHph2eDPs,7889 +pandas/tests/tslibs/test_npy_units.py,sha256=d9NFsygcKGtp-pw-ZpOvIxMhpsRqd1uPBVlqejHkNmU,922 +pandas/tests/tslibs/test_parse_iso8601.py,sha256=XGQ_GBOCosTiOFFjK4rYoDDZcIBitnyIb_0SXxKF9yo,4535 +pandas/tests/tslibs/test_parsing.py,sha256=xsD1wCNePi7BdUU-gQBfwIWOTr8i6ybIa1wSv-9-MT8,13962 +pandas/tests/tslibs/test_period.py,sha256=l1xiNGDhMIJFG21BcAcE8Gkd6GODs-dPVOXcNuw6XTA,3424 +pandas/tests/tslibs/test_resolution.py,sha256=YC6IpOJsIHrsn7DUGi_LKdQrAuZgAqofNeW0DU2gays,1544 +pandas/tests/tslibs/test_strptime.py,sha256=DqjYyJ9t-cpSFDRyF3RepxMSZ4qvPllEjvarqvQKw1E,3896 +pandas/tests/tslibs/test_timedeltas.py,sha256=DaaxCrPg5Usv1UtpaVWpiYWixUtNT1FqjtS26MJq9PI,4662 +pandas/tests/tslibs/test_timezones.py,sha256=Hb56aLljCgRtBmXp7N_TaXM55ODLs6Mvl851dncnpsQ,4724 +pandas/tests/tslibs/test_to_offset.py,sha256=GaUG1VE0HhjMFjIj3aAP1LtzqFBCVx5_e0GUX1alIIU,5873 +pandas/tests/tslibs/test_tzconversion.py,sha256=6Ouplo1p8ArDrxCzPNyH9xpYkxERNPvbd4C_-WmTNd4,953 +pandas/tests/util/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/util/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/util/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_almost_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_attr_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_categorical_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_extension_array_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_frame_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_index_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_interval_array_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_numpy_array_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_produces_warning.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_assert_series_equal.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_deprecate.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_deprecate_kwarg.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_deprecate_nonkeyword_arguments.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_doc.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_hashing.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_numba.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_rewrite_warning.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_shares_memory.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_show_versions.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_util.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_validate_args.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_validate_args_and_kwargs.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_validate_inclusive.cpython-312.pyc,, +pandas/tests/util/__pycache__/test_validate_kwargs.cpython-312.pyc,, +pandas/tests/util/conftest.py,sha256=loEbQsEtHtv-T4Umeq_UeV6R7s8SO01GHbW6gn8lvlo,476 +pandas/tests/util/test_assert_almost_equal.py,sha256=K1-2c3XrbAb3jU23Dl9T79ueRfE32_Va7CNPfvopOYo,16803 +pandas/tests/util/test_assert_attr_equal.py,sha256=ZXTojP4V5Kle96QOFhxCZjq-dQf6gHvNOorYyOuFP1I,1045 +pandas/tests/util/test_assert_categorical_equal.py,sha256=yDmVzU22k5k5txSHixGfRJ4nKeP46FdNoh3CY1xEwEM,2728 +pandas/tests/util/test_assert_extension_array_equal.py,sha256=quw84fCgsrwtUMu-TcvHmrq5-08J7l1ZzS_3h1Eh3qw,3887 +pandas/tests/util/test_assert_frame_equal.py,sha256=TC5P8XdkYO1cPEWNdzaWr_JyVrfVpvcoKGWyt92ymJs,13376 +pandas/tests/util/test_assert_index_equal.py,sha256=LcRAOgz4q-S5ME4hM8dSezgb8DmlzmKRLj9OfV6oSgU,10154 +pandas/tests/util/test_assert_interval_array_equal.py,sha256=ITqL0Z8AAy5D1knACPOHodI64AHxmNzxiG-i9FeU0b8,2158 +pandas/tests/util/test_assert_numpy_array_equal.py,sha256=fgb8GdUwX4EYiR3PWbjJULNfAJz4DfJ8RJXchssygO4,6624 +pandas/tests/util/test_assert_produces_warning.py,sha256=A-pN3V12hnIqlbFYArYbdU-992RgJ-fqsaKbM0yvYPw,8412 +pandas/tests/util/test_assert_series_equal.py,sha256=DlcaY6-RsRlN2pvTNuWvvWduYxz0XOEyj3covMsfKnY,14828 +pandas/tests/util/test_deprecate.py,sha256=1hGoeUQTew5o0DnCjLV5-hOfEuSoIGOXGByq5KpAP7A,1617 +pandas/tests/util/test_deprecate_kwarg.py,sha256=7T2QkCxXUoJHhCxUjAH_5_hM-BHC6nPWG635LFY35lo,2043 +pandas/tests/util/test_deprecate_nonkeyword_arguments.py,sha256=0UkqIi4ehxD3aoA3z7y8-3dpOs6o30_Gp8rZvFX1W9Q,3623 +pandas/tests/util/test_doc.py,sha256=u0fxCg4zZWhB4SkJYc2huQ0xv7sKKAt0OlpWldmhh_M,1492 +pandas/tests/util/test_hashing.py,sha256=ZjoFCs6MoAhGV1j2WyjjEJkqyO9WQgRqwS6xx-3n0oE,13857 +pandas/tests/util/test_numba.py,sha256=6eOVcokESth7h6yyeehVizx61FtwDdVbF8wV8j3t-Ic,308 +pandas/tests/util/test_rewrite_warning.py,sha256=AUHz_OT0HS6kXs-9e59GflBCP3Tb5jy8jl9FxBg5rDs,1151 +pandas/tests/util/test_shares_memory.py,sha256=KN5X8yuw6M8pHgL0ES6YeH6_sZDUEx_wEib6B5Gvkew,852 +pandas/tests/util/test_show_versions.py,sha256=FjYUrUMAF7hOzphaXED__8yjeF0HTccZS6q05__rH44,2096 +pandas/tests/util/test_util.py,sha256=4UacWPLyjRQZU697jBxBWO6V1gUgkE4E-KKF6H6aXuE,1463 +pandas/tests/util/test_validate_args.py,sha256=9Z4zTqnKAWn1q9KZNvuO3DF6oszHjQrQgtOOimurWcs,1907 +pandas/tests/util/test_validate_args_and_kwargs.py,sha256=d_XcMRAQ9r--yIAAWSdJML6KeWgksy5qRNFXaY1BMQA,2456 +pandas/tests/util/test_validate_inclusive.py,sha256=w2twetJgIedm6KGQ4WmdmGC_6-RShFjXBMBVxR0gcME,896 +pandas/tests/util/test_validate_kwargs.py,sha256=NAZi-4Z0DrlQKZkkcKrWxoHxzWuKFxY8iphCBweA9jk,1808 +pandas/tests/window/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/window/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/window/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_api.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_apply.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_base_indexer.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_cython_aggregations.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_dtypes.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_ewm.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_expanding.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_groupby.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_numba.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_online.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_pairwise.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_rolling.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_rolling_functions.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_rolling_quantile.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_rolling_skew_kurt.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_timeseries_window.cpython-312.pyc,, +pandas/tests/window/__pycache__/test_win_type.cpython-312.pyc,, +pandas/tests/window/conftest.py,sha256=rlS3eILzfTByRmmm7HLjk-FHEIbdTVVE9c0Dq-nfxa4,3137 +pandas/tests/window/moments/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pandas/tests/window/moments/__pycache__/__init__.cpython-312.pyc,, +pandas/tests/window/moments/__pycache__/conftest.cpython-312.pyc,, +pandas/tests/window/moments/__pycache__/test_moments_consistency_ewm.cpython-312.pyc,, +pandas/tests/window/moments/__pycache__/test_moments_consistency_expanding.cpython-312.pyc,, +pandas/tests/window/moments/__pycache__/test_moments_consistency_rolling.cpython-312.pyc,, +pandas/tests/window/moments/conftest.py,sha256=xSkyyVltsAkJETLDHJSksjRkjcVHsnhfyCiNvhsQ3no,1595 +pandas/tests/window/moments/test_moments_consistency_ewm.py,sha256=4FPmIGVQuOUg13aT5c9l_DN7j7K3J9QEU0KXeO2Qrt0,8107 +pandas/tests/window/moments/test_moments_consistency_expanding.py,sha256=e4Vn3nE02q-UeRH2aWLOSMv0QN4nN04iePKst5N-Vbo,5537 +pandas/tests/window/moments/test_moments_consistency_rolling.py,sha256=UBQL1mWD1qIB3fNb4tizqv-q4xlAz4tGT1nC1G-9RWM,7821 +pandas/tests/window/test_api.py,sha256=tgTULbAkhYVhgsIASr0q8rv2Gxh36Zn55hha1aNoKuM,13189 +pandas/tests/window/test_apply.py,sha256=v9YC4aORGX7yA50RFMjZqMx93SWp9o4Vpjo32xTROx0,9865 +pandas/tests/window/test_base_indexer.py,sha256=Fz81kU5x1g6OnNmRra6PRarPpq5HEYuA8XX0sR_y6LI,15954 +pandas/tests/window/test_cython_aggregations.py,sha256=wPAk76yfrG9D1-IzI0kDklpiTVqgp4xsEGjONe9lCY4,3967 +pandas/tests/window/test_dtypes.py,sha256=a3Xnqcq_jO0kczZmhmuBKkmCsKHOOufy9h6yNCPHlMk,5785 +pandas/tests/window/test_ewm.py,sha256=F1BB5E3_n5i5IzDNTMZeZzmG3aZqxC1jp_Pj-bWcozU,23020 +pandas/tests/window/test_expanding.py,sha256=Kz-2wSWxj4E31kd6y4jo7T7gE7aSe7yGHMYE7b4Bq18,24239 +pandas/tests/window/test_groupby.py,sha256=Uuunbe0ijjZaGcYV0of38imLoELseK0GYlHCRg6CEBU,46639 +pandas/tests/window/test_numba.py,sha256=ziiRaYE2FHbJvqA-moUJg-PdBGj1CFAnz3YB_wyEacU,16373 +pandas/tests/window/test_online.py,sha256=jhtEqYVPRoc9o7h4INf7-w2k5gKiVQJFnArH3AMFsEA,3644 +pandas/tests/window/test_pairwise.py,sha256=BXJLxRbolFs00FxTMp3uIFDNpZkciv8VGyAXFMw3zHI,16141 +pandas/tests/window/test_rolling.py,sha256=PzPkVsNDBUh6wgzFZvq_YNba2bdmwSO_H8BUK9ZxAys,61158 +pandas/tests/window/test_rolling_functions.py,sha256=xmaaXFaMq22o1s0Ba4NieIkTZtKWi9WOYae6z8i_rBo,17877 +pandas/tests/window/test_rolling_quantile.py,sha256=AvsqMR5YrVAlAFfhL0lHHAZIazXnzI1VkoVuPuiDEro,5516 +pandas/tests/window/test_rolling_skew_kurt.py,sha256=Emw9AJhTZyuVnxPg-nfYxpRNGJToWJ-he7obTSOy8iU,7807 +pandas/tests/window/test_timeseries_window.py,sha256=I0hk72tAFP4RJUaGesfUrjR5HC_bxBWwcXW7mxgslfg,24250 +pandas/tests/window/test_win_type.py,sha256=GRu_7tF1tQAEH8hcb6kZPSG2FJihUTE1_85tH1iYaN8,17522 +pandas/tseries/__init__.py,sha256=CM1Forog6FJC_5YY4IueiWfQ9cATlSDJ4hF23RTniBQ,293 +pandas/tseries/__pycache__/__init__.cpython-312.pyc,, +pandas/tseries/__pycache__/api.cpython-312.pyc,, +pandas/tseries/__pycache__/frequencies.cpython-312.pyc,, +pandas/tseries/__pycache__/holiday.cpython-312.pyc,, +pandas/tseries/__pycache__/offsets.cpython-312.pyc,, +pandas/tseries/api.py,sha256=0Tms-OsqaHcpWH7a2F4mqKqEV-G5btiZKte3cUnEWQM,234 +pandas/tseries/frequencies.py,sha256=HNmBHzxRPhtlnpZF6iBSvq6e2du9J1JZ9gQ2c48Bvv0,17686 +pandas/tseries/holiday.py,sha256=G9kQvaBMzdNUoCs4WApAcxzSkOozFEyfDYFFjL8ZlZc,18596 +pandas/tseries/offsets.py,sha256=wLWH1_fg7dYGDsHDRyBxc62788G9CDhLcpDeZHt5ixI,1531 +pandas/util/__init__.py,sha256=tXNVCMKcgkFf4GETkpUx_UYvN56-54tYCCM0-04OIn4,827 +pandas/util/__pycache__/__init__.cpython-312.pyc,, +pandas/util/__pycache__/_decorators.cpython-312.pyc,, +pandas/util/__pycache__/_doctools.cpython-312.pyc,, +pandas/util/__pycache__/_exceptions.cpython-312.pyc,, +pandas/util/__pycache__/_print_versions.cpython-312.pyc,, +pandas/util/__pycache__/_test_decorators.cpython-312.pyc,, +pandas/util/__pycache__/_tester.cpython-312.pyc,, +pandas/util/__pycache__/_validators.cpython-312.pyc,, +pandas/util/_decorators.py,sha256=n1OyKRRG-dcCRUSmyejpKTyfP_iu2kVF0TJ_9yIJkeo,17106 +pandas/util/_doctools.py,sha256=Es1FLqrmsOLpJ_7Y24q_vqdXGw5Vy6vcajcfbIi_FCo,6819 +pandas/util/_exceptions.py,sha256=H6Tz6X1PqPVp6wG_7OsjHEqTvTM9I3SebF5-WcTdZOc,2876 +pandas/util/_print_versions.py,sha256=yyjjNJgg7dxM1PgfeCUGUNqeEfM1XifUZjaGkgRdrRU,4615 +pandas/util/_test_decorators.py,sha256=KEhS1cMaBbf4U0R0KMRXZl-CcCkPfNqxpVz8BTtb0zY,5079 +pandas/util/_tester.py,sha256=Mluqpd_YwVdcdgZfSu-_oVdadk_JjX9FuPGFjn_S6ZA,1462 +pandas/util/_validators.py,sha256=VGKuOFzz0rY5g2dmbKpWV8vZb5Jb1RV5w-HTVi1GMY0,14300 +pandas/util/version/__init__.py,sha256=57SNOildSF8ehHn99uGwCZeAkTEuA6YMw6cYxjEyQ2I,16394 +pandas/util/version/__pycache__/__init__.cpython-312.pyc,, diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d66e1f83019210eb9d71315760879370e1e52455 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp312-cp312-macosx_11_0_arm64 +Generator: delocate 0.13.0 + diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/entry_points.txt b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..3c1b523d70758fbd0080e21ca4c7ce6d9c9d9bd5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas-2.3.3.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[pandas_plotting_backends] +matplotlib = pandas:plotting._matplotlib + diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..866f336a25d52f2be1da587135862c3bbbbc71f8 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/__pycache__/test_multilevel.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cb021a8a77c296429b80f92125a1b8d0750d4a4 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/__init__.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/test_compat.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/test_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..856a5b3a22a95d35cc577050f52d762b065e3ddf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/test_compat.py @@ -0,0 +1,32 @@ +import pytest + +from pandas.compat._optional import VERSIONS + +import pandas as pd +from pandas.core.computation import expr +from pandas.core.computation.engines import ENGINES +from pandas.util.version import Version + + +def test_compat(): + # test we have compat with our version of numexpr + + from pandas.core.computation.check import NUMEXPR_INSTALLED + + ne = pytest.importorskip("numexpr") + + ver = ne.__version__ + if Version(ver) < Version(VERSIONS["numexpr"]): + assert not NUMEXPR_INSTALLED + else: + assert NUMEXPR_INSTALLED + + +@pytest.mark.parametrize("engine", ENGINES) +@pytest.mark.parametrize("parser", expr.PARSERS) +def test_invalid_numexpr_version(engine, parser): + if engine == "numexpr": + pytest.importorskip("numexpr") + a, b = 1, 2 # noqa: F841 + res = pd.eval("a + b", engine=engine, parser=parser) + assert res == 3 diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/test_eval.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/test_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..859cbd30cfeadb29add9cabd770be0d6bd67d2d1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/computation/test_eval.py @@ -0,0 +1,2006 @@ +from __future__ import annotations + +from functools import reduce +from itertools import product +import operator + +import numpy as np +import pytest + +from pandas.compat import PY312 +from pandas.compat._optional import import_optional_dependency +from pandas.errors import ( + NumExprClobberingError, + PerformanceWarning, + UndefinedVariableError, +) +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import ( + is_bool, + is_float, + is_list_like, + is_scalar, +) + +import pandas as pd +from pandas import ( + DataFrame, + Index, + Series, + date_range, + period_range, + timedelta_range, +) +import pandas._testing as tm +from pandas.core.computation import ( + expr, + pytables, +) +from pandas.core.computation.engines import ENGINES +from pandas.core.computation.expr import ( + BaseExprVisitor, + PandasExprVisitor, + PythonExprVisitor, +) +from pandas.core.computation.expressions import ( + NUMEXPR_INSTALLED, + USE_NUMEXPR, +) +from pandas.core.computation.ops import ( + ARITH_OPS_SYMS, + SPECIAL_CASE_ARITH_OPS_SYMS, + _binary_math_ops, + _binary_ops_dict, + _unary_math_ops, +) +from pandas.core.computation.scope import DEFAULT_GLOBALS +from pandas.util.version import Version + +numexpr = import_optional_dependency("numexpr", errors="ignore") + + +@pytest.fixture( + params=( + pytest.param( + engine, + marks=[ + pytest.mark.skipif( + engine == "numexpr" and not USE_NUMEXPR, + reason=f"numexpr enabled->{USE_NUMEXPR}, " + f"installed->{NUMEXPR_INSTALLED}", + ), + td.skip_if_no("numexpr"), + ], + ) + for engine in ENGINES + ) +) +def engine(request): + return request.param + + +@pytest.fixture(params=expr.PARSERS) +def parser(request): + return request.param + + +def _eval_single_bin(lhs, cmp1, rhs, engine): + c = _binary_ops_dict[cmp1] + if ENGINES[engine].has_neg_frac: + try: + return c(lhs, rhs) + except ValueError as e: + if str(e).startswith( + "negative number cannot be raised to a fractional power" + ): + return np.nan + raise + return c(lhs, rhs) + + +# TODO: using range(5) here is a kludge +@pytest.fixture( + params=list(range(5)), + ids=["DataFrame", "Series", "SeriesNaN", "DataFrameNaN", "float"], +) +def lhs(request): + nan_df1 = DataFrame(np.random.default_rng(2).standard_normal((10, 5))) + nan_df1[nan_df1 > 0.5] = np.nan + + opts = ( + DataFrame(np.random.default_rng(2).standard_normal((10, 5))), + Series(np.random.default_rng(2).standard_normal(5)), + Series([1, 2, np.nan, np.nan, 5]), + nan_df1, + np.random.default_rng(2).standard_normal(), + ) + return opts[request.param] + + +rhs = lhs +midhs = lhs + + +@pytest.fixture +def idx_func_dict(): + return { + "i": lambda n: Index(np.arange(n), dtype=np.int64), + "f": lambda n: Index(np.arange(n), dtype=np.float64), + "s": lambda n: Index([f"{i}_{chr(i)}" for i in range(97, 97 + n)]), + "dt": lambda n: date_range("2020-01-01", periods=n), + "td": lambda n: timedelta_range("1 day", periods=n), + "p": lambda n: period_range("2020-01-01", periods=n, freq="D"), + } + + +class TestEval: + @pytest.mark.parametrize( + "cmp1", + ["!=", "==", "<=", ">=", "<", ">"], + ids=["ne", "eq", "le", "ge", "lt", "gt"], + ) + @pytest.mark.parametrize("cmp2", [">", "<"], ids=["gt", "lt"]) + @pytest.mark.parametrize("binop", expr.BOOL_OPS_SYMS) + def test_complex_cmp_ops(self, cmp1, cmp2, binop, lhs, rhs, engine, parser): + if parser == "python" and binop in ["and", "or"]: + msg = "'BoolOp' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)" + pd.eval(ex, engine=engine, parser=parser) + return + + lhs_new = _eval_single_bin(lhs, cmp1, rhs, engine) + rhs_new = _eval_single_bin(lhs, cmp2, rhs, engine) + expected = _eval_single_bin(lhs_new, binop, rhs_new, engine) + + ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)" + result = pd.eval(ex, engine=engine, parser=parser) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("cmp_op", expr.CMP_OPS_SYMS) + def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser): + lhs = lhs < 0 + rhs = rhs < 0 + + if parser == "python" and cmp_op in ["in", "not in"]: + msg = "'(In|NotIn)' nodes are not implemented" + + with pytest.raises(NotImplementedError, match=msg): + ex = f"lhs {cmp_op} rhs" + pd.eval(ex, engine=engine, parser=parser) + return + + ex = f"lhs {cmp_op} rhs" + msg = "|".join( + [ + r"only list-like( or dict-like)? objects are allowed to be " + r"passed to (DataFrame\.)?isin\(\), you passed a " + r"(`|')bool(`|')", + "argument of type 'bool' is not iterable", + ] + ) + if cmp_op in ("in", "not in") and not is_list_like(rhs): + with pytest.raises(TypeError, match=msg): + pd.eval( + ex, + engine=engine, + parser=parser, + local_dict={"lhs": lhs, "rhs": rhs}, + ) + else: + expected = _eval_single_bin(lhs, cmp_op, rhs, engine) + result = pd.eval(ex, engine=engine, parser=parser) + tm.assert_equal(result, expected) + + @pytest.mark.parametrize("op", expr.CMP_OPS_SYMS) + def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser): + if parser == "python" and op in ["in", "not in"]: + msg = "'(In|NotIn)' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + ex = f"~(lhs {op} rhs)" + pd.eval(ex, engine=engine, parser=parser) + return + + if ( + is_float(lhs) + and not is_float(rhs) + and op in ["in", "not in"] + and engine == "python" + and parser == "pandas" + ): + mark = pytest.mark.xfail( + reason="Looks like expected is negative, unclear whether " + "expected is incorrect or result is incorrect" + ) + request.applymarker(mark) + skip_these = ["in", "not in"] + ex = f"~(lhs {op} rhs)" + + msg = "|".join( + [ + r"only list-like( or dict-like)? objects are allowed to be " + r"passed to (DataFrame\.)?isin\(\), you passed a " + r"(`|')float(`|')", + "argument of type 'float' is not iterable", + ] + ) + if is_scalar(rhs) and op in skip_these: + with pytest.raises(TypeError, match=msg): + pd.eval( + ex, + engine=engine, + parser=parser, + local_dict={"lhs": lhs, "rhs": rhs}, + ) + else: + # compound + if is_scalar(lhs) and is_scalar(rhs): + lhs, rhs = (np.array([x]) for x in (lhs, rhs)) + expected = _eval_single_bin(lhs, op, rhs, engine) + if is_scalar(expected): + expected = not expected + else: + expected = ~expected + result = pd.eval(ex, engine=engine, parser=parser) + tm.assert_almost_equal(expected, result) + + @pytest.mark.parametrize("cmp1", ["<", ">"]) + @pytest.mark.parametrize("cmp2", ["<", ">"]) + def test_chained_cmp_op(self, cmp1, cmp2, lhs, midhs, rhs, engine, parser): + mid = midhs + if parser == "python": + ex1 = f"lhs {cmp1} mid {cmp2} rhs" + msg = "'BoolOp' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(ex1, engine=engine, parser=parser) + return + + lhs_new = _eval_single_bin(lhs, cmp1, mid, engine) + rhs_new = _eval_single_bin(mid, cmp2, rhs, engine) + + if lhs_new is not None and rhs_new is not None: + ex1 = f"lhs {cmp1} mid {cmp2} rhs" + ex2 = f"lhs {cmp1} mid and mid {cmp2} rhs" + ex3 = f"(lhs {cmp1} mid) & (mid {cmp2} rhs)" + expected = _eval_single_bin(lhs_new, "&", rhs_new, engine) + + for ex in (ex1, ex2, ex3): + result = pd.eval(ex, engine=engine, parser=parser) + + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize( + "arith1", sorted(set(ARITH_OPS_SYMS).difference(SPECIAL_CASE_ARITH_OPS_SYMS)) + ) + def test_binary_arith_ops(self, arith1, lhs, rhs, engine, parser): + ex = f"lhs {arith1} rhs" + result = pd.eval(ex, engine=engine, parser=parser) + expected = _eval_single_bin(lhs, arith1, rhs, engine) + + tm.assert_almost_equal(result, expected) + ex = f"lhs {arith1} rhs {arith1} rhs" + result = pd.eval(ex, engine=engine, parser=parser) + nlhs = _eval_single_bin(lhs, arith1, rhs, engine) + try: + nlhs, ghs = nlhs.align(rhs) + except (ValueError, TypeError, AttributeError): + # ValueError: series frame or frame series align + # TypeError, AttributeError: series or frame with scalar align + return + else: + if engine == "numexpr": + import numexpr as ne + + # direct numpy comparison + expected = ne.evaluate(f"nlhs {arith1} ghs") + # Update assert statement due to unreliable numerical + # precision component (GH37328) + # TODO: update testing code so that assert_almost_equal statement + # can be replaced again by the assert_numpy_array_equal statement + tm.assert_almost_equal(result.values, expected) + else: + expected = eval(f"nlhs {arith1} ghs") + tm.assert_almost_equal(result, expected) + + # modulus, pow, and floor division require special casing + + def test_modulus(self, lhs, rhs, engine, parser): + ex = r"lhs % rhs" + result = pd.eval(ex, engine=engine, parser=parser) + expected = lhs % rhs + tm.assert_almost_equal(result, expected) + + if engine == "numexpr": + import numexpr as ne + + expected = ne.evaluate(r"expected % rhs") + if isinstance(result, (DataFrame, Series)): + tm.assert_almost_equal(result.values, expected) + else: + tm.assert_almost_equal(result, expected.item()) + else: + expected = _eval_single_bin(expected, "%", rhs, engine) + tm.assert_almost_equal(result, expected) + + def test_floor_division(self, lhs, rhs, engine, parser): + ex = "lhs // rhs" + + if engine == "python" or ( + engine == "numexpr" and Version(numexpr.__version__) >= Version("2.13.0") + ): + res = pd.eval(ex, engine=engine, parser=parser) + expected = lhs // rhs + tm.assert_equal(res, expected) + else: + msg = ( + r"unsupported operand type\(s\) for //: 'VariableNode' and " + "'VariableNode'" + ) + with pytest.raises(TypeError, match=msg): + pd.eval( + ex, + local_dict={"lhs": lhs, "rhs": rhs}, + engine=engine, + parser=parser, + ) + + @td.skip_if_windows + def test_pow(self, lhs, rhs, engine, parser): + # odd failure on win32 platform, so skip + ex = "lhs ** rhs" + expected = _eval_single_bin(lhs, "**", rhs, engine) + result = pd.eval(ex, engine=engine, parser=parser) + + if ( + is_scalar(lhs) + and is_scalar(rhs) + and isinstance(expected, (complex, np.complexfloating)) + and np.isnan(result) + ): + msg = "(DataFrame.columns|numpy array) are different" + with pytest.raises(AssertionError, match=msg): + tm.assert_numpy_array_equal(result, expected) + else: + tm.assert_almost_equal(result, expected) + + ex = "(lhs ** rhs) ** rhs" + result = pd.eval(ex, engine=engine, parser=parser) + + middle = _eval_single_bin(lhs, "**", rhs, engine) + expected = _eval_single_bin(middle, "**", rhs, engine) + tm.assert_almost_equal(result, expected) + + def test_check_single_invert_op(self, lhs, engine, parser): + # simple + try: + elb = lhs.astype(bool) + except AttributeError: + elb = np.array([bool(lhs)]) + expected = ~elb + result = pd.eval("~elb", engine=engine, parser=parser) + tm.assert_almost_equal(expected, result) + + def test_frame_invert(self, engine, parser): + expr = "~lhs" + + # ~ ## + # frame + # float always raises + lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2))) + if engine == "numexpr": + msg = "couldn't find matching opcode for 'invert_dd'" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + else: + msg = "ufunc 'invert' not supported for the input types" + with pytest.raises(TypeError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + + # int raises on numexpr + lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))) + if engine == "numexpr" and Version(numexpr.__version__) < Version("2.13.0"): + msg = "couldn't find matching opcode for 'invert" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + else: + expect = ~lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_frame_equal(expect, result) + + # bool always works + lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5) + expect = ~lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_frame_equal(expect, result) + + # object raises + lhs = DataFrame( + {"b": ["a", 1, 2.0], "c": np.random.default_rng(2).standard_normal(3) > 0.5} + ) + if engine == "numexpr": + with pytest.raises(ValueError, match="unknown type object"): + pd.eval(expr, engine=engine, parser=parser) + else: + msg = "bad operand type for unary ~: 'str'" + with pytest.raises(TypeError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + + def test_series_invert(self, engine, parser): + # ~ #### + expr = "~lhs" + + # series + # float raises + lhs = Series(np.random.default_rng(2).standard_normal(5)) + if engine == "numexpr": + msg = "couldn't find matching opcode for 'invert_dd'" + with pytest.raises(NotImplementedError, match=msg): + result = pd.eval(expr, engine=engine, parser=parser) + else: + msg = "ufunc 'invert' not supported for the input types" + with pytest.raises(TypeError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + + # int raises on numexpr + lhs = Series(np.random.default_rng(2).integers(5, size=5)) + if engine == "numexpr" and Version(numexpr.__version__) < Version("2.13.0"): + msg = "couldn't find matching opcode for 'invert" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + else: + expect = ~lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_series_equal(expect, result) + + # bool + lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5) + expect = ~lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_series_equal(expect, result) + + # float + # int + # bool + + # object + lhs = Series(["a", 1, 2.0]) + if engine == "numexpr": + with pytest.raises(ValueError, match="unknown type object"): + pd.eval(expr, engine=engine, parser=parser) + else: + msg = "bad operand type for unary ~: 'str'" + with pytest.raises(TypeError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + + def test_frame_negate(self, engine, parser): + expr = "-lhs" + + # float + lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2))) + expect = -lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_frame_equal(expect, result) + + # int + lhs = DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))) + expect = -lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_frame_equal(expect, result) + + # bool doesn't work with numexpr but works elsewhere + lhs = DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5) + if engine == "numexpr": + msg = "couldn't find matching opcode for 'neg_bb'" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + else: + expect = -lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_frame_equal(expect, result) + + def test_series_negate(self, engine, parser): + expr = "-lhs" + + # float + lhs = Series(np.random.default_rng(2).standard_normal(5)) + expect = -lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_series_equal(expect, result) + + # int + lhs = Series(np.random.default_rng(2).integers(5, size=5)) + expect = -lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_series_equal(expect, result) + + # bool doesn't work with numexpr but works elsewhere + lhs = Series(np.random.default_rng(2).standard_normal(5) > 0.5) + if engine == "numexpr": + msg = "couldn't find matching opcode for 'neg_bb'" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(expr, engine=engine, parser=parser) + else: + expect = -lhs + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_series_equal(expect, result) + + @pytest.mark.parametrize( + "lhs", + [ + # Float + DataFrame(np.random.default_rng(2).standard_normal((5, 2))), + # Int + DataFrame(np.random.default_rng(2).integers(5, size=(5, 2))), + # bool doesn't work with numexpr but works elsewhere + DataFrame(np.random.default_rng(2).standard_normal((5, 2)) > 0.5), + ], + ) + def test_frame_pos(self, lhs, engine, parser): + expr = "+lhs" + expect = lhs + + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_frame_equal(expect, result) + + @pytest.mark.parametrize( + "lhs", + [ + # Float + Series(np.random.default_rng(2).standard_normal(5)), + # Int + Series(np.random.default_rng(2).integers(5, size=5)), + # bool doesn't work with numexpr but works elsewhere + Series(np.random.default_rng(2).standard_normal(5) > 0.5), + ], + ) + def test_series_pos(self, lhs, engine, parser): + expr = "+lhs" + expect = lhs + + result = pd.eval(expr, engine=engine, parser=parser) + tm.assert_series_equal(expect, result) + + def test_scalar_unary(self, engine, parser): + msg = "bad operand type for unary ~: 'float'" + warn = None + if PY312 and not (engine == "numexpr" and parser == "pandas"): + warn = DeprecationWarning + with pytest.raises(TypeError, match=msg): + pd.eval("~1.0", engine=engine, parser=parser) + + assert pd.eval("-1.0", parser=parser, engine=engine) == -1.0 + assert pd.eval("+1.0", parser=parser, engine=engine) == +1.0 + assert pd.eval("~1", parser=parser, engine=engine) == ~1 + assert pd.eval("-1", parser=parser, engine=engine) == -1 + assert pd.eval("+1", parser=parser, engine=engine) == +1 + with tm.assert_produces_warning( + warn, match="Bitwise inversion", check_stacklevel=False + ): + assert pd.eval("~True", parser=parser, engine=engine) == ~True + with tm.assert_produces_warning( + warn, match="Bitwise inversion", check_stacklevel=False + ): + assert pd.eval("~False", parser=parser, engine=engine) == ~False + assert pd.eval("-True", parser=parser, engine=engine) == -True + assert pd.eval("-False", parser=parser, engine=engine) == -False + assert pd.eval("+True", parser=parser, engine=engine) == +True + assert pd.eval("+False", parser=parser, engine=engine) == +False + + def test_unary_in_array(self): + # GH 11235 + # TODO: 2022-01-29: result return list with numexpr 2.7.3 in CI + # but cannot reproduce locally + result = np.array( + pd.eval("[-True, True, +True, -False, False, +False, -37, 37, ~37, +37]"), + dtype=np.object_, + ) + expected = np.array( + [ + -True, + True, + +True, + -False, + False, + +False, + -37, + 37, + ~37, + +37, + ], + dtype=np.object_, + ) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("expr", ["x < -0.1", "-5 > x"]) + def test_float_comparison_bin_op(self, float_numpy_dtype, expr): + # GH 16363 + df = DataFrame({"x": np.array([0], dtype=float_numpy_dtype)}) + res = df.eval(expr) + assert res.values == np.array([False]) + + def test_unary_in_function(self): + # GH 46471 + df = DataFrame({"x": [0, 1, np.nan]}) + + result = df.eval("x.fillna(-1)") + expected = df.x.fillna(-1) + # column name becomes None if using numexpr + # only check names when the engine is not numexpr + tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR) + + result = df.eval("x.shift(1, fill_value=-1)") + expected = df.x.shift(1, fill_value=-1) + tm.assert_series_equal(result, expected, check_names=not USE_NUMEXPR) + + @pytest.mark.parametrize( + "ex", + ( + "1 or 2", + "1 and 2", + "a and b", + "a or b", + "1 or 2 and (3 + 2) > 3", + "2 * x > 2 or 1 and 2", + "2 * df > 3 and 1 or a", + ), + ) + def test_disallow_scalar_bool_ops(self, ex, engine, parser): + x, a, b = np.random.default_rng(2).standard_normal(3), 1, 2 # noqa: F841 + df = DataFrame(np.random.default_rng(2).standard_normal((3, 2))) # noqa: F841 + + msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(ex, engine=engine, parser=parser) + + def test_identical(self, engine, parser): + # see gh-10546 + x = 1 + result = pd.eval("x", engine=engine, parser=parser) + assert result == 1 + assert is_scalar(result) + + x = 1.5 + result = pd.eval("x", engine=engine, parser=parser) + assert result == 1.5 + assert is_scalar(result) + + x = False + result = pd.eval("x", engine=engine, parser=parser) + assert not result + assert is_bool(result) + assert is_scalar(result) + + x = np.array([1]) + result = pd.eval("x", engine=engine, parser=parser) + tm.assert_numpy_array_equal(result, np.array([1])) + assert result.shape == (1,) + + x = np.array([1.5]) + result = pd.eval("x", engine=engine, parser=parser) + tm.assert_numpy_array_equal(result, np.array([1.5])) + assert result.shape == (1,) + + x = np.array([False]) # noqa: F841 + result = pd.eval("x", engine=engine, parser=parser) + tm.assert_numpy_array_equal(result, np.array([False])) + assert result.shape == (1,) + + def test_line_continuation(self, engine, parser): + # GH 11149 + exp = """1 + 2 * \ + 5 - 1 + 2 """ + result = pd.eval(exp, engine=engine, parser=parser) + assert result == 12 + + def test_float_truncation(self, engine, parser): + # GH 14241 + exp = "1000000000.006" + result = pd.eval(exp, engine=engine, parser=parser) + expected = np.float64(exp) + assert result == expected + + df = DataFrame({"A": [1000000000.0009, 1000000000.0011, 1000000000.0015]}) + cutoff = 1000000000.0006 + result = df.query(f"A < {cutoff:.4f}") + assert result.empty + + cutoff = 1000000000.0010 + result = df.query(f"A > {cutoff:.4f}") + expected = df.loc[[1, 2], :] + tm.assert_frame_equal(expected, result) + + exact = 1000000000.0011 + result = df.query(f"A == {exact:.4f}") + expected = df.loc[[1], :] + tm.assert_frame_equal(expected, result) + + def test_disallow_python_keywords(self): + # GH 18221 + df = DataFrame([[0, 0, 0]], columns=["foo", "bar", "class"]) + msg = "Python keyword not valid identifier in numexpr query" + with pytest.raises(SyntaxError, match=msg): + df.query("class == 0") + + df = DataFrame() + df.index.name = "lambda" + with pytest.raises(SyntaxError, match=msg): + df.query("lambda == 0") + + def test_true_false_logic(self): + # GH 25823 + # This behavior is deprecated in Python 3.12 + with tm.maybe_produces_warning( + DeprecationWarning, PY312, check_stacklevel=False + ): + assert pd.eval("not True") == -2 + assert pd.eval("not False") == -1 + assert pd.eval("True and not True") == 0 + + def test_and_logic_string_match(self): + # GH 25823 + event = Series({"a": "hello"}) + assert pd.eval(f"{event.str.match('hello').a}") + assert pd.eval(f"{event.str.match('hello').a and event.str.match('hello').a}") + + +# ------------------------------------- +# gh-12388: Typecasting rules consistency with python + + +class TestTypeCasting: + @pytest.mark.parametrize("op", ["+", "-", "*", "**", "/"]) + # maybe someday... numexpr has too many upcasting rules now + # chain(*(np.core.sctypes[x] for x in ['uint', 'int', 'float'])) + @pytest.mark.parametrize("left_right", [("df", "3"), ("3", "df")]) + def test_binop_typecasting( + self, engine, parser, op, complex_or_float_dtype, left_right, request + ): + # GH#21374 + dtype = complex_or_float_dtype + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), dtype=dtype) + left, right = left_right + s = f"{left} {op} {right}" + res = pd.eval(s, engine=engine, parser=parser) + if dtype == "complex64" and engine == "numexpr": + mark = pytest.mark.xfail( + reason="numexpr issue with complex that are upcast " + "to complex 128 " + "https://github.com/pydata/numexpr/issues/492" + ) + request.applymarker(mark) + assert df.values.dtype == dtype + assert res.values.dtype == dtype + tm.assert_frame_equal(res, eval(s), check_exact=False) + + +# ------------------------------------- +# Basic and complex alignment + + +def should_warn(*args): + not_mono = not any(map(operator.attrgetter("is_monotonic_increasing"), args)) + only_one_dt = reduce( + operator.xor, (issubclass(x.dtype.type, np.datetime64) for x in args) + ) + return not_mono and only_one_dt + + +class TestAlignment: + index_types = ["i", "s", "dt"] + lhs_index_types = index_types + ["s"] # 'p' + + def test_align_nested_unary_op(self, engine, parser): + s = "df * ~2" + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + res = pd.eval(s, engine=engine, parser=parser) + tm.assert_frame_equal(res, df * ~2) + + @pytest.mark.filterwarnings("always::RuntimeWarning") + @pytest.mark.parametrize("lr_idx_type", lhs_index_types) + @pytest.mark.parametrize("rr_idx_type", index_types) + @pytest.mark.parametrize("c_idx_type", index_types) + def test_basic_frame_alignment( + self, engine, parser, lr_idx_type, rr_idx_type, c_idx_type, idx_func_dict + ): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 10)), + index=idx_func_dict[lr_idx_type](10), + columns=idx_func_dict[c_idx_type](10), + ) + df2 = DataFrame( + np.random.default_rng(2).standard_normal((20, 10)), + index=idx_func_dict[rr_idx_type](20), + columns=idx_func_dict[c_idx_type](10), + ) + # only warns if not monotonic and not sortable + if should_warn(df.index, df2.index): + with tm.assert_produces_warning(RuntimeWarning): + res = pd.eval("df + df2", engine=engine, parser=parser) + else: + res = pd.eval("df + df2", engine=engine, parser=parser) + tm.assert_frame_equal(res, df + df2) + + @pytest.mark.parametrize("r_idx_type", lhs_index_types) + @pytest.mark.parametrize("c_idx_type", lhs_index_types) + def test_frame_comparison( + self, engine, parser, r_idx_type, c_idx_type, idx_func_dict + ): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 10)), + index=idx_func_dict[r_idx_type](10), + columns=idx_func_dict[c_idx_type](10), + ) + res = pd.eval("df < 2", engine=engine, parser=parser) + tm.assert_frame_equal(res, df < 2) + + df3 = DataFrame( + np.random.default_rng(2).standard_normal(df.shape), + index=df.index, + columns=df.columns, + ) + res = pd.eval("df < df3", engine=engine, parser=parser) + tm.assert_frame_equal(res, df < df3) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + @pytest.mark.parametrize("r1", lhs_index_types) + @pytest.mark.parametrize("c1", index_types) + @pytest.mark.parametrize("r2", index_types) + @pytest.mark.parametrize("c2", index_types) + def test_medium_complex_frame_alignment( + self, engine, parser, r1, c1, r2, c2, idx_func_dict + ): + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 2)), + index=idx_func_dict[r1](3), + columns=idx_func_dict[c1](2), + ) + df2 = DataFrame( + np.random.default_rng(2).standard_normal((4, 2)), + index=idx_func_dict[r2](4), + columns=idx_func_dict[c2](2), + ) + df3 = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), + index=idx_func_dict[r2](5), + columns=idx_func_dict[c2](2), + ) + if should_warn(df.index, df2.index, df3.index): + with tm.assert_produces_warning(RuntimeWarning): + res = pd.eval("df + df2 + df3", engine=engine, parser=parser) + else: + res = pd.eval("df + df2 + df3", engine=engine, parser=parser) + tm.assert_frame_equal(res, df + df2 + df3) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + @pytest.mark.parametrize("index_name", ["index", "columns"]) + @pytest.mark.parametrize("c_idx_type", index_types) + @pytest.mark.parametrize("r_idx_type", lhs_index_types) + def test_basic_frame_series_alignment( + self, engine, parser, index_name, r_idx_type, c_idx_type, idx_func_dict + ): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 10)), + index=idx_func_dict[r_idx_type](10), + columns=idx_func_dict[c_idx_type](10), + ) + index = getattr(df, index_name) + s = Series(np.random.default_rng(2).standard_normal(5), index[:5]) + + if should_warn(df.index, s.index): + with tm.assert_produces_warning(RuntimeWarning): + res = pd.eval("df + s", engine=engine, parser=parser) + else: + res = pd.eval("df + s", engine=engine, parser=parser) + + if r_idx_type == "dt" or c_idx_type == "dt": + expected = df.add(s) if engine == "numexpr" else df + s + else: + expected = df + s + tm.assert_frame_equal(res, expected) + + @pytest.mark.parametrize("index_name", ["index", "columns"]) + @pytest.mark.parametrize( + "r_idx_type, c_idx_type", + list(product(["i", "s"], ["i", "s"])) + [("dt", "dt")], + ) + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + def test_basic_series_frame_alignment( + self, request, engine, parser, index_name, r_idx_type, c_idx_type, idx_func_dict + ): + if ( + engine == "numexpr" + and parser in ("pandas", "python") + and index_name == "index" + and r_idx_type == "i" + and c_idx_type == "s" + ): + reason = ( + f"Flaky column ordering when engine={engine}, " + f"parser={parser}, index_name={index_name}, " + f"r_idx_type={r_idx_type}, c_idx_type={c_idx_type}" + ) + request.applymarker(pytest.mark.xfail(reason=reason, strict=False)) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 7)), + index=idx_func_dict[r_idx_type](10), + columns=idx_func_dict[c_idx_type](7), + ) + index = getattr(df, index_name) + s = Series(np.random.default_rng(2).standard_normal(5), index[:5]) + if should_warn(s.index, df.index): + with tm.assert_produces_warning(RuntimeWarning): + res = pd.eval("s + df", engine=engine, parser=parser) + else: + res = pd.eval("s + df", engine=engine, parser=parser) + + if r_idx_type == "dt" or c_idx_type == "dt": + expected = df.add(s) if engine == "numexpr" else s + df + else: + expected = s + df + tm.assert_frame_equal(res, expected) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + @pytest.mark.parametrize("c_idx_type", index_types) + @pytest.mark.parametrize("r_idx_type", lhs_index_types) + @pytest.mark.parametrize("index_name", ["index", "columns"]) + @pytest.mark.parametrize("op", ["+", "*"]) + def test_series_frame_commutativity( + self, engine, parser, index_name, op, r_idx_type, c_idx_type, idx_func_dict + ): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 10)), + index=idx_func_dict[r_idx_type](10), + columns=idx_func_dict[c_idx_type](10), + ) + index = getattr(df, index_name) + s = Series(np.random.default_rng(2).standard_normal(5), index[:5]) + + lhs = f"s {op} df" + rhs = f"df {op} s" + if should_warn(df.index, s.index): + with tm.assert_produces_warning(RuntimeWarning): + a = pd.eval(lhs, engine=engine, parser=parser) + with tm.assert_produces_warning(RuntimeWarning): + b = pd.eval(rhs, engine=engine, parser=parser) + else: + a = pd.eval(lhs, engine=engine, parser=parser) + b = pd.eval(rhs, engine=engine, parser=parser) + + if r_idx_type != "dt" and c_idx_type != "dt": + if engine == "numexpr": + tm.assert_frame_equal(a, b) + + @pytest.mark.filterwarnings("always::RuntimeWarning") + @pytest.mark.parametrize("r1", lhs_index_types) + @pytest.mark.parametrize("c1", index_types) + @pytest.mark.parametrize("r2", index_types) + @pytest.mark.parametrize("c2", index_types) + def test_complex_series_frame_alignment( + self, engine, parser, r1, c1, r2, c2, idx_func_dict + ): + n = 3 + m1 = 5 + m2 = 2 * m1 + df = DataFrame( + np.random.default_rng(2).standard_normal((m1, n)), + index=idx_func_dict[r1](m1), + columns=idx_func_dict[c1](n), + ) + df2 = DataFrame( + np.random.default_rng(2).standard_normal((m2, n)), + index=idx_func_dict[r2](m2), + columns=idx_func_dict[c2](n), + ) + index = df2.columns + ser = Series(np.random.default_rng(2).standard_normal(n), index[:n]) + + if r2 == "dt" or c2 == "dt": + if engine == "numexpr": + expected2 = df2.add(ser) + else: + expected2 = df2 + ser + else: + expected2 = df2 + ser + + if r1 == "dt" or c1 == "dt": + if engine == "numexpr": + expected = expected2.add(df) + else: + expected = expected2 + df + else: + expected = expected2 + df + + if should_warn(df2.index, ser.index, df.index): + with tm.assert_produces_warning(RuntimeWarning): + res = pd.eval("df2 + ser + df", engine=engine, parser=parser) + else: + res = pd.eval("df2 + ser + df", engine=engine, parser=parser) + assert res.shape == expected.shape + tm.assert_frame_equal(res, expected) + + def test_performance_warning_for_poor_alignment(self, engine, parser): + df = DataFrame(np.random.default_rng(2).standard_normal((1000, 10))) + s = Series(np.random.default_rng(2).standard_normal(10000)) + if engine == "numexpr": + seen = PerformanceWarning + else: + seen = False + + with tm.assert_produces_warning(seen): + pd.eval("df + s", engine=engine, parser=parser) + + s = Series(np.random.default_rng(2).standard_normal(1000)) + with tm.assert_produces_warning(False): + pd.eval("df + s", engine=engine, parser=parser) + + df = DataFrame(np.random.default_rng(2).standard_normal((10, 10000))) + s = Series(np.random.default_rng(2).standard_normal(10000)) + with tm.assert_produces_warning(False): + pd.eval("df + s", engine=engine, parser=parser) + + df = DataFrame(np.random.default_rng(2).standard_normal((10, 10))) + s = Series(np.random.default_rng(2).standard_normal(10000)) + + is_python_engine = engine == "python" + + if not is_python_engine: + wrn = PerformanceWarning + else: + wrn = False + + with tm.assert_produces_warning(wrn) as w: + pd.eval("df + s", engine=engine, parser=parser) + + if not is_python_engine: + assert len(w) == 1 + msg = str(w[0].message) + logged = np.log10(s.size - df.shape[1]) + expected = ( + f"Alignment difference on axis 1 is larger " + f"than an order of magnitude on term 'df', " + f"by more than {logged:.4g}; performance may suffer." + ) + assert msg == expected + + +# ------------------------------------ +# Slightly more complex ops + + +class TestOperations: + def eval(self, *args, **kwargs): + kwargs["level"] = kwargs.pop("level", 0) + 1 + return pd.eval(*args, **kwargs) + + def test_simple_arith_ops(self, engine, parser): + exclude_arith = [] + if parser == "python": + exclude_arith = ["in", "not in"] + + arith_ops = [ + op + for op in expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS + if op not in exclude_arith + ] + + ops = (op for op in arith_ops if op != "//") + + for op in ops: + ex = f"1 {op} 1" + ex2 = f"x {op} 1" + ex3 = f"1 {op} (x + 1)" + + if op in ("in", "not in"): + msg = "argument of type 'int' is not iterable" + with pytest.raises(TypeError, match=msg): + pd.eval(ex, engine=engine, parser=parser) + else: + expec = _eval_single_bin(1, op, 1, engine) + x = self.eval(ex, engine=engine, parser=parser) + assert x == expec + + expec = _eval_single_bin(x, op, 1, engine) + y = self.eval(ex2, local_dict={"x": x}, engine=engine, parser=parser) + assert y == expec + + expec = _eval_single_bin(1, op, x + 1, engine) + y = self.eval(ex3, local_dict={"x": x}, engine=engine, parser=parser) + assert y == expec + + @pytest.mark.parametrize("rhs", [True, False]) + @pytest.mark.parametrize("lhs", [True, False]) + @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS) + def test_simple_bool_ops(self, rhs, lhs, op): + ex = f"{lhs} {op} {rhs}" + + if parser == "python" and op in ["and", "or"]: + msg = "'BoolOp' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + self.eval(ex) + return + + res = self.eval(ex) + exp = eval(ex) + assert res == exp + + @pytest.mark.parametrize("rhs", [True, False]) + @pytest.mark.parametrize("lhs", [True, False]) + @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS) + def test_bool_ops_with_constants(self, rhs, lhs, op): + ex = f"{lhs} {op} {rhs}" + + if parser == "python" and op in ["and", "or"]: + msg = "'BoolOp' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + self.eval(ex) + return + + res = self.eval(ex) + exp = eval(ex) + assert res == exp + + def test_4d_ndarray_fails(self): + x = np.random.default_rng(2).standard_normal((3, 4, 5, 6)) + y = Series(np.random.default_rng(2).standard_normal(10)) + msg = "N-dimensional objects, where N > 2, are not supported with eval" + with pytest.raises(NotImplementedError, match=msg): + self.eval("x + y", local_dict={"x": x, "y": y}) + + def test_constant(self): + x = self.eval("1") + assert x == 1 + + def test_single_variable(self): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) + df2 = self.eval("df", local_dict={"df": df}) + tm.assert_frame_equal(df, df2) + + def test_failing_subscript_with_name_error(self): + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841 + with pytest.raises(NameError, match="name 'x' is not defined"): + self.eval("df[x > 2] > 2") + + def test_lhs_expression_subscript(self): + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + result = self.eval("(df + 1)[df > 2]", local_dict={"df": df}) + expected = (df + 1)[df > 2] + tm.assert_frame_equal(result, expected) + + def test_attr_expression(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc") + ) + expr1 = "df.a < df.b" + expec1 = df.a < df.b + expr2 = "df.a + df.b + df.c" + expec2 = df.a + df.b + df.c + expr3 = "df.a + df.b + df.c[df.b < 0]" + expec3 = df.a + df.b + df.c[df.b < 0] + exprs = expr1, expr2, expr3 + expecs = expec1, expec2, expec3 + for e, expec in zip(exprs, expecs): + tm.assert_series_equal(expec, self.eval(e, local_dict={"df": df})) + + def test_assignment_fails(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), columns=list("abc") + ) + df2 = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + expr1 = "df = df2" + msg = "cannot assign without a target object" + with pytest.raises(ValueError, match=msg): + self.eval(expr1, local_dict={"df": df, "df2": df2}) + + def test_assignment_column_multiple_raise(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + # multiple assignees + with pytest.raises(SyntaxError, match="invalid syntax"): + df.eval("d c = a + b") + + def test_assignment_column_invalid_assign(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + # invalid assignees + msg = "left hand side of an assignment must be a single name" + with pytest.raises(SyntaxError, match=msg): + df.eval("d,c = a + b") + + def test_assignment_column_invalid_assign_function_call(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + msg = "cannot assign to function call" + with pytest.raises(SyntaxError, match=msg): + df.eval('Timestamp("20131001") = a + b') + + def test_assignment_single_assign_existing(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + # single assignment - existing variable + expected = df.copy() + expected["a"] = expected["a"] + expected["b"] + df.eval("a = a + b", inplace=True) + tm.assert_frame_equal(df, expected) + + def test_assignment_single_assign_new(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + # single assignment - new variable + expected = df.copy() + expected["c"] = expected["a"] + expected["b"] + df.eval("c = a + b", inplace=True) + tm.assert_frame_equal(df, expected) + + def test_assignment_single_assign_local_overlap(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + df = df.copy() + a = 1 # noqa: F841 + df.eval("a = 1 + b", inplace=True) + + expected = df.copy() + expected["a"] = 1 + expected["b"] + tm.assert_frame_equal(df, expected) + + def test_assignment_single_assign_name(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + + a = 1 # noqa: F841 + old_a = df.a.copy() + df.eval("a = a + b", inplace=True) + result = old_a + df.b + tm.assert_series_equal(result, df.a, check_names=False) + assert result.name is None + + def test_assignment_multiple_raises(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + # multiple assignment + df.eval("c = a + b", inplace=True) + msg = "can only assign a single expression" + with pytest.raises(SyntaxError, match=msg): + df.eval("c = a = b") + + def test_assignment_explicit(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + # explicit targets + self.eval("c = df.a + df.b", local_dict={"df": df}, target=df, inplace=True) + expected = df.copy() + expected["c"] = expected["a"] + expected["b"] + tm.assert_frame_equal(df, expected) + + def test_column_in(self): + # GH 11235 + df = DataFrame({"a": [11], "b": [-32]}) + result = df.eval("a in [11, -32]") + expected = Series([True]) + # TODO: 2022-01-29: Name check failed with numexpr 2.7.3 in CI + # but cannot reproduce locally + tm.assert_series_equal(result, expected, check_names=False) + + @pytest.mark.xfail(reason="Unknown: Omitted test_ in name prior.") + def test_assignment_not_inplace(self): + # see gh-9297 + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") + ) + + actual = df.eval("c = a + b", inplace=False) + assert actual is not None + + expected = df.copy() + expected["c"] = expected["a"] + expected["b"] + tm.assert_frame_equal(df, expected) + + def test_multi_line_expression(self, warn_copy_on_write): + # GH 11149 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + expected = df.copy() + + expected["c"] = expected["a"] + expected["b"] + expected["d"] = expected["c"] + expected["b"] + answer = df.eval( + """ + c = a + b + d = c + b""", + inplace=True, + ) + tm.assert_frame_equal(expected, df) + assert answer is None + + expected["a"] = expected["a"] - 1 + expected["e"] = expected["a"] + 2 + answer = df.eval( + """ + a = a - 1 + e = a + 2""", + inplace=True, + ) + tm.assert_frame_equal(expected, df) + assert answer is None + + # multi-line not valid if not all assignments + msg = "Multi-line expressions are only valid if all expressions contain" + with pytest.raises(ValueError, match=msg): + df.eval( + """ + a = b + 2 + b - 2""", + inplace=False, + ) + + def test_multi_line_expression_not_inplace(self): + # GH 11149 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + expected = df.copy() + + expected["c"] = expected["a"] + expected["b"] + expected["d"] = expected["c"] + expected["b"] + df = df.eval( + """ + c = a + b + d = c + b""", + inplace=False, + ) + tm.assert_frame_equal(expected, df) + + expected["a"] = expected["a"] - 1 + expected["e"] = expected["a"] + 2 + df = df.eval( + """ + a = a - 1 + e = a + 2""", + inplace=False, + ) + tm.assert_frame_equal(expected, df) + + def test_multi_line_expression_local_variable(self): + # GH 15342 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + expected = df.copy() + + local_var = 7 + expected["c"] = expected["a"] * local_var + expected["d"] = expected["c"] + local_var + answer = df.eval( + """ + c = a * @local_var + d = c + @local_var + """, + inplace=True, + ) + tm.assert_frame_equal(expected, df) + assert answer is None + + def test_multi_line_expression_callable_local_variable(self): + # 26426 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + + def local_func(a, b): + return b + + expected = df.copy() + expected["c"] = expected["a"] * local_func(1, 7) + expected["d"] = expected["c"] + local_func(1, 7) + answer = df.eval( + """ + c = a * @local_func(1, 7) + d = c + @local_func(1, 7) + """, + inplace=True, + ) + tm.assert_frame_equal(expected, df) + assert answer is None + + def test_multi_line_expression_callable_local_variable_with_kwargs(self): + # 26426 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + + def local_func(a, b): + return b + + expected = df.copy() + expected["c"] = expected["a"] * local_func(b=7, a=1) + expected["d"] = expected["c"] + local_func(b=7, a=1) + answer = df.eval( + """ + c = a * @local_func(b=7, a=1) + d = c + @local_func(b=7, a=1) + """, + inplace=True, + ) + tm.assert_frame_equal(expected, df) + assert answer is None + + def test_assignment_in_query(self): + # GH 8664 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df_orig = df.copy() + msg = "cannot assign without a target object" + with pytest.raises(ValueError, match=msg): + df.query("a = 1") + tm.assert_frame_equal(df, df_orig) + + def test_query_inplace(self): + # see gh-11149 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + expected = df.copy() + expected = expected[expected["a"] == 2] + df.query("a == 2", inplace=True) + tm.assert_frame_equal(expected, df) + + df = {} + expected = {"a": 3} + + self.eval("a = 1 + 2", target=df, inplace=True) + tm.assert_dict_equal(df, expected) + + @pytest.mark.parametrize("invalid_target", [1, "cat", [1, 2], np.array([]), (1, 3)]) + def test_cannot_item_assign(self, invalid_target): + msg = "Cannot assign expression output to target" + expression = "a = 1 + 2" + + with pytest.raises(ValueError, match=msg): + self.eval(expression, target=invalid_target, inplace=True) + + if hasattr(invalid_target, "copy"): + with pytest.raises(ValueError, match=msg): + self.eval(expression, target=invalid_target, inplace=False) + + @pytest.mark.parametrize("invalid_target", [1, "cat", (1, 3)]) + def test_cannot_copy_item(self, invalid_target): + msg = "Cannot return a copy of the target" + expression = "a = 1 + 2" + + with pytest.raises(ValueError, match=msg): + self.eval(expression, target=invalid_target, inplace=False) + + @pytest.mark.parametrize("target", [1, "cat", [1, 2], np.array([]), (1, 3), {1: 2}]) + def test_inplace_no_assignment(self, target): + expression = "1 + 2" + + assert self.eval(expression, target=target, inplace=False) == 3 + + msg = "Cannot operate inplace if there is no assignment" + with pytest.raises(ValueError, match=msg): + self.eval(expression, target=target, inplace=True) + + def test_basic_period_index_boolean_expression(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((2, 2)), + columns=period_range("2020-01-01", freq="D", periods=2), + ) + e = df < 2 + r = self.eval("df < 2", local_dict={"df": df}) + x = df < 2 + + tm.assert_frame_equal(r, e) + tm.assert_frame_equal(x, e) + + def test_basic_period_index_subscript_expression(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((2, 2)), + columns=period_range("2020-01-01", freq="D", periods=2), + ) + r = self.eval("df[df < 2 + 3]", local_dict={"df": df}) + e = df[df < 2 + 3] + tm.assert_frame_equal(r, e) + + def test_nested_period_index_subscript_expression(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((2, 2)), + columns=period_range("2020-01-01", freq="D", periods=2), + ) + r = self.eval("df[df[df < 2] < 2] + df * 2", local_dict={"df": df}) + e = df[df[df < 2] < 2] + df * 2 + tm.assert_frame_equal(r, e) + + def test_date_boolean(self, engine, parser): + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + df["dates1"] = date_range("1/1/2012", periods=5) + res = self.eval( + "df.dates1 < 20130101", + local_dict={"df": df}, + engine=engine, + parser=parser, + ) + expec = df.dates1 < "20130101" + tm.assert_series_equal(res, expec, check_names=False) + + def test_simple_in_ops(self, engine, parser): + if parser != "python": + res = pd.eval("1 in [1, 2]", engine=engine, parser=parser) + assert res + + res = pd.eval("2 in (1, 2)", engine=engine, parser=parser) + assert res + + res = pd.eval("3 in (1, 2)", engine=engine, parser=parser) + assert not res + + res = pd.eval("3 not in (1, 2)", engine=engine, parser=parser) + assert res + + res = pd.eval("[3] not in (1, 2)", engine=engine, parser=parser) + assert res + + res = pd.eval("[3] in ([3], 2)", engine=engine, parser=parser) + assert res + + res = pd.eval("[[3]] in [[[3]], 2]", engine=engine, parser=parser) + assert res + + res = pd.eval("(3,) in [(3,), 2]", engine=engine, parser=parser) + assert res + + res = pd.eval("(3,) not in [(3,), 2]", engine=engine, parser=parser) + assert not res + + res = pd.eval("[(3,)] in [[(3,)], 2]", engine=engine, parser=parser) + assert res + else: + msg = "'In' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + pd.eval("1 in [1, 2]", engine=engine, parser=parser) + with pytest.raises(NotImplementedError, match=msg): + pd.eval("2 in (1, 2)", engine=engine, parser=parser) + with pytest.raises(NotImplementedError, match=msg): + pd.eval("3 in (1, 2)", engine=engine, parser=parser) + with pytest.raises(NotImplementedError, match=msg): + pd.eval("[(3,)] in (1, 2, [(3,)])", engine=engine, parser=parser) + msg = "'NotIn' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + pd.eval("3 not in (1, 2)", engine=engine, parser=parser) + with pytest.raises(NotImplementedError, match=msg): + pd.eval("[3] not in (1, 2, [[3]])", engine=engine, parser=parser) + + def test_check_many_exprs(self, engine, parser): + a = 1 # noqa: F841 + expr = " * ".join("a" * 33) + expected = 1 + res = pd.eval(expr, engine=engine, parser=parser) + assert res == expected + + @pytest.mark.parametrize( + "expr", + [ + "df > 2 and df > 3", + "df > 2 or df > 3", + "not df > 2", + ], + ) + def test_fails_and_or_not(self, expr, engine, parser): + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) + if parser == "python": + msg = "'BoolOp' nodes are not implemented" + if "not" in expr: + msg = "'Not' nodes are not implemented" + + with pytest.raises(NotImplementedError, match=msg): + pd.eval( + expr, + local_dict={"df": df}, + parser=parser, + engine=engine, + ) + else: + # smoke-test, should not raise + pd.eval( + expr, + local_dict={"df": df}, + parser=parser, + engine=engine, + ) + + @pytest.mark.parametrize("char", ["|", "&"]) + def test_fails_ampersand_pipe(self, char, engine, parser): + df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # noqa: F841 + ex = f"(df + 2)[df > 1] > 0 {char} (df > 0)" + if parser == "python": + msg = "cannot evaluate scalar only bool ops" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(ex, parser=parser, engine=engine) + else: + # smoke-test, should not raise + pd.eval(ex, parser=parser, engine=engine) + + +class TestMath: + def eval(self, *args, **kwargs): + kwargs["level"] = kwargs.pop("level", 0) + 1 + return pd.eval(*args, **kwargs) + + @pytest.mark.skipif( + not NUMEXPR_INSTALLED, reason="Unary ops only implemented for numexpr" + ) + @pytest.mark.parametrize("fn", _unary_math_ops) + def test_unary_functions(self, fn): + df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)}) + a = df.a + + expr = f"{fn}(a)" + got = self.eval(expr) + with np.errstate(all="ignore"): + expect = getattr(np, fn)(a) + tm.assert_series_equal(got, expect, check_names=False) + + @pytest.mark.parametrize("fn", _binary_math_ops) + def test_binary_functions(self, fn): + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(10), + "b": np.random.default_rng(2).standard_normal(10), + } + ) + a = df.a + b = df.b + + expr = f"{fn}(a, b)" + got = self.eval(expr) + with np.errstate(all="ignore"): + expect = getattr(np, fn)(a, b) + tm.assert_almost_equal(got, expect, check_names=False) + + def test_df_use_case(self, engine, parser): + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(10), + "b": np.random.default_rng(2).standard_normal(10), + } + ) + df.eval( + "e = arctan2(sin(a), b)", + engine=engine, + parser=parser, + inplace=True, + ) + got = df.e + expect = np.arctan2(np.sin(df.a), df.b) + tm.assert_series_equal(got, expect, check_names=False) + + def test_df_arithmetic_subexpression(self, engine, parser): + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(10), + "b": np.random.default_rng(2).standard_normal(10), + } + ) + df.eval("e = sin(a + b)", engine=engine, parser=parser, inplace=True) + got = df.e + expect = np.sin(df.a + df.b) + tm.assert_series_equal(got, expect, check_names=False) + + @pytest.mark.parametrize( + "dtype, expect_dtype", + [ + (np.int32, np.float64), + (np.int64, np.float64), + (np.float32, np.float32), + (np.float64, np.float64), + pytest.param(np.complex128, np.complex128, marks=td.skip_if_windows), + ], + ) + def test_result_types(self, dtype, expect_dtype, engine, parser): + # xref https://github.com/pandas-dev/pandas/issues/12293 + # this fails on Windows, apparently a floating point precision issue + + # Did not test complex64 because DataFrame is converting it to + # complex128. Due to https://github.com/pandas-dev/pandas/issues/10952 + df = DataFrame( + {"a": np.random.default_rng(2).standard_normal(10).astype(dtype)} + ) + assert df.a.dtype == dtype + df.eval("b = sin(a)", engine=engine, parser=parser, inplace=True) + got = df.b + expect = np.sin(df.a) + assert expect.dtype == got.dtype + assert expect_dtype == got.dtype + tm.assert_series_equal(got, expect, check_names=False) + + def test_undefined_func(self, engine, parser): + df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)}) + msg = '"mysin" is not a supported function' + + with pytest.raises(ValueError, match=msg): + df.eval("mysin(a)", engine=engine, parser=parser) + + def test_keyword_arg(self, engine, parser): + df = DataFrame({"a": np.random.default_rng(2).standard_normal(10)}) + msg = 'Function "sin" does not support keyword arguments' + + with pytest.raises(TypeError, match=msg): + df.eval("sin(x=a)", engine=engine, parser=parser) + + +_var_s = np.random.default_rng(2).standard_normal(10) + + +class TestScope: + def test_global_scope(self, engine, parser): + e = "_var_s * 2" + tm.assert_numpy_array_equal( + _var_s * 2, pd.eval(e, engine=engine, parser=parser) + ) + + def test_no_new_locals(self, engine, parser): + x = 1 + lcls = locals().copy() + pd.eval("x + 1", local_dict=lcls, engine=engine, parser=parser) + lcls2 = locals().copy() + lcls2.pop("lcls") + assert lcls == lcls2 + + def test_no_new_globals(self, engine, parser): + x = 1 # noqa: F841 + gbls = globals().copy() + pd.eval("x + 1", engine=engine, parser=parser) + gbls2 = globals().copy() + assert gbls == gbls2 + + def test_empty_locals(self, engine, parser): + # GH 47084 + x = 1 # noqa: F841 + msg = "name 'x' is not defined" + with pytest.raises(UndefinedVariableError, match=msg): + pd.eval("x + 1", engine=engine, parser=parser, local_dict={}) + + def test_empty_globals(self, engine, parser): + # GH 47084 + msg = "name '_var_s' is not defined" + e = "_var_s * 2" + with pytest.raises(UndefinedVariableError, match=msg): + pd.eval(e, engine=engine, parser=parser, global_dict={}) + + +@td.skip_if_no("numexpr") +def test_invalid_engine(): + msg = "Invalid engine 'asdf' passed" + with pytest.raises(KeyError, match=msg): + pd.eval("x + y", local_dict={"x": 1, "y": 2}, engine="asdf") + + +@td.skip_if_no("numexpr") +@pytest.mark.parametrize( + ("use_numexpr", "expected"), + ( + (True, "numexpr"), + (False, "python"), + ), +) +def test_numexpr_option_respected(use_numexpr, expected): + # GH 32556 + from pandas.core.computation.eval import _check_engine + + with pd.option_context("compute.use_numexpr", use_numexpr): + result = _check_engine(None) + assert result == expected + + +@td.skip_if_no("numexpr") +def test_numexpr_option_incompatible_op(): + # GH 32556 + with pd.option_context("compute.use_numexpr", False): + df = DataFrame( + {"A": [True, False, True, False, None, None], "B": [1, 2, 3, 4, 5, 6]} + ) + result = df.query("A.isnull()") + expected = DataFrame({"A": [None, None], "B": [5, 6]}, index=[4, 5]) + tm.assert_frame_equal(result, expected) + + +@td.skip_if_no("numexpr") +def test_invalid_parser(): + msg = "Invalid parser 'asdf' passed" + with pytest.raises(KeyError, match=msg): + pd.eval("x + y", local_dict={"x": 1, "y": 2}, parser="asdf") + + +_parsers: dict[str, type[BaseExprVisitor]] = { + "python": PythonExprVisitor, + "pytables": pytables.PyTablesExprVisitor, + "pandas": PandasExprVisitor, +} + + +@pytest.mark.parametrize("engine", ENGINES) +@pytest.mark.parametrize("parser", _parsers) +def test_disallowed_nodes(engine, parser): + VisitorClass = _parsers[parser] + inst = VisitorClass("x + 1", engine, parser) + + for ops in VisitorClass.unsupported_nodes: + msg = "nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + getattr(inst, ops)() + + +def test_syntax_error_exprs(engine, parser): + e = "s +" + with pytest.raises(SyntaxError, match="invalid syntax"): + pd.eval(e, engine=engine, parser=parser) + + +def test_name_error_exprs(engine, parser): + e = "s + t" + msg = "name 's' is not defined" + with pytest.raises(NameError, match=msg): + pd.eval(e, engine=engine, parser=parser) + + +@pytest.mark.parametrize("express", ["a + @b", "@a + b", "@a + @b"]) +def test_invalid_local_variable_reference(engine, parser, express): + a, b = 1, 2 # noqa: F841 + + if parser != "pandas": + with pytest.raises(SyntaxError, match="The '@' prefix is only"): + pd.eval(express, engine=engine, parser=parser) + else: + with pytest.raises(SyntaxError, match="The '@' prefix is not"): + pd.eval(express, engine=engine, parser=parser) + + +def test_numexpr_builtin_raises(engine, parser): + sin, dotted_line = 1, 2 + if engine == "numexpr": + msg = "Variables in expression .+" + with pytest.raises(NumExprClobberingError, match=msg): + pd.eval("sin + dotted_line", engine=engine, parser=parser) + else: + res = pd.eval("sin + dotted_line", engine=engine, parser=parser) + assert res == sin + dotted_line + + +def test_bad_resolver_raises(engine, parser): + cannot_resolve = 42, 3.0 + with pytest.raises(TypeError, match="Resolver of type .+"): + pd.eval("1 + 2", resolvers=cannot_resolve, engine=engine, parser=parser) + + +def test_empty_string_raises(engine, parser): + # GH 13139 + with pytest.raises(ValueError, match="expr cannot be an empty string"): + pd.eval("", engine=engine, parser=parser) + + +def test_more_than_one_expression_raises(engine, parser): + with pytest.raises(SyntaxError, match="only a single expression is allowed"): + pd.eval("1 + 1; 2 + 2", engine=engine, parser=parser) + + +@pytest.mark.parametrize("cmp", ("and", "or")) +@pytest.mark.parametrize("lhs", (int, float)) +@pytest.mark.parametrize("rhs", (int, float)) +def test_bool_ops_fails_on_scalars(lhs, cmp, rhs, engine, parser): + gen = { + int: lambda: np.random.default_rng(2).integers(10), + float: np.random.default_rng(2).standard_normal, + } + + mid = gen[lhs]() # noqa: F841 + lhs = gen[lhs]() + rhs = gen[rhs]() + + ex1 = f"lhs {cmp} mid {cmp} rhs" + ex2 = f"lhs {cmp} mid and mid {cmp} rhs" + ex3 = f"(lhs {cmp} mid) & (mid {cmp} rhs)" + for ex in (ex1, ex2, ex3): + msg = "cannot evaluate scalar only bool ops|'BoolOp' nodes are not" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(ex, engine=engine, parser=parser) + + +@pytest.mark.parametrize( + "other", + [ + "'x'", + "...", + ], +) +def test_equals_various(other): + df = DataFrame({"A": ["a", "b", "c"]}, dtype=object) + result = df.eval(f"A == {other}") + expected = Series([False, False, False], name="A") + if USE_NUMEXPR: + # https://github.com/pandas-dev/pandas/issues/10239 + # lose name with numexpr engine. Remove when that's fixed. + expected.name = None + tm.assert_series_equal(result, expected) + + +def test_inf(engine, parser): + s = "inf + 1" + expected = np.inf + result = pd.eval(s, engine=engine, parser=parser) + assert result == expected + + +@pytest.mark.parametrize("column", ["Temp(°C)", "Capacitance(μF)"]) +def test_query_token(engine, column): + # See: https://github.com/pandas-dev/pandas/pull/42826 + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 2)), columns=[column, "b"] + ) + expected = df[df[column] > 5] + query_string = f"`{column}` > 5" + result = df.query(query_string, engine=engine) + tm.assert_frame_equal(result, expected) + + +def test_negate_lt_eq_le(engine, parser): + df = DataFrame([[0, 10], [1, 20]], columns=["cat", "count"]) + expected = df[~(df.cat > 0)] + + result = df.query("~(cat > 0)", engine=engine, parser=parser) + tm.assert_frame_equal(result, expected) + + if parser == "python": + msg = "'Not' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + df.query("not (cat > 0)", engine=engine, parser=parser) + else: + result = df.query("not (cat > 0)", engine=engine, parser=parser) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "column", + DEFAULT_GLOBALS.keys(), +) +def test_eval_no_support_column_name(request, column): + # GH 44603 + if column in ["True", "False", "inf", "Inf"]: + request.applymarker( + pytest.mark.xfail( + raises=KeyError, + reason=f"GH 47859 DataFrame eval not supported with {column}", + ) + ) + + df = DataFrame( + np.random.default_rng(2).integers(0, 100, size=(10, 2)), + columns=[column, "col1"], + ) + expected = df[df[column] > 6] + result = df.query(f"{column}>6") + + tm.assert_frame_equal(result, expected) + + +def test_set_inplace(using_copy_on_write, warn_copy_on_write): + # https://github.com/pandas-dev/pandas/issues/47449 + # Ensure we don't only update the DataFrame inplace, but also the actual + # column values, such that references to this column also get updated + df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) + result_view = df[:] + ser = df["A"] + with tm.assert_cow_warning(warn_copy_on_write): + df.eval("A = B + C", inplace=True) + expected = DataFrame({"A": [11, 13, 15], "B": [4, 5, 6], "C": [7, 8, 9]}) + tm.assert_frame_equal(df, expected) + if not using_copy_on_write: + tm.assert_series_equal(ser, expected["A"]) + tm.assert_series_equal(result_view["A"], expected["A"]) + else: + expected = Series([1, 2, 3], name="A") + tm.assert_series_equal(ser, expected) + tm.assert_series_equal(result_view["A"], expected) + + +class TestValidate: + @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) + def test_validate_bool_args(self, value): + msg = 'For argument "inplace" expected type bool, received type' + with pytest.raises(ValueError, match=msg): + pd.eval("2+2", inplace=value) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/__init__.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_common.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..579f5636922dc3fb4ed652e1fa374607ec57501a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_common.py @@ -0,0 +1,865 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from pandas.compat import HAS_PYARROW +import pandas.util._test_decorators as td + +from pandas.core.dtypes.astype import astype_array +import pandas.core.dtypes.common as com +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + CategoricalDtypeType, + DatetimeTZDtype, + ExtensionDtype, + IntervalDtype, + PeriodDtype, +) +from pandas.core.dtypes.missing import isna + +import pandas as pd +import pandas._testing as tm +from pandas.api.types import pandas_dtype +from pandas.arrays import SparseArray +from pandas.util.version import Version + + +# EA & Actual Dtypes +def to_ea_dtypes(dtypes): + """convert list of string dtypes to EA dtype""" + return [getattr(pd, dt + "Dtype") for dt in dtypes] + + +def to_numpy_dtypes(dtypes): + """convert list of string dtypes to numpy dtype""" + return [getattr(np, dt) for dt in dtypes if isinstance(dt, str)] + + +class TestNumpyEADtype: + # Passing invalid dtype, both as a string or object, must raise TypeError + # Per issue GH15520 + @pytest.mark.parametrize("box", [pd.Timestamp, "pd.Timestamp", list]) + def test_invalid_dtype_error(self, box): + with pytest.raises(TypeError, match="not understood"): + com.pandas_dtype(box) + + @pytest.mark.parametrize( + "dtype", + [ + object, + "float64", + np.object_, + np.dtype("object"), + "O", + np.float64, + float, + np.dtype("float64"), + "object_", + ], + ) + def test_pandas_dtype_valid(self, dtype): + assert com.pandas_dtype(dtype) == dtype + + @pytest.mark.parametrize( + "dtype", ["M8[ns]", "m8[ns]", "object", "float64", "int64"] + ) + def test_numpy_dtype(self, dtype): + assert com.pandas_dtype(dtype) == np.dtype(dtype) + + def test_numpy_string_dtype(self): + # do not parse freq-like string as period dtype + assert com.pandas_dtype("U") == np.dtype("U") + assert com.pandas_dtype("S") == np.dtype("S") + + @pytest.mark.parametrize( + "dtype", + [ + "datetime64[ns, US/Eastern]", + "datetime64[ns, Asia/Tokyo]", + "datetime64[ns, UTC]", + # GH#33885 check that the M8 alias is understood + "M8[ns, US/Eastern]", + "M8[ns, Asia/Tokyo]", + "M8[ns, UTC]", + ], + ) + def test_datetimetz_dtype(self, dtype): + assert com.pandas_dtype(dtype) == DatetimeTZDtype.construct_from_string(dtype) + assert com.pandas_dtype(dtype) == dtype + + def test_categorical_dtype(self): + assert com.pandas_dtype("category") == CategoricalDtype() + + @pytest.mark.parametrize( + "dtype", + [ + "period[D]", + "period[3M]", + "period[us]", + "Period[D]", + "Period[3M]", + "Period[us]", + ], + ) + def test_period_dtype(self, dtype): + assert com.pandas_dtype(dtype) is not PeriodDtype(dtype) + assert com.pandas_dtype(dtype) == PeriodDtype(dtype) + assert com.pandas_dtype(dtype) == dtype + + +dtypes = { + "datetime_tz": com.pandas_dtype("datetime64[ns, US/Eastern]"), + "datetime": com.pandas_dtype("datetime64[ns]"), + "timedelta": com.pandas_dtype("timedelta64[ns]"), + "period": PeriodDtype("D"), + "integer": np.dtype(np.int64), + "float": np.dtype(np.float64), + "object": np.dtype(object), + "category": com.pandas_dtype("category"), + "string": pd.StringDtype(), +} + + +@pytest.mark.parametrize("name1,dtype1", list(dtypes.items()), ids=lambda x: str(x)) +@pytest.mark.parametrize("name2,dtype2", list(dtypes.items()), ids=lambda x: str(x)) +def test_dtype_equal(name1, dtype1, name2, dtype2): + # match equal to self, but not equal to other + assert com.is_dtype_equal(dtype1, dtype1) + if name1 != name2: + assert not com.is_dtype_equal(dtype1, dtype2) + + +@pytest.mark.parametrize("name,dtype", list(dtypes.items()), ids=lambda x: str(x)) +def test_pyarrow_string_import_error(name, dtype): + # GH-44276 + assert not com.is_dtype_equal(dtype, "string[pyarrow]") + + +@pytest.mark.parametrize( + "dtype1,dtype2", + [ + (np.int8, np.int64), + (np.int16, np.int64), + (np.int32, np.int64), + (np.float32, np.float64), + (PeriodDtype("D"), PeriodDtype("2D")), # PeriodType + ( + com.pandas_dtype("datetime64[ns, US/Eastern]"), + com.pandas_dtype("datetime64[ns, CET]"), + ), # Datetime + (None, None), # gh-15941: no exception should be raised. + ], +) +def test_dtype_equal_strict(dtype1, dtype2): + assert not com.is_dtype_equal(dtype1, dtype2) + + +def get_is_dtype_funcs(): + """ + Get all functions in pandas.core.dtypes.common that + begin with 'is_' and end with 'dtype' + + """ + fnames = [f for f in dir(com) if (f.startswith("is_") and f.endswith("dtype"))] + fnames.remove("is_string_or_object_np_dtype") # fastpath requires np.dtype obj + return [getattr(com, fname) for fname in fnames] + + +@pytest.mark.filterwarnings( + "ignore:is_categorical_dtype is deprecated:DeprecationWarning" +) +@pytest.mark.parametrize("func", get_is_dtype_funcs(), ids=lambda x: x.__name__) +def test_get_dtype_error_catch(func): + # see gh-15941 + # + # No exception should be raised. + + msg = f"{func.__name__} is deprecated" + warn = None + if ( + func is com.is_int64_dtype + or func is com.is_interval_dtype + or func is com.is_datetime64tz_dtype + or func is com.is_categorical_dtype + or func is com.is_period_dtype + ): + warn = DeprecationWarning + + with tm.assert_produces_warning(warn, match=msg): + assert not func(None) + + +def test_is_object(): + assert com.is_object_dtype(object) + assert com.is_object_dtype(np.array([], dtype=object)) + + assert not com.is_object_dtype(int) + assert not com.is_object_dtype(np.array([], dtype=int)) + assert not com.is_object_dtype([1, 2, 3]) + + +@pytest.mark.parametrize( + "check_scipy", [False, pytest.param(True, marks=td.skip_if_no("scipy"))] +) +def test_is_sparse(check_scipy): + msg = "is_sparse is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert com.is_sparse(SparseArray([1, 2, 3])) + + assert not com.is_sparse(np.array([1, 2, 3])) + + if check_scipy: + import scipy.sparse + + assert not com.is_sparse(scipy.sparse.bsr_matrix([1, 2, 3])) + + +def test_is_scipy_sparse(): + sp_sparse = pytest.importorskip("scipy.sparse") + + assert com.is_scipy_sparse(sp_sparse.bsr_matrix([1, 2, 3])) + + assert not com.is_scipy_sparse(SparseArray([1, 2, 3])) + + +def test_is_datetime64_dtype(): + assert not com.is_datetime64_dtype(object) + assert not com.is_datetime64_dtype([1, 2, 3]) + assert not com.is_datetime64_dtype(np.array([], dtype=int)) + + assert com.is_datetime64_dtype(np.datetime64) + assert com.is_datetime64_dtype(np.array([], dtype=np.datetime64)) + + +def test_is_datetime64tz_dtype(): + msg = "is_datetime64tz_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert not com.is_datetime64tz_dtype(object) + assert not com.is_datetime64tz_dtype([1, 2, 3]) + assert not com.is_datetime64tz_dtype(pd.DatetimeIndex([1, 2, 3])) + assert com.is_datetime64tz_dtype(pd.DatetimeIndex(["2000"], tz="US/Eastern")) + + +def test_custom_ea_kind_M_not_datetime64tz(): + # GH 34986 + class NotTZDtype(ExtensionDtype): + @property + def kind(self) -> str: + return "M" + + not_tz_dtype = NotTZDtype() + msg = "is_datetime64tz_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert not com.is_datetime64tz_dtype(not_tz_dtype) + assert not com.needs_i8_conversion(not_tz_dtype) + + +def test_is_timedelta64_dtype(): + assert not com.is_timedelta64_dtype(object) + assert not com.is_timedelta64_dtype(None) + assert not com.is_timedelta64_dtype([1, 2, 3]) + assert not com.is_timedelta64_dtype(np.array([], dtype=np.datetime64)) + assert not com.is_timedelta64_dtype("0 days") + assert not com.is_timedelta64_dtype("0 days 00:00:00") + assert not com.is_timedelta64_dtype(["0 days 00:00:00"]) + assert not com.is_timedelta64_dtype("NO DATE") + + assert com.is_timedelta64_dtype(np.timedelta64) + assert com.is_timedelta64_dtype(pd.Series([], dtype="timedelta64[ns]")) + assert com.is_timedelta64_dtype(pd.to_timedelta(["0 days", "1 days"])) + + +def test_is_period_dtype(): + msg = "is_period_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert not com.is_period_dtype(object) + assert not com.is_period_dtype([1, 2, 3]) + assert not com.is_period_dtype(pd.Period("2017-01-01")) + + assert com.is_period_dtype(PeriodDtype(freq="D")) + assert com.is_period_dtype(pd.PeriodIndex([], freq="Y")) + + +def test_is_interval_dtype(): + msg = "is_interval_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert not com.is_interval_dtype(object) + assert not com.is_interval_dtype([1, 2, 3]) + + assert com.is_interval_dtype(IntervalDtype()) + + interval = pd.Interval(1, 2, closed="right") + assert not com.is_interval_dtype(interval) + assert com.is_interval_dtype(pd.IntervalIndex([interval])) + + +def test_is_categorical_dtype(): + msg = "is_categorical_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert not com.is_categorical_dtype(object) + assert not com.is_categorical_dtype([1, 2, 3]) + + assert com.is_categorical_dtype(CategoricalDtype()) + assert com.is_categorical_dtype(pd.Categorical([1, 2, 3])) + assert com.is_categorical_dtype(pd.CategoricalIndex([1, 2, 3])) + + +@pytest.mark.parametrize( + "dtype, expected", + [ + (int, False), + (pd.Series([1, 2]), False), + (str, True), + (object, True), + (np.array(["a", "b"]), True), + (pd.StringDtype(), True), + (pd.Index([], dtype="O"), True), + ], +) +def test_is_string_dtype(dtype, expected): + # GH#54661 + + result = com.is_string_dtype(dtype) + assert result is expected + + +@pytest.mark.parametrize( + "data", + [[(0, 1), (1, 1)], pd.Categorical([1, 2, 3]), np.array([1, 2], dtype=object)], +) +def test_is_string_dtype_arraylike_with_object_elements_not_strings(data): + # GH 15585 + assert not com.is_string_dtype(pd.Series(data)) + + +def test_is_string_dtype_nullable(nullable_string_dtype): + assert com.is_string_dtype(pd.array(["a", "b"], dtype=nullable_string_dtype)) + + +integer_dtypes: list = [] + + +@pytest.mark.parametrize( + "dtype", + integer_dtypes + + [pd.Series([1, 2])] + + tm.ALL_INT_NUMPY_DTYPES + + to_numpy_dtypes(tm.ALL_INT_NUMPY_DTYPES) + + tm.ALL_INT_EA_DTYPES + + to_ea_dtypes(tm.ALL_INT_EA_DTYPES), +) +def test_is_integer_dtype(dtype): + assert com.is_integer_dtype(dtype) + + +@pytest.mark.parametrize( + "dtype", + [ + str, + float, + np.datetime64, + np.timedelta64, + pd.Index([1, 2.0]), + np.array(["a", "b"]), + np.array([], dtype=np.timedelta64), + ], +) +def test_is_not_integer_dtype(dtype): + assert not com.is_integer_dtype(dtype) + + +signed_integer_dtypes: list = [] + + +@pytest.mark.parametrize( + "dtype", + signed_integer_dtypes + + [pd.Series([1, 2])] + + tm.SIGNED_INT_NUMPY_DTYPES + + to_numpy_dtypes(tm.SIGNED_INT_NUMPY_DTYPES) + + tm.SIGNED_INT_EA_DTYPES + + to_ea_dtypes(tm.SIGNED_INT_EA_DTYPES), +) +def test_is_signed_integer_dtype(dtype): + assert com.is_integer_dtype(dtype) + + +@pytest.mark.parametrize( + "dtype", + [ + str, + float, + np.datetime64, + np.timedelta64, + pd.Index([1, 2.0]), + np.array(["a", "b"]), + np.array([], dtype=np.timedelta64), + ] + + tm.UNSIGNED_INT_NUMPY_DTYPES + + to_numpy_dtypes(tm.UNSIGNED_INT_NUMPY_DTYPES) + + tm.UNSIGNED_INT_EA_DTYPES + + to_ea_dtypes(tm.UNSIGNED_INT_EA_DTYPES), +) +def test_is_not_signed_integer_dtype(dtype): + assert not com.is_signed_integer_dtype(dtype) + + +unsigned_integer_dtypes: list = [] + + +@pytest.mark.parametrize( + "dtype", + unsigned_integer_dtypes + + [pd.Series([1, 2], dtype=np.uint32)] + + tm.UNSIGNED_INT_NUMPY_DTYPES + + to_numpy_dtypes(tm.UNSIGNED_INT_NUMPY_DTYPES) + + tm.UNSIGNED_INT_EA_DTYPES + + to_ea_dtypes(tm.UNSIGNED_INT_EA_DTYPES), +) +def test_is_unsigned_integer_dtype(dtype): + assert com.is_unsigned_integer_dtype(dtype) + + +@pytest.mark.parametrize( + "dtype", + [ + str, + float, + np.datetime64, + np.timedelta64, + pd.Index([1, 2.0]), + np.array(["a", "b"]), + np.array([], dtype=np.timedelta64), + ] + + tm.SIGNED_INT_NUMPY_DTYPES + + to_numpy_dtypes(tm.SIGNED_INT_NUMPY_DTYPES) + + tm.SIGNED_INT_EA_DTYPES + + to_ea_dtypes(tm.SIGNED_INT_EA_DTYPES), +) +def test_is_not_unsigned_integer_dtype(dtype): + assert not com.is_unsigned_integer_dtype(dtype) + + +@pytest.mark.parametrize( + "dtype", [np.int64, np.array([1, 2], dtype=np.int64), "Int64", pd.Int64Dtype] +) +def test_is_int64_dtype(dtype): + msg = "is_int64_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert com.is_int64_dtype(dtype) + + +def test_type_comparison_with_numeric_ea_dtype(any_numeric_ea_dtype): + # GH#43038 + assert pandas_dtype(any_numeric_ea_dtype) == any_numeric_ea_dtype + + +def test_type_comparison_with_real_numpy_dtype(any_real_numpy_dtype): + # GH#43038 + assert pandas_dtype(any_real_numpy_dtype) == any_real_numpy_dtype + + +def test_type_comparison_with_signed_int_ea_dtype_and_signed_int_numpy_dtype( + any_signed_int_ea_dtype, any_signed_int_numpy_dtype +): + # GH#43038 + assert not pandas_dtype(any_signed_int_ea_dtype) == any_signed_int_numpy_dtype + + +@pytest.mark.parametrize( + "dtype", + [ + str, + float, + np.int32, + np.uint64, + pd.Index([1, 2.0]), + np.array(["a", "b"]), + np.array([1, 2], dtype=np.uint32), + "int8", + "Int8", + pd.Int8Dtype, + ], +) +def test_is_not_int64_dtype(dtype): + msg = "is_int64_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert not com.is_int64_dtype(dtype) + + +def test_is_datetime64_any_dtype(): + assert not com.is_datetime64_any_dtype(int) + assert not com.is_datetime64_any_dtype(str) + assert not com.is_datetime64_any_dtype(np.array([1, 2])) + assert not com.is_datetime64_any_dtype(np.array(["a", "b"])) + + assert com.is_datetime64_any_dtype(np.datetime64) + assert com.is_datetime64_any_dtype(np.array([], dtype=np.datetime64)) + assert com.is_datetime64_any_dtype(DatetimeTZDtype("ns", "US/Eastern")) + assert com.is_datetime64_any_dtype( + pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]") + ) + + +def test_is_datetime64_ns_dtype(): + assert not com.is_datetime64_ns_dtype(int) + assert not com.is_datetime64_ns_dtype(str) + assert not com.is_datetime64_ns_dtype(np.datetime64) + assert not com.is_datetime64_ns_dtype(np.array([1, 2])) + assert not com.is_datetime64_ns_dtype(np.array(["a", "b"])) + assert not com.is_datetime64_ns_dtype(np.array([], dtype=np.datetime64)) + + # This datetime array has the wrong unit (ps instead of ns) + assert not com.is_datetime64_ns_dtype(np.array([], dtype="datetime64[ps]")) + + assert com.is_datetime64_ns_dtype(DatetimeTZDtype("ns", "US/Eastern")) + assert com.is_datetime64_ns_dtype( + pd.DatetimeIndex([1, 2, 3], dtype=np.dtype("datetime64[ns]")) + ) + + # non-nano dt64tz + assert not com.is_datetime64_ns_dtype(DatetimeTZDtype("us", "US/Eastern")) + + +def test_is_timedelta64_ns_dtype(): + assert not com.is_timedelta64_ns_dtype(np.dtype("m8[ps]")) + assert not com.is_timedelta64_ns_dtype(np.array([1, 2], dtype=np.timedelta64)) + + assert com.is_timedelta64_ns_dtype(np.dtype("m8[ns]")) + assert com.is_timedelta64_ns_dtype(np.array([1, 2], dtype="m8[ns]")) + + +def test_is_numeric_v_string_like(): + assert not com.is_numeric_v_string_like(np.array([1]), 1) + assert not com.is_numeric_v_string_like(np.array([1]), np.array([2])) + assert not com.is_numeric_v_string_like(np.array(["foo"]), np.array(["foo"])) + + assert com.is_numeric_v_string_like(np.array([1]), "foo") + assert com.is_numeric_v_string_like(np.array([1, 2]), np.array(["foo"])) + assert com.is_numeric_v_string_like(np.array(["foo"]), np.array([1, 2])) + + +def test_needs_i8_conversion(): + assert not com.needs_i8_conversion(str) + assert not com.needs_i8_conversion(np.int64) + assert not com.needs_i8_conversion(pd.Series([1, 2])) + assert not com.needs_i8_conversion(np.array(["a", "b"])) + + assert not com.needs_i8_conversion(np.datetime64) + assert com.needs_i8_conversion(np.dtype(np.datetime64)) + assert not com.needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]")) + assert com.needs_i8_conversion(pd.Series([], dtype="timedelta64[ns]").dtype) + assert not com.needs_i8_conversion(pd.DatetimeIndex(["2000"], tz="US/Eastern")) + assert com.needs_i8_conversion(pd.DatetimeIndex(["2000"], tz="US/Eastern").dtype) + + +def test_is_numeric_dtype(): + assert not com.is_numeric_dtype(str) + assert not com.is_numeric_dtype(np.datetime64) + assert not com.is_numeric_dtype(np.timedelta64) + assert not com.is_numeric_dtype(np.array(["a", "b"])) + assert not com.is_numeric_dtype(np.array([], dtype=np.timedelta64)) + + assert com.is_numeric_dtype(int) + assert com.is_numeric_dtype(float) + assert com.is_numeric_dtype(np.uint64) + assert com.is_numeric_dtype(pd.Series([1, 2])) + assert com.is_numeric_dtype(pd.Index([1, 2.0])) + + class MyNumericDType(ExtensionDtype): + @property + def type(self): + return str + + @property + def name(self): + raise NotImplementedError + + @classmethod + def construct_array_type(cls): + raise NotImplementedError + + def _is_numeric(self) -> bool: + return True + + assert com.is_numeric_dtype(MyNumericDType()) + + +def test_is_any_real_numeric_dtype(): + assert not com.is_any_real_numeric_dtype(str) + assert not com.is_any_real_numeric_dtype(bool) + assert not com.is_any_real_numeric_dtype(complex) + assert not com.is_any_real_numeric_dtype(object) + assert not com.is_any_real_numeric_dtype(np.datetime64) + assert not com.is_any_real_numeric_dtype(np.array(["a", "b", complex(1, 2)])) + assert not com.is_any_real_numeric_dtype(pd.DataFrame([complex(1, 2), True])) + + assert com.is_any_real_numeric_dtype(int) + assert com.is_any_real_numeric_dtype(float) + assert com.is_any_real_numeric_dtype(np.array([1, 2.5])) + + +def test_is_float_dtype(): + assert not com.is_float_dtype(str) + assert not com.is_float_dtype(int) + assert not com.is_float_dtype(pd.Series([1, 2])) + assert not com.is_float_dtype(np.array(["a", "b"])) + + assert com.is_float_dtype(float) + assert com.is_float_dtype(pd.Index([1, 2.0])) + + +def test_is_bool_dtype(): + assert not com.is_bool_dtype(int) + assert not com.is_bool_dtype(str) + assert not com.is_bool_dtype(pd.Series([1, 2])) + assert not com.is_bool_dtype(pd.Series(["a", "b"], dtype="category")) + assert not com.is_bool_dtype(np.array(["a", "b"])) + assert not com.is_bool_dtype(pd.Index(["a", "b"])) + assert not com.is_bool_dtype("Int64") + + assert com.is_bool_dtype(bool) + assert com.is_bool_dtype(np.bool_) + assert com.is_bool_dtype(pd.Series([True, False], dtype="category")) + assert com.is_bool_dtype(np.array([True, False])) + assert com.is_bool_dtype(pd.Index([True, False])) + + assert com.is_bool_dtype(pd.BooleanDtype()) + assert com.is_bool_dtype(pd.array([True, False, None], dtype="boolean")) + assert com.is_bool_dtype("boolean") + + +def test_is_bool_dtype_numpy_error(): + # GH39010 + assert not com.is_bool_dtype("0 - Name") + + +@pytest.mark.parametrize( + "check_scipy", [False, pytest.param(True, marks=td.skip_if_no("scipy"))] +) +def test_is_extension_array_dtype(check_scipy): + assert not com.is_extension_array_dtype([1, 2, 3]) + assert not com.is_extension_array_dtype(np.array([1, 2, 3])) + assert not com.is_extension_array_dtype(pd.DatetimeIndex([1, 2, 3])) + + cat = pd.Categorical([1, 2, 3]) + assert com.is_extension_array_dtype(cat) + assert com.is_extension_array_dtype(pd.Series(cat)) + assert com.is_extension_array_dtype(SparseArray([1, 2, 3])) + assert com.is_extension_array_dtype(pd.DatetimeIndex(["2000"], tz="US/Eastern")) + + dtype = DatetimeTZDtype("ns", tz="US/Eastern") + s = pd.Series([], dtype=dtype) + assert com.is_extension_array_dtype(s) + + if check_scipy: + import scipy.sparse + + assert not com.is_extension_array_dtype(scipy.sparse.bsr_matrix([1, 2, 3])) + + +def test_is_complex_dtype(): + assert not com.is_complex_dtype(int) + assert not com.is_complex_dtype(str) + assert not com.is_complex_dtype(pd.Series([1, 2])) + assert not com.is_complex_dtype(np.array(["a", "b"])) + + assert com.is_complex_dtype(np.complex128) + assert com.is_complex_dtype(complex) + assert com.is_complex_dtype(np.array([1 + 1j, 5])) + + +@pytest.mark.parametrize( + "input_param,result", + [ + (int, np.dtype(int)), + ("int32", np.dtype("int32")), + (float, np.dtype(float)), + ("float64", np.dtype("float64")), + (np.dtype("float64"), np.dtype("float64")), + (str, np.dtype(str)), + (pd.Series([1, 2], dtype=np.dtype("int16")), np.dtype("int16")), + (pd.Series(["a", "b"], dtype=object), np.dtype(object)), + (pd.Index([1, 2]), np.dtype("int64")), + (pd.Index(["a", "b"], dtype=object), np.dtype(object)), + ("category", "category"), + (pd.Categorical(["a", "b"]).dtype, CategoricalDtype(["a", "b"])), + (pd.Categorical(["a", "b"]), CategoricalDtype(["a", "b"])), + (pd.CategoricalIndex(["a", "b"]).dtype, CategoricalDtype(["a", "b"])), + (pd.CategoricalIndex(["a", "b"]), CategoricalDtype(["a", "b"])), + (CategoricalDtype(), CategoricalDtype()), + (pd.DatetimeIndex([1, 2]), np.dtype("=M8[ns]")), + (pd.DatetimeIndex([1, 2]).dtype, np.dtype("=M8[ns]")), + (" df.two.sum() + + with tm.assert_produces_warning(None): + # successfully modify column in place + # this should not raise a warning + df.one += 1 + assert df.one.iloc[0] == 2 + + with tm.assert_produces_warning(None): + # successfully add an attribute to a series + # this should not raise a warning + df.two.not_an_index = [1, 2] + + with tm.assert_produces_warning(UserWarning): + # warn when setting column to nonexistent name + df.four = df.two + 2 + assert df.four.sum() > df.two.sum() diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_inference.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..79b7e6ff092b6efc519d8b29ad134c8019c6602f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_inference.py @@ -0,0 +1,2072 @@ +""" +These the test the public routines exposed in types/common.py +related to inference and not otherwise tested in types/test_common.py + +""" +import collections +from collections import namedtuple +from collections.abc import Iterator +from datetime import ( + date, + datetime, + time, + timedelta, +) +from decimal import Decimal +from fractions import Fraction +from io import StringIO +import itertools +from numbers import Number +import re +import sys +from typing import ( + Generic, + TypeVar, +) + +import numpy as np +import pytest +import pytz + +from pandas._libs import ( + lib, + missing as libmissing, + ops as libops, +) +from pandas.compat.numpy import np_version_gt2 + +from pandas.core.dtypes import inference +from pandas.core.dtypes.cast import find_result_type +from pandas.core.dtypes.common import ( + ensure_int32, + is_bool, + is_complex, + is_datetime64_any_dtype, + is_datetime64_dtype, + is_datetime64_ns_dtype, + is_datetime64tz_dtype, + is_float, + is_integer, + is_number, + is_scalar, + is_scipy_sparse, + is_timedelta64_dtype, + is_timedelta64_ns_dtype, +) + +import pandas as pd +from pandas import ( + Categorical, + DataFrame, + DateOffset, + DatetimeIndex, + Index, + Interval, + Period, + PeriodIndex, + Series, + Timedelta, + TimedeltaIndex, + Timestamp, +) +import pandas._testing as tm +from pandas.core.arrays import ( + BooleanArray, + FloatingArray, + IntegerArray, +) + + +@pytest.fixture(params=[True, False], ids=str) +def coerce(request): + return request.param + + +class MockNumpyLikeArray: + """ + A class which is numpy-like (e.g. Pint's Quantity) but not actually numpy + + The key is that it is not actually a numpy array so + ``util.is_array(mock_numpy_like_array_instance)`` returns ``False``. Other + important properties are that the class defines a :meth:`__iter__` method + (so that ``isinstance(abc.Iterable)`` returns ``True``) and has a + :meth:`ndim` property, as pandas special-cases 0-dimensional arrays in some + cases. + + We expect pandas to behave with respect to such duck arrays exactly as + with real numpy arrays. In particular, a 0-dimensional duck array is *NOT* + a scalar (`is_scalar(np.array(1)) == False`), but it is not list-like either. + """ + + def __init__(self, values) -> None: + self._values = values + + def __iter__(self) -> Iterator: + iter_values = iter(self._values) + + def it_outer(): + yield from iter_values + + return it_outer() + + def __len__(self) -> int: + return len(self._values) + + def __array__(self, dtype=None, copy=None): + return np.asarray(self._values, dtype=dtype) + + @property + def ndim(self): + return self._values.ndim + + @property + def dtype(self): + return self._values.dtype + + @property + def size(self): + return self._values.size + + @property + def shape(self): + return self._values.shape + + +# collect all objects to be tested for list-like-ness; use tuples of objects, +# whether they are list-like or not (special casing for sets), and their ID +ll_params = [ + ([1], True, "list"), + ([], True, "list-empty"), + ((1,), True, "tuple"), + ((), True, "tuple-empty"), + ({"a": 1}, True, "dict"), + ({}, True, "dict-empty"), + ({"a", 1}, "set", "set"), + (set(), "set", "set-empty"), + (frozenset({"a", 1}), "set", "frozenset"), + (frozenset(), "set", "frozenset-empty"), + (iter([1, 2]), True, "iterator"), + (iter([]), True, "iterator-empty"), + ((x for x in [1, 2]), True, "generator"), + ((_ for _ in []), True, "generator-empty"), + (Series([1]), True, "Series"), + (Series([], dtype=object), True, "Series-empty"), + # Series.str will still raise a TypeError if iterated + (Series(["a"]).str, True, "StringMethods"), + (Series([], dtype="O").str, True, "StringMethods-empty"), + (Index([1]), True, "Index"), + (Index([]), True, "Index-empty"), + (DataFrame([[1]]), True, "DataFrame"), + (DataFrame(), True, "DataFrame-empty"), + (np.ndarray((2,) * 1), True, "ndarray-1d"), + (np.array([]), True, "ndarray-1d-empty"), + (np.ndarray((2,) * 2), True, "ndarray-2d"), + (np.array([[]]), True, "ndarray-2d-empty"), + (np.ndarray((2,) * 3), True, "ndarray-3d"), + (np.array([[[]]]), True, "ndarray-3d-empty"), + (np.ndarray((2,) * 4), True, "ndarray-4d"), + (np.array([[[[]]]]), True, "ndarray-4d-empty"), + (np.array(2), False, "ndarray-0d"), + (MockNumpyLikeArray(np.ndarray((2,) * 1)), True, "duck-ndarray-1d"), + (MockNumpyLikeArray(np.array([])), True, "duck-ndarray-1d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 2)), True, "duck-ndarray-2d"), + (MockNumpyLikeArray(np.array([[]])), True, "duck-ndarray-2d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 3)), True, "duck-ndarray-3d"), + (MockNumpyLikeArray(np.array([[[]]])), True, "duck-ndarray-3d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 4)), True, "duck-ndarray-4d"), + (MockNumpyLikeArray(np.array([[[[]]]])), True, "duck-ndarray-4d-empty"), + (MockNumpyLikeArray(np.array(2)), False, "duck-ndarray-0d"), + (1, False, "int"), + (b"123", False, "bytes"), + (b"", False, "bytes-empty"), + ("123", False, "string"), + ("", False, "string-empty"), + (str, False, "string-type"), + (object(), False, "object"), + (np.nan, False, "NaN"), + (None, False, "None"), +] +objs, expected, ids = zip(*ll_params) + + +@pytest.fixture(params=zip(objs, expected), ids=ids) +def maybe_list_like(request): + return request.param + + +def test_is_list_like(maybe_list_like): + obj, expected = maybe_list_like + expected = True if expected == "set" else expected + assert inference.is_list_like(obj) == expected + + +def test_is_list_like_disallow_sets(maybe_list_like): + obj, expected = maybe_list_like + expected = False if expected == "set" else expected + assert inference.is_list_like(obj, allow_sets=False) == expected + + +def test_is_list_like_recursion(): + # GH 33721 + # interpreter would crash with SIGABRT + def list_like(): + inference.is_list_like([]) + list_like() + + rec_limit = sys.getrecursionlimit() + try: + # Limit to avoid stack overflow on Windows CI + sys.setrecursionlimit(100) + with tm.external_error_raised(RecursionError): + list_like() + finally: + sys.setrecursionlimit(rec_limit) + + +def test_is_list_like_iter_is_none(): + # GH 43373 + # is_list_like was yielding false positives with __iter__ == None + class NotListLike: + def __getitem__(self, item): + return self + + __iter__ = None + + assert not inference.is_list_like(NotListLike()) + + +def test_is_list_like_generic(): + # GH 49649 + # is_list_like was yielding false positives for Generic classes in python 3.11 + T = TypeVar("T") + + class MyDataFrame(DataFrame, Generic[T]): + ... + + tstc = MyDataFrame[int] + tst = MyDataFrame[int]({"x": [1, 2, 3]}) + + assert not inference.is_list_like(tstc) + assert isinstance(tst, DataFrame) + assert inference.is_list_like(tst) + + +def test_is_sequence(): + is_seq = inference.is_sequence + assert is_seq((1, 2)) + assert is_seq([1, 2]) + assert not is_seq("abcd") + assert not is_seq(np.int64) + + class A: + def __getitem__(self, item): + return 1 + + assert not is_seq(A()) + + +def test_is_array_like(): + assert inference.is_array_like(Series([], dtype=object)) + assert inference.is_array_like(Series([1, 2])) + assert inference.is_array_like(np.array(["a", "b"])) + assert inference.is_array_like(Index(["2016-01-01"])) + assert inference.is_array_like(np.array([2, 3])) + assert inference.is_array_like(MockNumpyLikeArray(np.array([2, 3]))) + + class DtypeList(list): + dtype = "special" + + assert inference.is_array_like(DtypeList()) + + assert not inference.is_array_like([1, 2, 3]) + assert not inference.is_array_like(()) + assert not inference.is_array_like("foo") + assert not inference.is_array_like(123) + + +@pytest.mark.parametrize( + "inner", + [ + [], + [1], + (1,), + (1, 2), + {"a": 1}, + {1, "a"}, + Series([1]), + Series([], dtype=object), + Series(["a"]).str, + (x for x in range(5)), + ], +) +@pytest.mark.parametrize("outer", [list, Series, np.array, tuple]) +def test_is_nested_list_like_passes(inner, outer): + result = outer([inner for _ in range(5)]) + assert inference.is_list_like(result) + + +@pytest.mark.parametrize( + "obj", + [ + "abc", + [], + [1], + (1,), + ["a"], + "a", + {"a"}, + [1, 2, 3], + Series([1]), + DataFrame({"A": [1]}), + ([1, 2] for _ in range(5)), + ], +) +def test_is_nested_list_like_fails(obj): + assert not inference.is_nested_list_like(obj) + + +@pytest.mark.parametrize("ll", [{}, {"A": 1}, Series([1]), collections.defaultdict()]) +def test_is_dict_like_passes(ll): + assert inference.is_dict_like(ll) + + +@pytest.mark.parametrize( + "ll", + [ + "1", + 1, + [1, 2], + (1, 2), + range(2), + Index([1]), + dict, + collections.defaultdict, + Series, + ], +) +def test_is_dict_like_fails(ll): + assert not inference.is_dict_like(ll) + + +@pytest.mark.parametrize("has_keys", [True, False]) +@pytest.mark.parametrize("has_getitem", [True, False]) +@pytest.mark.parametrize("has_contains", [True, False]) +def test_is_dict_like_duck_type(has_keys, has_getitem, has_contains): + class DictLike: + def __init__(self, d) -> None: + self.d = d + + if has_keys: + + def keys(self): + return self.d.keys() + + if has_getitem: + + def __getitem__(self, key): + return self.d.__getitem__(key) + + if has_contains: + + def __contains__(self, key) -> bool: + return self.d.__contains__(key) + + d = DictLike({1: 2}) + result = inference.is_dict_like(d) + expected = has_keys and has_getitem and has_contains + + assert result is expected + + +def test_is_file_like(): + class MockFile: + pass + + is_file = inference.is_file_like + + data = StringIO("data") + assert is_file(data) + + # No read / write attributes + # No iterator attributes + m = MockFile() + assert not is_file(m) + + MockFile.write = lambda self: 0 + + # Write attribute but not an iterator + m = MockFile() + assert not is_file(m) + + # gh-16530: Valid iterator just means we have the + # __iter__ attribute for our purposes. + MockFile.__iter__ = lambda self: self + + # Valid write-only file + m = MockFile() + assert is_file(m) + + del MockFile.write + MockFile.read = lambda self: 0 + + # Valid read-only file + m = MockFile() + assert is_file(m) + + # Iterator but no read / write attributes + data = [1, 2, 3] + assert not is_file(data) + + +test_tuple = collections.namedtuple("test_tuple", ["a", "b", "c"]) + + +@pytest.mark.parametrize("ll", [test_tuple(1, 2, 3)]) +def test_is_names_tuple_passes(ll): + assert inference.is_named_tuple(ll) + + +@pytest.mark.parametrize("ll", [(1, 2, 3), "a", Series({"pi": 3.14})]) +def test_is_names_tuple_fails(ll): + assert not inference.is_named_tuple(ll) + + +def test_is_hashable(): + # all new-style classes are hashable by default + class HashableClass: + pass + + class UnhashableClass1: + __hash__ = None + + class UnhashableClass2: + def __hash__(self): + raise TypeError("Not hashable") + + hashable = (1, 3.14, np.float64(3.14), "a", (), (1,), HashableClass()) + not_hashable = ([], UnhashableClass1()) + abc_hashable_not_really_hashable = (([],), UnhashableClass2()) + + for i in hashable: + assert inference.is_hashable(i) + for i in not_hashable: + assert not inference.is_hashable(i) + for i in abc_hashable_not_really_hashable: + assert not inference.is_hashable(i) + + # numpy.array is no longer collections.abc.Hashable as of + # https://github.com/numpy/numpy/pull/5326, just test + # is_hashable() + assert not inference.is_hashable(np.array([])) + + +@pytest.mark.parametrize("ll", [re.compile("ad")]) +def test_is_re_passes(ll): + assert inference.is_re(ll) + + +@pytest.mark.parametrize("ll", ["x", 2, 3, object()]) +def test_is_re_fails(ll): + assert not inference.is_re(ll) + + +@pytest.mark.parametrize( + "ll", [r"a", "x", r"asdf", re.compile("adsf"), r"\u2233\s*", re.compile(r"")] +) +def test_is_recompilable_passes(ll): + assert inference.is_re_compilable(ll) + + +@pytest.mark.parametrize("ll", [1, [], object()]) +def test_is_recompilable_fails(ll): + assert not inference.is_re_compilable(ll) + + +class TestInference: + @pytest.mark.parametrize( + "arr", + [ + np.array(list("abc"), dtype="S1"), + np.array(list("abc"), dtype="S1").astype(object), + [b"a", np.nan, b"c"], + ], + ) + def test_infer_dtype_bytes(self, arr): + result = lib.infer_dtype(arr, skipna=True) + assert result == "bytes" + + @pytest.mark.parametrize( + "value, expected", + [ + (float("inf"), True), + (np.inf, True), + (-np.inf, False), + (1, False), + ("a", False), + ], + ) + def test_isposinf_scalar(self, value, expected): + # GH 11352 + result = libmissing.isposinf_scalar(value) + assert result is expected + + @pytest.mark.parametrize( + "value, expected", + [ + (float("-inf"), True), + (-np.inf, True), + (np.inf, False), + (1, False), + ("a", False), + ], + ) + def test_isneginf_scalar(self, value, expected): + result = libmissing.isneginf_scalar(value) + assert result is expected + + @pytest.mark.parametrize( + "convert_to_masked_nullable, exp", + [ + ( + True, + BooleanArray( + np.array([True, False], dtype="bool"), np.array([False, True]) + ), + ), + (False, np.array([True, np.nan], dtype="object")), + ], + ) + def test_maybe_convert_nullable_boolean(self, convert_to_masked_nullable, exp): + # GH 40687 + arr = np.array([True, np.nan], dtype=object) + result = libops.maybe_convert_bool( + arr, set(), convert_to_masked_nullable=convert_to_masked_nullable + ) + if convert_to_masked_nullable: + tm.assert_extension_array_equal(BooleanArray(*result), exp) + else: + result = result[0] + tm.assert_numpy_array_equal(result, exp) + + @pytest.mark.parametrize("convert_to_masked_nullable", [True, False]) + @pytest.mark.parametrize("coerce_numeric", [True, False]) + @pytest.mark.parametrize( + "infinity", ["inf", "inF", "iNf", "Inf", "iNF", "InF", "INf", "INF"] + ) + @pytest.mark.parametrize("prefix", ["", "-", "+"]) + def test_maybe_convert_numeric_infinities( + self, coerce_numeric, infinity, prefix, convert_to_masked_nullable + ): + # see gh-13274 + result, _ = lib.maybe_convert_numeric( + np.array([prefix + infinity], dtype=object), + na_values={"", "NULL", "nan"}, + coerce_numeric=coerce_numeric, + convert_to_masked_nullable=convert_to_masked_nullable, + ) + expected = np.array([np.inf if prefix in ["", "+"] else -np.inf]) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("convert_to_masked_nullable", [True, False]) + def test_maybe_convert_numeric_infinities_raises(self, convert_to_masked_nullable): + msg = "Unable to parse string" + with pytest.raises(ValueError, match=msg): + lib.maybe_convert_numeric( + np.array(["foo_inf"], dtype=object), + na_values={"", "NULL", "nan"}, + coerce_numeric=False, + convert_to_masked_nullable=convert_to_masked_nullable, + ) + + @pytest.mark.parametrize("convert_to_masked_nullable", [True, False]) + def test_maybe_convert_numeric_post_floatify_nan( + self, coerce, convert_to_masked_nullable + ): + # see gh-13314 + data = np.array(["1.200", "-999.000", "4.500"], dtype=object) + expected = np.array([1.2, np.nan, 4.5], dtype=np.float64) + nan_values = {-999, -999.0} + + out = lib.maybe_convert_numeric( + data, + nan_values, + coerce, + convert_to_masked_nullable=convert_to_masked_nullable, + ) + if convert_to_masked_nullable: + expected = FloatingArray(expected, np.isnan(expected)) + tm.assert_extension_array_equal(expected, FloatingArray(*out)) + else: + out = out[0] + tm.assert_numpy_array_equal(out, expected) + + def test_convert_infs(self): + arr = np.array(["inf", "inf", "inf"], dtype="O") + result, _ = lib.maybe_convert_numeric(arr, set(), False) + assert result.dtype == np.float64 + + arr = np.array(["-inf", "-inf", "-inf"], dtype="O") + result, _ = lib.maybe_convert_numeric(arr, set(), False) + assert result.dtype == np.float64 + + def test_scientific_no_exponent(self): + # See PR 12215 + arr = np.array(["42E", "2E", "99e", "6e"], dtype="O") + result, _ = lib.maybe_convert_numeric(arr, set(), False, True) + assert np.all(np.isnan(result)) + + def test_convert_non_hashable(self): + # GH13324 + # make sure that we are handing non-hashables + arr = np.array([[10.0, 2], 1.0, "apple"], dtype=object) + result, _ = lib.maybe_convert_numeric(arr, set(), False, True) + tm.assert_numpy_array_equal(result, np.array([np.nan, 1.0, np.nan])) + + def test_convert_numeric_uint64(self): + arr = np.array([2**63], dtype=object) + exp = np.array([2**63], dtype=np.uint64) + tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp) + + arr = np.array([str(2**63)], dtype=object) + exp = np.array([2**63], dtype=np.uint64) + tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp) + + arr = np.array([np.uint64(2**63)], dtype=object) + exp = np.array([2**63], dtype=np.uint64) + tm.assert_numpy_array_equal(lib.maybe_convert_numeric(arr, set())[0], exp) + + @pytest.mark.parametrize( + "arr", + [ + np.array([2**63, np.nan], dtype=object), + np.array([str(2**63), np.nan], dtype=object), + np.array([np.nan, 2**63], dtype=object), + np.array([np.nan, str(2**63)], dtype=object), + ], + ) + def test_convert_numeric_uint64_nan(self, coerce, arr): + expected = arr.astype(float) if coerce else arr.copy() + result, _ = lib.maybe_convert_numeric(arr, set(), coerce_numeric=coerce) + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize("convert_to_masked_nullable", [True, False]) + def test_convert_numeric_uint64_nan_values( + self, coerce, convert_to_masked_nullable + ): + arr = np.array([2**63, 2**63 + 1], dtype=object) + na_values = {2**63} + + expected = ( + np.array([np.nan, 2**63 + 1], dtype=float) if coerce else arr.copy() + ) + result = lib.maybe_convert_numeric( + arr, + na_values, + coerce_numeric=coerce, + convert_to_masked_nullable=convert_to_masked_nullable, + ) + if convert_to_masked_nullable and coerce: + expected = IntegerArray( + np.array([0, 2**63 + 1], dtype="u8"), + np.array([True, False], dtype="bool"), + ) + result = IntegerArray(*result) + else: + result = result[0] # discard mask + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize( + "case", + [ + np.array([2**63, -1], dtype=object), + np.array([str(2**63), -1], dtype=object), + np.array([str(2**63), str(-1)], dtype=object), + np.array([-1, 2**63], dtype=object), + np.array([-1, str(2**63)], dtype=object), + np.array([str(-1), str(2**63)], dtype=object), + ], + ) + @pytest.mark.parametrize("convert_to_masked_nullable", [True, False]) + def test_convert_numeric_int64_uint64( + self, case, coerce, convert_to_masked_nullable + ): + expected = case.astype(float) if coerce else case.copy() + result, _ = lib.maybe_convert_numeric( + case, + set(), + coerce_numeric=coerce, + convert_to_masked_nullable=convert_to_masked_nullable, + ) + + tm.assert_almost_equal(result, expected) + + @pytest.mark.parametrize("convert_to_masked_nullable", [True, False]) + def test_convert_numeric_string_uint64(self, convert_to_masked_nullable): + # GH32394 + result = lib.maybe_convert_numeric( + np.array(["uint64"], dtype=object), + set(), + coerce_numeric=True, + convert_to_masked_nullable=convert_to_masked_nullable, + ) + if convert_to_masked_nullable: + result = FloatingArray(*result) + else: + result = result[0] + assert np.isnan(result) + + @pytest.mark.parametrize("value", [-(2**63) - 1, 2**64]) + def test_convert_int_overflow(self, value): + # see gh-18584 + arr = np.array([value], dtype=object) + result = lib.maybe_convert_objects(arr) + tm.assert_numpy_array_equal(arr, result) + + @pytest.mark.parametrize("val", [None, np.nan, float("nan")]) + @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) + def test_maybe_convert_objects_nat_inference(self, val, dtype): + dtype = np.dtype(dtype) + vals = np.array([pd.NaT, val], dtype=object) + result = lib.maybe_convert_objects( + vals, + convert_non_numeric=True, + dtype_if_all_nat=dtype, + ) + assert result.dtype == dtype + assert np.isnat(result).all() + + result = lib.maybe_convert_objects( + vals[::-1], + convert_non_numeric=True, + dtype_if_all_nat=dtype, + ) + assert result.dtype == dtype + assert np.isnat(result).all() + + @pytest.mark.parametrize( + "value, expected_dtype", + [ + # see gh-4471 + ([2**63], np.uint64), + # NumPy bug: can't compare uint64 to int64, as that + # results in both casting to float64, so we should + # make sure that this function is robust against it + ([np.uint64(2**63)], np.uint64), + ([2, -1], np.int64), + ([2**63, -1], object), + # GH#47294 + ([np.uint8(1)], np.uint8), + ([np.uint16(1)], np.uint16), + ([np.uint32(1)], np.uint32), + ([np.uint64(1)], np.uint64), + ([np.uint8(2), np.uint16(1)], np.uint16), + ([np.uint32(2), np.uint16(1)], np.uint32), + ([np.uint32(2), -1], object), + ([np.uint32(2), 1], np.uint64), + ([np.uint32(2), np.int32(1)], object), + ], + ) + def test_maybe_convert_objects_uint(self, value, expected_dtype): + arr = np.array(value, dtype=object) + exp = np.array(value, dtype=expected_dtype) + tm.assert_numpy_array_equal(lib.maybe_convert_objects(arr), exp) + + def test_maybe_convert_objects_datetime(self): + # GH27438 + arr = np.array( + [np.datetime64("2000-01-01"), np.timedelta64(1, "s")], dtype=object + ) + exp = arr.copy() + out = lib.maybe_convert_objects(arr, convert_non_numeric=True) + tm.assert_numpy_array_equal(out, exp) + + arr = np.array([pd.NaT, np.timedelta64(1, "s")], dtype=object) + exp = np.array([np.timedelta64("NaT"), np.timedelta64(1, "s")], dtype="m8[ns]") + out = lib.maybe_convert_objects(arr, convert_non_numeric=True) + tm.assert_numpy_array_equal(out, exp) + + # with convert_non_numeric=True, the nan is a valid NA value for td64 + arr = np.array([np.timedelta64(1, "s"), np.nan], dtype=object) + exp = exp[::-1] + out = lib.maybe_convert_objects(arr, convert_non_numeric=True) + tm.assert_numpy_array_equal(out, exp) + + def test_maybe_convert_objects_dtype_if_all_nat(self): + arr = np.array([pd.NaT, pd.NaT], dtype=object) + out = lib.maybe_convert_objects(arr, convert_non_numeric=True) + # no dtype_if_all_nat passed -> we dont guess + tm.assert_numpy_array_equal(out, arr) + + out = lib.maybe_convert_objects( + arr, + convert_non_numeric=True, + dtype_if_all_nat=np.dtype("timedelta64[ns]"), + ) + exp = np.array(["NaT", "NaT"], dtype="timedelta64[ns]") + tm.assert_numpy_array_equal(out, exp) + + out = lib.maybe_convert_objects( + arr, + convert_non_numeric=True, + dtype_if_all_nat=np.dtype("datetime64[ns]"), + ) + exp = np.array(["NaT", "NaT"], dtype="datetime64[ns]") + tm.assert_numpy_array_equal(out, exp) + + def test_maybe_convert_objects_dtype_if_all_nat_invalid(self): + # we accept datetime64[ns], timedelta64[ns], and EADtype + arr = np.array([pd.NaT, pd.NaT], dtype=object) + + with pytest.raises(ValueError, match="int64"): + lib.maybe_convert_objects( + arr, + convert_non_numeric=True, + dtype_if_all_nat=np.dtype("int64"), + ) + + @pytest.mark.parametrize("dtype", ["datetime64[ns]", "timedelta64[ns]"]) + def test_maybe_convert_objects_datetime_overflow_safe(self, dtype): + stamp = datetime(2363, 10, 4) # Enterprise-D launch date + if dtype == "timedelta64[ns]": + stamp = stamp - datetime(1970, 1, 1) + arr = np.array([stamp], dtype=object) + + out = lib.maybe_convert_objects(arr, convert_non_numeric=True) + # no OutOfBoundsDatetime/OutOfBoundsTimedeltas + tm.assert_numpy_array_equal(out, arr) + + def test_maybe_convert_objects_mixed_datetimes(self): + ts = Timestamp("now") + vals = [ts, ts.to_pydatetime(), ts.to_datetime64(), pd.NaT, np.nan, None] + + for data in itertools.permutations(vals): + data = np.array(list(data), dtype=object) + expected = DatetimeIndex(data)._data._ndarray + result = lib.maybe_convert_objects(data, convert_non_numeric=True) + tm.assert_numpy_array_equal(result, expected) + + def test_maybe_convert_objects_timedelta64_nat(self): + obj = np.timedelta64("NaT", "ns") + arr = np.array([obj], dtype=object) + assert arr[0] is obj + + result = lib.maybe_convert_objects(arr, convert_non_numeric=True) + + expected = np.array([obj], dtype="m8[ns]") + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "exp", + [ + IntegerArray(np.array([2, 0], dtype="i8"), np.array([False, True])), + IntegerArray(np.array([2, 0], dtype="int64"), np.array([False, True])), + ], + ) + def test_maybe_convert_objects_nullable_integer(self, exp): + # GH27335 + arr = np.array([2, np.nan], dtype=object) + result = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True) + + tm.assert_extension_array_equal(result, exp) + + @pytest.mark.parametrize( + "dtype, val", [("int64", 1), ("uint64", np.iinfo(np.int64).max + 1)] + ) + def test_maybe_convert_objects_nullable_none(self, dtype, val): + # GH#50043 + arr = np.array([val, None, 3], dtype="object") + result = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True) + expected = IntegerArray( + np.array([val, 0, 3], dtype=dtype), np.array([False, True, False]) + ) + tm.assert_extension_array_equal(result, expected) + + @pytest.mark.parametrize( + "convert_to_masked_nullable, exp", + [ + (True, IntegerArray(np.array([2, 0], dtype="i8"), np.array([False, True]))), + (False, np.array([2, np.nan], dtype="float64")), + ], + ) + def test_maybe_convert_numeric_nullable_integer( + self, convert_to_masked_nullable, exp + ): + # GH 40687 + arr = np.array([2, np.nan], dtype=object) + result = lib.maybe_convert_numeric( + arr, set(), convert_to_masked_nullable=convert_to_masked_nullable + ) + if convert_to_masked_nullable: + result = IntegerArray(*result) + tm.assert_extension_array_equal(result, exp) + else: + result = result[0] + tm.assert_numpy_array_equal(result, exp) + + @pytest.mark.parametrize( + "convert_to_masked_nullable, exp", + [ + ( + True, + FloatingArray( + np.array([2.0, 0.0], dtype="float64"), np.array([False, True]) + ), + ), + (False, np.array([2.0, np.nan], dtype="float64")), + ], + ) + def test_maybe_convert_numeric_floating_array( + self, convert_to_masked_nullable, exp + ): + # GH 40687 + arr = np.array([2.0, np.nan], dtype=object) + result = lib.maybe_convert_numeric( + arr, set(), convert_to_masked_nullable=convert_to_masked_nullable + ) + if convert_to_masked_nullable: + tm.assert_extension_array_equal(FloatingArray(*result), exp) + else: + result = result[0] + tm.assert_numpy_array_equal(result, exp) + + def test_maybe_convert_objects_bool_nan(self): + # GH32146 + ind = Index([True, False, np.nan], dtype=object) + exp = np.array([True, False, np.nan], dtype=object) + out = lib.maybe_convert_objects(ind.values, safe=1) + tm.assert_numpy_array_equal(out, exp) + + def test_maybe_convert_objects_nullable_boolean(self): + # GH50047 + arr = np.array([True, False], dtype=object) + exp = np.array([True, False]) + out = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True) + tm.assert_numpy_array_equal(out, exp) + + arr = np.array([True, False, pd.NaT], dtype=object) + exp = np.array([True, False, pd.NaT], dtype=object) + out = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True) + tm.assert_numpy_array_equal(out, exp) + + @pytest.mark.parametrize("val", [None, np.nan]) + def test_maybe_convert_objects_nullable_boolean_na(self, val): + # GH50047 + arr = np.array([True, False, val], dtype=object) + exp = BooleanArray( + np.array([True, False, False]), np.array([False, False, True]) + ) + out = lib.maybe_convert_objects(arr, convert_to_nullable_dtype=True) + tm.assert_extension_array_equal(out, exp) + + @pytest.mark.parametrize( + "data0", + [ + True, + 1, + 1.0, + 1.0 + 1.0j, + np.int8(1), + np.int16(1), + np.int32(1), + np.int64(1), + np.float16(1), + np.float32(1), + np.float64(1), + np.complex64(1), + np.complex128(1), + ], + ) + @pytest.mark.parametrize( + "data1", + [ + True, + 1, + 1.0, + 1.0 + 1.0j, + np.int8(1), + np.int16(1), + np.int32(1), + np.int64(1), + np.float16(1), + np.float32(1), + np.float64(1), + np.complex64(1), + np.complex128(1), + ], + ) + def test_maybe_convert_objects_itemsize(self, data0, data1): + # GH 40908 + data = [data0, data1] + arr = np.array(data, dtype="object") + + common_kind = np.result_type(type(data0), type(data1)).kind + kind0 = "python" if not hasattr(data0, "dtype") else data0.dtype.kind + kind1 = "python" if not hasattr(data1, "dtype") else data1.dtype.kind + if kind0 != "python" and kind1 != "python": + kind = common_kind + itemsize = max(data0.dtype.itemsize, data1.dtype.itemsize) + elif is_bool(data0) or is_bool(data1): + kind = "bool" if (is_bool(data0) and is_bool(data1)) else "object" + itemsize = "" + elif is_complex(data0) or is_complex(data1): + kind = common_kind + itemsize = 16 + else: + kind = common_kind + itemsize = 8 + + expected = np.array(data, dtype=f"{kind}{itemsize}") + result = lib.maybe_convert_objects(arr) + tm.assert_numpy_array_equal(result, expected) + + def test_mixed_dtypes_remain_object_array(self): + # GH14956 + arr = np.array([datetime(2015, 1, 1, tzinfo=pytz.utc), 1], dtype=object) + result = lib.maybe_convert_objects(arr, convert_non_numeric=True) + tm.assert_numpy_array_equal(result, arr) + + @pytest.mark.parametrize( + "idx", + [ + pd.IntervalIndex.from_breaks(range(5), closed="both"), + pd.period_range("2016-01-01", periods=3, freq="D"), + ], + ) + def test_maybe_convert_objects_ea(self, idx): + result = lib.maybe_convert_objects( + np.array(idx, dtype=object), + convert_non_numeric=True, + ) + tm.assert_extension_array_equal(result, idx._data) + + +class TestTypeInference: + # Dummy class used for testing with Python objects + class Dummy: + pass + + def test_inferred_dtype_fixture(self, any_skipna_inferred_dtype): + # see pandas/conftest.py + inferred_dtype, values = any_skipna_inferred_dtype + + # make sure the inferred dtype of the fixture is as requested + assert inferred_dtype == lib.infer_dtype(values, skipna=True) + + @pytest.mark.parametrize("skipna", [True, False]) + def test_length_zero(self, skipna): + result = lib.infer_dtype(np.array([], dtype="i4"), skipna=skipna) + assert result == "integer" + + result = lib.infer_dtype([], skipna=skipna) + assert result == "empty" + + # GH 18004 + arr = np.array([np.array([], dtype=object), np.array([], dtype=object)]) + result = lib.infer_dtype(arr, skipna=skipna) + assert result == "empty" + + def test_integers(self): + arr = np.array([1, 2, 3, np.int64(4), np.int32(5)], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "integer" + + arr = np.array([1, 2, 3, np.int64(4), np.int32(5), "foo"], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "mixed-integer" + + arr = np.array([1, 2, 3, 4, 5], dtype="i4") + result = lib.infer_dtype(arr, skipna=True) + assert result == "integer" + + @pytest.mark.parametrize( + "arr, skipna", + [ + (np.array([1, 2, np.nan, np.nan, 3], dtype="O"), False), + (np.array([1, 2, np.nan, np.nan, 3], dtype="O"), True), + (np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), False), + (np.array([1, 2, 3, np.int64(4), np.int32(5), np.nan], dtype="O"), True), + ], + ) + def test_integer_na(self, arr, skipna): + # GH 27392 + result = lib.infer_dtype(arr, skipna=skipna) + expected = "integer" if skipna else "integer-na" + assert result == expected + + def test_infer_dtype_skipna_default(self): + # infer_dtype `skipna` default deprecated in GH#24050, + # changed to True in GH#29876 + arr = np.array([1, 2, 3, np.nan], dtype=object) + + result = lib.infer_dtype(arr) + assert result == "integer" + + def test_bools(self): + arr = np.array([True, False, True, True, True], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "boolean" + + arr = np.array([np.bool_(True), np.bool_(False)], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "boolean" + + arr = np.array([True, False, True, "foo"], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "mixed" + + arr = np.array([True, False, True], dtype=bool) + result = lib.infer_dtype(arr, skipna=True) + assert result == "boolean" + + arr = np.array([True, np.nan, False], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "boolean" + + result = lib.infer_dtype(arr, skipna=False) + assert result == "mixed" + + def test_floats(self): + arr = np.array([1.0, 2.0, 3.0, np.float64(4), np.float32(5)], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "floating" + + arr = np.array([1, 2, 3, np.float64(4), np.float32(5), "foo"], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "mixed-integer" + + arr = np.array([1, 2, 3, 4, 5], dtype="f4") + result = lib.infer_dtype(arr, skipna=True) + assert result == "floating" + + arr = np.array([1, 2, 3, 4, 5], dtype="f8") + result = lib.infer_dtype(arr, skipna=True) + assert result == "floating" + + def test_decimals(self): + # GH15690 + arr = np.array([Decimal(1), Decimal(2), Decimal(3)]) + result = lib.infer_dtype(arr, skipna=True) + assert result == "decimal" + + arr = np.array([1.0, 2.0, Decimal(3)]) + result = lib.infer_dtype(arr, skipna=True) + assert result == "mixed" + + result = lib.infer_dtype(arr[::-1], skipna=True) + assert result == "mixed" + + arr = np.array([Decimal(1), Decimal("NaN"), Decimal(3)]) + result = lib.infer_dtype(arr, skipna=True) + assert result == "decimal" + + arr = np.array([Decimal(1), np.nan, Decimal(3)], dtype="O") + result = lib.infer_dtype(arr, skipna=True) + assert result == "decimal" + + # complex is compatible with nan, so skipna has no effect + @pytest.mark.parametrize("skipna", [True, False]) + def test_complex(self, skipna): + # gets cast to complex on array construction + arr = np.array([1.0, 2.0, 1 + 1j]) + result = lib.infer_dtype(arr, skipna=skipna) + assert result == "complex" + + arr = np.array([1.0, 2.0, 1 + 1j], dtype="O") + result = lib.infer_dtype(arr, skipna=skipna) + assert result == "mixed" + + result = lib.infer_dtype(arr[::-1], skipna=skipna) + assert result == "mixed" + + # gets cast to complex on array construction + arr = np.array([1, np.nan, 1 + 1j]) + result = lib.infer_dtype(arr, skipna=skipna) + assert result == "complex" + + arr = np.array([1.0, np.nan, 1 + 1j], dtype="O") + result = lib.infer_dtype(arr, skipna=skipna) + assert result == "mixed" + + # complex with nans stays complex + arr = np.array([1 + 1j, np.nan, 3 + 3j], dtype="O") + result = lib.infer_dtype(arr, skipna=skipna) + assert result == "complex" + + # test smaller complex dtype; will pass through _try_infer_map fastpath + arr = np.array([1 + 1j, np.nan, 3 + 3j], dtype=np.complex64) + result = lib.infer_dtype(arr, skipna=skipna) + assert result == "complex" + + def test_string(self): + pass + + def test_unicode(self): + arr = ["a", np.nan, "c"] + result = lib.infer_dtype(arr, skipna=False) + # This currently returns "mixed", but it's not clear that's optimal. + # This could also return "string" or "mixed-string" + assert result == "mixed" + + # even though we use skipna, we are only skipping those NAs that are + # considered matching by is_string_array + arr = ["a", np.nan, "c"] + result = lib.infer_dtype(arr, skipna=True) + assert result == "string" + + arr = ["a", pd.NA, "c"] + result = lib.infer_dtype(arr, skipna=True) + assert result == "string" + + arr = ["a", pd.NaT, "c"] + result = lib.infer_dtype(arr, skipna=True) + assert result == "mixed" + + arr = ["a", "c"] + result = lib.infer_dtype(arr, skipna=False) + assert result == "string" + + @pytest.mark.parametrize( + "dtype, missing, skipna, expected", + [ + (float, np.nan, False, "floating"), + (float, np.nan, True, "floating"), + (object, np.nan, False, "floating"), + (object, np.nan, True, "empty"), + (object, None, False, "mixed"), + (object, None, True, "empty"), + ], + ) + @pytest.mark.parametrize("box", [Series, np.array]) + def test_object_empty(self, box, missing, dtype, skipna, expected): + # GH 23421 + arr = box([missing, missing], dtype=dtype) + + result = lib.infer_dtype(arr, skipna=skipna) + assert result == expected + + def test_datetime(self): + dates = [datetime(2012, 1, x) for x in range(1, 20)] + index = Index(dates) + assert index.inferred_type == "datetime64" + + def test_infer_dtype_datetime64(self): + arr = np.array( + [np.datetime64("2011-01-01"), np.datetime64("2011-01-01")], dtype=object + ) + assert lib.infer_dtype(arr, skipna=True) == "datetime64" + + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + def test_infer_dtype_datetime64_with_na(self, na_value): + # starts with nan + arr = np.array([na_value, np.datetime64("2011-01-02")]) + assert lib.infer_dtype(arr, skipna=True) == "datetime64" + + arr = np.array([na_value, np.datetime64("2011-01-02"), na_value]) + assert lib.infer_dtype(arr, skipna=True) == "datetime64" + + @pytest.mark.parametrize( + "arr", + [ + np.array( + [np.timedelta64("nat"), np.datetime64("2011-01-02")], dtype=object + ), + np.array( + [np.datetime64("2011-01-02"), np.timedelta64("nat")], dtype=object + ), + np.array([np.datetime64("2011-01-01"), Timestamp("2011-01-02")]), + np.array([Timestamp("2011-01-02"), np.datetime64("2011-01-01")]), + np.array([np.nan, Timestamp("2011-01-02"), 1.1]), + np.array([np.nan, "2011-01-01", Timestamp("2011-01-02")], dtype=object), + np.array([np.datetime64("nat"), np.timedelta64(1, "D")], dtype=object), + np.array([np.timedelta64(1, "D"), np.datetime64("nat")], dtype=object), + ], + ) + def test_infer_datetimelike_dtype_mixed(self, arr): + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + def test_infer_dtype_mixed_integer(self): + arr = np.array([np.nan, Timestamp("2011-01-02"), 1]) + assert lib.infer_dtype(arr, skipna=True) == "mixed-integer" + + @pytest.mark.parametrize( + "arr", + [ + np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]), + np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]), + np.array([datetime(2011, 1, 1), Timestamp("2011-01-02")]), + ], + ) + def test_infer_dtype_datetime(self, arr): + assert lib.infer_dtype(arr, skipna=True) == "datetime" + + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + @pytest.mark.parametrize( + "time_stamp", [Timestamp("2011-01-01"), datetime(2011, 1, 1)] + ) + def test_infer_dtype_datetime_with_na(self, na_value, time_stamp): + # starts with nan + arr = np.array([na_value, time_stamp]) + assert lib.infer_dtype(arr, skipna=True) == "datetime" + + arr = np.array([na_value, time_stamp, na_value]) + assert lib.infer_dtype(arr, skipna=True) == "datetime" + + @pytest.mark.parametrize( + "arr", + [ + np.array([Timedelta("1 days"), Timedelta("2 days")]), + np.array([np.timedelta64(1, "D"), np.timedelta64(2, "D")], dtype=object), + np.array([timedelta(1), timedelta(2)]), + ], + ) + def test_infer_dtype_timedelta(self, arr): + assert lib.infer_dtype(arr, skipna=True) == "timedelta" + + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + @pytest.mark.parametrize( + "delta", [Timedelta("1 days"), np.timedelta64(1, "D"), timedelta(1)] + ) + def test_infer_dtype_timedelta_with_na(self, na_value, delta): + # starts with nan + arr = np.array([na_value, delta]) + assert lib.infer_dtype(arr, skipna=True) == "timedelta" + + arr = np.array([na_value, delta, na_value]) + assert lib.infer_dtype(arr, skipna=True) == "timedelta" + + def test_infer_dtype_period(self): + # GH 13664 + arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="D")]) + assert lib.infer_dtype(arr, skipna=True) == "period" + + # non-homogeneous freqs -> mixed + arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="M")]) + assert lib.infer_dtype(arr, skipna=True) == "mixed" + + @pytest.mark.parametrize("klass", [pd.array, Series, Index]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_infer_dtype_period_array(self, klass, skipna): + # https://github.com/pandas-dev/pandas/issues/23553 + values = klass( + [ + Period("2011-01-01", freq="D"), + Period("2011-01-02", freq="D"), + pd.NaT, + ] + ) + assert lib.infer_dtype(values, skipna=skipna) == "period" + + # periods but mixed freq + values = klass( + [ + Period("2011-01-01", freq="D"), + Period("2011-01-02", freq="M"), + pd.NaT, + ] + ) + # with pd.array this becomes NumpyExtensionArray which ends up + # as "unknown-array" + exp = "unknown-array" if klass is pd.array else "mixed" + assert lib.infer_dtype(values, skipna=skipna) == exp + + def test_infer_dtype_period_mixed(self): + arr = np.array( + [Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object + ) + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + arr = np.array( + [np.datetime64("nat"), Period("2011-01", freq="M")], dtype=object + ) + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) + def test_infer_dtype_period_with_na(self, na_value): + # starts with nan + arr = np.array([na_value, Period("2011-01", freq="D")]) + assert lib.infer_dtype(arr, skipna=True) == "period" + + arr = np.array([na_value, Period("2011-01", freq="D"), na_value]) + assert lib.infer_dtype(arr, skipna=True) == "period" + + def test_infer_dtype_all_nan_nat_like(self): + arr = np.array([np.nan, np.nan]) + assert lib.infer_dtype(arr, skipna=True) == "floating" + + # nan and None mix are result in mixed + arr = np.array([np.nan, np.nan, None]) + assert lib.infer_dtype(arr, skipna=True) == "empty" + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + arr = np.array([None, np.nan, np.nan]) + assert lib.infer_dtype(arr, skipna=True) == "empty" + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + # pd.NaT + arr = np.array([pd.NaT]) + assert lib.infer_dtype(arr, skipna=False) == "datetime" + + arr = np.array([pd.NaT, np.nan]) + assert lib.infer_dtype(arr, skipna=False) == "datetime" + + arr = np.array([np.nan, pd.NaT]) + assert lib.infer_dtype(arr, skipna=False) == "datetime" + + arr = np.array([np.nan, pd.NaT, np.nan]) + assert lib.infer_dtype(arr, skipna=False) == "datetime" + + arr = np.array([None, pd.NaT, None]) + assert lib.infer_dtype(arr, skipna=False) == "datetime" + + # np.datetime64(nat) + arr = np.array([np.datetime64("nat")]) + assert lib.infer_dtype(arr, skipna=False) == "datetime64" + + for n in [np.nan, pd.NaT, None]: + arr = np.array([n, np.datetime64("nat"), n]) + assert lib.infer_dtype(arr, skipna=False) == "datetime64" + + arr = np.array([pd.NaT, n, np.datetime64("nat"), n]) + assert lib.infer_dtype(arr, skipna=False) == "datetime64" + + arr = np.array([np.timedelta64("nat")], dtype=object) + assert lib.infer_dtype(arr, skipna=False) == "timedelta" + + for n in [np.nan, pd.NaT, None]: + arr = np.array([n, np.timedelta64("nat"), n]) + assert lib.infer_dtype(arr, skipna=False) == "timedelta" + + arr = np.array([pd.NaT, n, np.timedelta64("nat"), n]) + assert lib.infer_dtype(arr, skipna=False) == "timedelta" + + # datetime / timedelta mixed + arr = np.array([pd.NaT, np.datetime64("nat"), np.timedelta64("nat"), np.nan]) + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + arr = np.array([np.timedelta64("nat"), np.datetime64("nat")], dtype=object) + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + def test_is_datetimelike_array_all_nan_nat_like(self): + arr = np.array([np.nan, pd.NaT, np.datetime64("nat")]) + assert lib.is_datetime_array(arr) + assert lib.is_datetime64_array(arr) + assert not lib.is_timedelta_or_timedelta64_array(arr) + + arr = np.array([np.nan, pd.NaT, np.timedelta64("nat")]) + assert not lib.is_datetime_array(arr) + assert not lib.is_datetime64_array(arr) + assert lib.is_timedelta_or_timedelta64_array(arr) + + arr = np.array([np.nan, pd.NaT, np.datetime64("nat"), np.timedelta64("nat")]) + assert not lib.is_datetime_array(arr) + assert not lib.is_datetime64_array(arr) + assert not lib.is_timedelta_or_timedelta64_array(arr) + + arr = np.array([np.nan, pd.NaT]) + assert lib.is_datetime_array(arr) + assert lib.is_datetime64_array(arr) + assert lib.is_timedelta_or_timedelta64_array(arr) + + arr = np.array([np.nan, np.nan], dtype=object) + assert not lib.is_datetime_array(arr) + assert not lib.is_datetime64_array(arr) + assert not lib.is_timedelta_or_timedelta64_array(arr) + + assert lib.is_datetime_with_singletz_array( + np.array( + [ + Timestamp("20130101", tz="US/Eastern"), + Timestamp("20130102", tz="US/Eastern"), + ], + dtype=object, + ) + ) + assert not lib.is_datetime_with_singletz_array( + np.array( + [ + Timestamp("20130101", tz="US/Eastern"), + Timestamp("20130102", tz="CET"), + ], + dtype=object, + ) + ) + + @pytest.mark.parametrize( + "func", + [ + "is_datetime_array", + "is_datetime64_array", + "is_bool_array", + "is_timedelta_or_timedelta64_array", + "is_date_array", + "is_time_array", + "is_interval_array", + ], + ) + def test_other_dtypes_for_array(self, func): + func = getattr(lib, func) + arr = np.array(["foo", "bar"]) + assert not func(arr) + assert not func(arr.reshape(2, 1)) + + arr = np.array([1, 2]) + assert not func(arr) + assert not func(arr.reshape(2, 1)) + + def test_date(self): + dates = [date(2012, 1, day) for day in range(1, 20)] + index = Index(dates) + assert index.inferred_type == "date" + + dates = [date(2012, 1, day) for day in range(1, 20)] + [np.nan] + result = lib.infer_dtype(dates, skipna=False) + assert result == "mixed" + + result = lib.infer_dtype(dates, skipna=True) + assert result == "date" + + @pytest.mark.parametrize( + "values", + [ + [date(2020, 1, 1), Timestamp("2020-01-01")], + [Timestamp("2020-01-01"), date(2020, 1, 1)], + [date(2020, 1, 1), pd.NaT], + [pd.NaT, date(2020, 1, 1)], + ], + ) + @pytest.mark.parametrize("skipna", [True, False]) + def test_infer_dtype_date_order_invariant(self, values, skipna): + # https://github.com/pandas-dev/pandas/issues/33741 + result = lib.infer_dtype(values, skipna=skipna) + assert result == "date" + + def test_is_numeric_array(self): + assert lib.is_float_array(np.array([1, 2.0])) + assert lib.is_float_array(np.array([1, 2.0, np.nan])) + assert not lib.is_float_array(np.array([1, 2])) + + assert lib.is_integer_array(np.array([1, 2])) + assert not lib.is_integer_array(np.array([1, 2.0])) + + def test_is_string_array(self): + # We should only be accepting pd.NA, np.nan, + # other floating point nans e.g. float('nan')] + # when skipna is True. + assert lib.is_string_array(np.array(["foo", "bar"])) + assert not lib.is_string_array( + np.array(["foo", "bar", pd.NA], dtype=object), skipna=False + ) + assert lib.is_string_array( + np.array(["foo", "bar", pd.NA], dtype=object), skipna=True + ) + # we allow NaN/None in the StringArray constructor, so its allowed here + assert lib.is_string_array( + np.array(["foo", "bar", None], dtype=object), skipna=True + ) + assert lib.is_string_array( + np.array(["foo", "bar", np.nan], dtype=object), skipna=True + ) + # But not e.g. datetimelike or Decimal NAs + assert not lib.is_string_array( + np.array(["foo", "bar", pd.NaT], dtype=object), skipna=True + ) + assert not lib.is_string_array( + np.array(["foo", "bar", np.datetime64("NaT")], dtype=object), skipna=True + ) + assert not lib.is_string_array( + np.array(["foo", "bar", Decimal("NaN")], dtype=object), skipna=True + ) + + assert not lib.is_string_array( + np.array(["foo", "bar", None], dtype=object), skipna=False + ) + assert not lib.is_string_array( + np.array(["foo", "bar", np.nan], dtype=object), skipna=False + ) + assert not lib.is_string_array(np.array([1, 2])) + + @pytest.mark.parametrize( + "func", + [ + "is_bool_array", + "is_date_array", + "is_datetime_array", + "is_datetime64_array", + "is_float_array", + "is_integer_array", + "is_interval_array", + "is_string_array", + "is_time_array", + "is_timedelta_or_timedelta64_array", + ], + ) + def test_is_dtype_array_empty_obj(self, func): + # https://github.com/pandas-dev/pandas/pull/60796 + func = getattr(lib, func) + + arr = np.empty((2, 0), dtype=object) + assert not func(arr) + + arr = np.empty((0, 2), dtype=object) + assert not func(arr) + + def test_to_object_array_tuples(self): + r = (5, 6) + values = [r] + lib.to_object_array_tuples(values) + + # make sure record array works + record = namedtuple("record", "x y") + r = record(5, 6) + values = [r] + lib.to_object_array_tuples(values) + + def test_object(self): + # GH 7431 + # cannot infer more than this as only a single element + arr = np.array([None], dtype="O") + result = lib.infer_dtype(arr, skipna=False) + assert result == "mixed" + result = lib.infer_dtype(arr, skipna=True) + assert result == "empty" + + def test_to_object_array_width(self): + # see gh-13320 + rows = [[1, 2, 3], [4, 5, 6]] + + expected = np.array(rows, dtype=object) + out = lib.to_object_array(rows) + tm.assert_numpy_array_equal(out, expected) + + expected = np.array(rows, dtype=object) + out = lib.to_object_array(rows, min_width=1) + tm.assert_numpy_array_equal(out, expected) + + expected = np.array( + [[1, 2, 3, None, None], [4, 5, 6, None, None]], dtype=object + ) + out = lib.to_object_array(rows, min_width=5) + tm.assert_numpy_array_equal(out, expected) + + def test_is_period(self): + # GH#55264 + msg = "is_period is deprecated and will be removed in a future version" + with tm.assert_produces_warning(FutureWarning, match=msg): + assert lib.is_period(Period("2011-01", freq="M")) + assert not lib.is_period(PeriodIndex(["2011-01"], freq="M")) + assert not lib.is_period(Timestamp("2011-01")) + assert not lib.is_period(1) + assert not lib.is_period(np.nan) + + def test_is_interval(self): + # GH#55264 + msg = "is_interval is deprecated and will be removed in a future version" + item = Interval(1, 2) + with tm.assert_produces_warning(FutureWarning, match=msg): + assert lib.is_interval(item) + assert not lib.is_interval(pd.IntervalIndex([item])) + assert not lib.is_interval(pd.IntervalIndex([item])._engine) + + def test_categorical(self): + # GH 8974 + arr = Categorical(list("abc")) + result = lib.infer_dtype(arr, skipna=True) + assert result == "categorical" + + result = lib.infer_dtype(Series(arr), skipna=True) + assert result == "categorical" + + arr = Categorical(list("abc"), categories=["cegfab"], ordered=True) + result = lib.infer_dtype(arr, skipna=True) + assert result == "categorical" + + result = lib.infer_dtype(Series(arr), skipna=True) + assert result == "categorical" + + @pytest.mark.parametrize("asobject", [True, False]) + def test_interval(self, asobject): + idx = pd.IntervalIndex.from_breaks(range(5), closed="both") + if asobject: + idx = idx.astype(object) + + inferred = lib.infer_dtype(idx, skipna=False) + assert inferred == "interval" + + inferred = lib.infer_dtype(idx._data, skipna=False) + assert inferred == "interval" + + inferred = lib.infer_dtype(Series(idx, dtype=idx.dtype), skipna=False) + assert inferred == "interval" + + @pytest.mark.parametrize("value", [Timestamp(0), Timedelta(0), 0, 0.0]) + def test_interval_mismatched_closed(self, value): + first = Interval(value, value, closed="left") + second = Interval(value, value, closed="right") + + # if closed match, we should infer "interval" + arr = np.array([first, first], dtype=object) + assert lib.infer_dtype(arr, skipna=False) == "interval" + + # if closed dont match, we should _not_ get "interval" + arr2 = np.array([first, second], dtype=object) + assert lib.infer_dtype(arr2, skipna=False) == "mixed" + + def test_interval_mismatched_subtype(self): + first = Interval(0, 1, closed="left") + second = Interval(Timestamp(0), Timestamp(1), closed="left") + third = Interval(Timedelta(0), Timedelta(1), closed="left") + + arr = np.array([first, second]) + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + arr = np.array([second, third]) + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + arr = np.array([first, third]) + assert lib.infer_dtype(arr, skipna=False) == "mixed" + + # float vs int subdtype are compatible + flt_interval = Interval(1.5, 2.5, closed="left") + arr = np.array([first, flt_interval], dtype=object) + assert lib.infer_dtype(arr, skipna=False) == "interval" + + @pytest.mark.parametrize("klass", [pd.array, Series]) + @pytest.mark.parametrize("skipna", [True, False]) + @pytest.mark.parametrize("data", [["a", "b", "c"], ["a", "b", pd.NA]]) + def test_string_dtype(self, data, skipna, klass, nullable_string_dtype): + # StringArray + val = klass(data, dtype=nullable_string_dtype) + inferred = lib.infer_dtype(val, skipna=skipna) + assert inferred == "string" + + @pytest.mark.parametrize("klass", [pd.array, Series]) + @pytest.mark.parametrize("skipna", [True, False]) + @pytest.mark.parametrize("data", [[True, False, True], [True, False, pd.NA]]) + def test_boolean_dtype(self, data, skipna, klass): + # BooleanArray + val = klass(data, dtype="boolean") + inferred = lib.infer_dtype(val, skipna=skipna) + assert inferred == "boolean" + + +class TestNumberScalar: + def test_is_number(self): + assert is_number(True) + assert is_number(1) + assert is_number(1.1) + assert is_number(1 + 3j) + assert is_number(np.int64(1)) + assert is_number(np.float64(1.1)) + assert is_number(np.complex128(1 + 3j)) + assert is_number(np.nan) + + assert not is_number(None) + assert not is_number("x") + assert not is_number(datetime(2011, 1, 1)) + assert not is_number(np.datetime64("2011-01-01")) + assert not is_number(Timestamp("2011-01-01")) + assert not is_number(Timestamp("2011-01-01", tz="US/Eastern")) + assert not is_number(timedelta(1000)) + assert not is_number(Timedelta("1 days")) + + # questionable + assert not is_number(np.bool_(False)) + assert is_number(np.timedelta64(1, "D")) + + def test_is_bool(self): + assert is_bool(True) + assert is_bool(False) + assert is_bool(np.bool_(False)) + + assert not is_bool(1) + assert not is_bool(1.1) + assert not is_bool(1 + 3j) + assert not is_bool(np.int64(1)) + assert not is_bool(np.float64(1.1)) + assert not is_bool(np.complex128(1 + 3j)) + assert not is_bool(np.nan) + assert not is_bool(None) + assert not is_bool("x") + assert not is_bool(datetime(2011, 1, 1)) + assert not is_bool(np.datetime64("2011-01-01")) + assert not is_bool(Timestamp("2011-01-01")) + assert not is_bool(Timestamp("2011-01-01", tz="US/Eastern")) + assert not is_bool(timedelta(1000)) + assert not is_bool(np.timedelta64(1, "D")) + assert not is_bool(Timedelta("1 days")) + + def test_is_integer(self): + assert is_integer(1) + assert is_integer(np.int64(1)) + + assert not is_integer(True) + assert not is_integer(1.1) + assert not is_integer(1 + 3j) + assert not is_integer(False) + assert not is_integer(np.bool_(False)) + assert not is_integer(np.float64(1.1)) + assert not is_integer(np.complex128(1 + 3j)) + assert not is_integer(np.nan) + assert not is_integer(None) + assert not is_integer("x") + assert not is_integer(datetime(2011, 1, 1)) + assert not is_integer(np.datetime64("2011-01-01")) + assert not is_integer(Timestamp("2011-01-01")) + assert not is_integer(Timestamp("2011-01-01", tz="US/Eastern")) + assert not is_integer(timedelta(1000)) + assert not is_integer(Timedelta("1 days")) + assert not is_integer(np.timedelta64(1, "D")) + + def test_is_float(self): + assert is_float(1.1) + assert is_float(np.float64(1.1)) + assert is_float(np.nan) + + assert not is_float(True) + assert not is_float(1) + assert not is_float(1 + 3j) + assert not is_float(False) + assert not is_float(np.bool_(False)) + assert not is_float(np.int64(1)) + assert not is_float(np.complex128(1 + 3j)) + assert not is_float(None) + assert not is_float("x") + assert not is_float(datetime(2011, 1, 1)) + assert not is_float(np.datetime64("2011-01-01")) + assert not is_float(Timestamp("2011-01-01")) + assert not is_float(Timestamp("2011-01-01", tz="US/Eastern")) + assert not is_float(timedelta(1000)) + assert not is_float(np.timedelta64(1, "D")) + assert not is_float(Timedelta("1 days")) + + def test_is_datetime_dtypes(self): + ts = pd.date_range("20130101", periods=3) + tsa = pd.date_range("20130101", periods=3, tz="US/Eastern") + + msg = "is_datetime64tz_dtype is deprecated" + + assert is_datetime64_dtype("datetime64") + assert is_datetime64_dtype("datetime64[ns]") + assert is_datetime64_dtype(ts) + assert not is_datetime64_dtype(tsa) + + assert not is_datetime64_ns_dtype("datetime64") + assert is_datetime64_ns_dtype("datetime64[ns]") + assert is_datetime64_ns_dtype(ts) + assert is_datetime64_ns_dtype(tsa) + + assert is_datetime64_any_dtype("datetime64") + assert is_datetime64_any_dtype("datetime64[ns]") + assert is_datetime64_any_dtype(ts) + assert is_datetime64_any_dtype(tsa) + + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert not is_datetime64tz_dtype("datetime64") + assert not is_datetime64tz_dtype("datetime64[ns]") + assert not is_datetime64tz_dtype(ts) + assert is_datetime64tz_dtype(tsa) + + @pytest.mark.parametrize("tz", ["US/Eastern", "UTC"]) + def test_is_datetime_dtypes_with_tz(self, tz): + dtype = f"datetime64[ns, {tz}]" + assert not is_datetime64_dtype(dtype) + + msg = "is_datetime64tz_dtype is deprecated" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + assert is_datetime64tz_dtype(dtype) + assert is_datetime64_ns_dtype(dtype) + assert is_datetime64_any_dtype(dtype) + + def test_is_timedelta(self): + assert is_timedelta64_dtype("timedelta64") + assert is_timedelta64_dtype("timedelta64[ns]") + assert not is_timedelta64_ns_dtype("timedelta64") + assert is_timedelta64_ns_dtype("timedelta64[ns]") + + tdi = TimedeltaIndex([1e14, 2e14], dtype="timedelta64[ns]") + assert is_timedelta64_dtype(tdi) + assert is_timedelta64_ns_dtype(tdi) + assert is_timedelta64_ns_dtype(tdi.astype("timedelta64[ns]")) + + assert not is_timedelta64_ns_dtype(Index([], dtype=np.float64)) + assert not is_timedelta64_ns_dtype(Index([], dtype=np.int64)) + + +class TestIsScalar: + def test_is_scalar_builtin_scalars(self): + assert is_scalar(None) + assert is_scalar(True) + assert is_scalar(False) + assert is_scalar(Fraction()) + assert is_scalar(0.0) + assert is_scalar(1) + assert is_scalar(complex(2)) + assert is_scalar(float("NaN")) + assert is_scalar(np.nan) + assert is_scalar("foobar") + assert is_scalar(b"foobar") + assert is_scalar(datetime(2014, 1, 1)) + assert is_scalar(date(2014, 1, 1)) + assert is_scalar(time(12, 0)) + assert is_scalar(timedelta(hours=1)) + assert is_scalar(pd.NaT) + assert is_scalar(pd.NA) + + def test_is_scalar_builtin_nonscalars(self): + assert not is_scalar({}) + assert not is_scalar([]) + assert not is_scalar([1]) + assert not is_scalar(()) + assert not is_scalar((1,)) + assert not is_scalar(slice(None)) + assert not is_scalar(Ellipsis) + + def test_is_scalar_numpy_array_scalars(self): + assert is_scalar(np.int64(1)) + assert is_scalar(np.float64(1.0)) + assert is_scalar(np.int32(1)) + assert is_scalar(np.complex64(2)) + assert is_scalar(np.object_("foobar")) + assert is_scalar(np.str_("foobar")) + assert is_scalar(np.bytes_(b"foobar")) + assert is_scalar(np.datetime64("2014-01-01")) + assert is_scalar(np.timedelta64(1, "h")) + + @pytest.mark.parametrize( + "zerodim", + [ + np.array(1), + np.array("foobar"), + np.array(np.datetime64("2014-01-01")), + np.array(np.timedelta64(1, "h")), + np.array(np.datetime64("NaT")), + ], + ) + def test_is_scalar_numpy_zerodim_arrays(self, zerodim): + assert not is_scalar(zerodim) + assert is_scalar(lib.item_from_zerodim(zerodim)) + + @pytest.mark.parametrize("arr", [np.array([]), np.array([[]])]) + def test_is_scalar_numpy_arrays(self, arr): + assert not is_scalar(arr) + assert not is_scalar(MockNumpyLikeArray(arr)) + + def test_is_scalar_pandas_scalars(self): + assert is_scalar(Timestamp("2014-01-01")) + assert is_scalar(Timedelta(hours=1)) + assert is_scalar(Period("2014-01-01")) + assert is_scalar(Interval(left=0, right=1)) + assert is_scalar(DateOffset(days=1)) + assert is_scalar(pd.offsets.Minute(3)) + + def test_is_scalar_pandas_containers(self): + assert not is_scalar(Series(dtype=object)) + assert not is_scalar(Series([1])) + assert not is_scalar(DataFrame()) + assert not is_scalar(DataFrame([[1]])) + assert not is_scalar(Index([])) + assert not is_scalar(Index([1])) + assert not is_scalar(Categorical([])) + assert not is_scalar(DatetimeIndex([])._data) + assert not is_scalar(TimedeltaIndex([])._data) + assert not is_scalar(DatetimeIndex([])._data.to_period("D")) + assert not is_scalar(pd.array([1, 2, 3])) + + def test_is_scalar_number(self): + # Number() is not recognied by PyNumber_Check, so by extension + # is not recognized by is_scalar, but instances of non-abstract + # subclasses are. + + class Numeric(Number): + def __init__(self, value) -> None: + self.value = value + + def __int__(self) -> int: + return self.value + + num = Numeric(1) + assert is_scalar(num) + + +@pytest.mark.parametrize("unit", ["ms", "us", "ns"]) +def test_datetimeindex_from_empty_datetime64_array(unit): + idx = DatetimeIndex(np.array([], dtype=f"datetime64[{unit}]")) + assert len(idx) == 0 + + +def test_nan_to_nat_conversions(): + df = DataFrame( + {"A": np.asarray(range(10), dtype="float64"), "B": Timestamp("20010101")} + ) + df.iloc[3:6, :] = np.nan + result = df.loc[4, "B"] + assert result is pd.NaT + + s = df["B"].copy() + s[8:9] = np.nan + assert s[8] is pd.NaT + + +@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") +def test_is_scipy_sparse(spmatrix): + pytest.importorskip("scipy") + assert is_scipy_sparse(spmatrix([[0, 1]])) + assert not is_scipy_sparse(np.array([1])) + + +def test_ensure_int32(): + values = np.arange(10, dtype=np.int32) + result = ensure_int32(values) + assert result.dtype == np.int32 + + values = np.arange(10, dtype=np.int64) + result = ensure_int32(values) + assert result.dtype == np.int32 + + +@pytest.mark.parametrize( + "right,result", + [ + (0, np.uint8), + (-1, np.int16), + (300, np.uint16), + # For floats, we just upcast directly to float64 instead of trying to + # find a smaller floating dtype + (300.0, np.uint16), # for integer floats, we convert them to ints + (300.1, np.float64), + (np.int16(300), np.int16 if np_version_gt2 else np.uint16), + ], +) +def test_find_result_type_uint_int(right, result): + left_dtype = np.dtype("uint8") + assert find_result_type(left_dtype, right) == result + + +@pytest.mark.parametrize( + "right,result", + [ + (0, np.int8), + (-1, np.int8), + (300, np.int16), + # For floats, we just upcast directly to float64 instead of trying to + # find a smaller floating dtype + (300.0, np.int16), # for integer floats, we convert them to ints + (300.1, np.float64), + (np.int16(300), np.int16), + ], +) +def test_find_result_type_int_int(right, result): + left_dtype = np.dtype("int8") + assert find_result_type(left_dtype, right) == result + + +@pytest.mark.parametrize( + "right,result", + [ + (300.0, np.float64), + (np.float32(300), np.float32), + ], +) +def test_find_result_type_floats(right, result): + left_dtype = np.dtype("float16") + assert find_result_type(left_dtype, right) == result diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_missing.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_missing.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d3e98ae2b93f0a182ea15a3a11d6af39fd2f05 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/dtypes/test_missing.py @@ -0,0 +1,923 @@ +from contextlib import nullcontext +from datetime import datetime +from decimal import Decimal + +import numpy as np +import pytest + +from pandas._config import config as cf + +from pandas._libs import missing as libmissing +from pandas._libs.tslibs import iNaT +from pandas.compat.numpy import np_version_gte1p25 + +from pandas.core.dtypes.common import ( + is_float, + is_scalar, + pandas_dtype, +) +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + DatetimeTZDtype, + IntervalDtype, + PeriodDtype, +) +from pandas.core.dtypes.missing import ( + array_equivalent, + is_valid_na_for_dtype, + isna, + isnull, + na_value_for_dtype, + notna, + notnull, +) + +import pandas as pd +from pandas import ( + DatetimeIndex, + Index, + NaT, + Series, + TimedeltaIndex, + date_range, + period_range, +) +import pandas._testing as tm + +fix_now = pd.Timestamp("2021-01-01") +fix_utcnow = pd.Timestamp("2021-01-01", tz="UTC") + + +@pytest.mark.parametrize("notna_f", [notna, notnull]) +def test_notna_notnull(notna_f): + assert notna_f(1.0) + assert not notna_f(None) + assert not notna_f(np.nan) + + msg = "use_inf_as_na option is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + with cf.option_context("mode.use_inf_as_na", False): + assert notna_f(np.inf) + assert notna_f(-np.inf) + + arr = np.array([1.5, np.inf, 3.5, -np.inf]) + result = notna_f(arr) + assert result.all() + + with tm.assert_produces_warning(FutureWarning, match=msg): + with cf.option_context("mode.use_inf_as_na", True): + assert not notna_f(np.inf) + assert not notna_f(-np.inf) + + arr = np.array([1.5, np.inf, 3.5, -np.inf]) + result = notna_f(arr) + assert result.sum() == 2 + + +@pytest.mark.parametrize("null_func", [notna, notnull, isna, isnull]) +@pytest.mark.parametrize( + "ser", + [ + Series( + [str(i) for i in range(5)], + index=Index([str(i) for i in range(5)], dtype=object), + dtype=object, + ), + Series(range(5), date_range("2020-01-01", periods=5)), + Series(range(5), period_range("2020-01-01", periods=5)), + ], +) +def test_null_check_is_series(null_func, ser): + msg = "use_inf_as_na option is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + with cf.option_context("mode.use_inf_as_na", False): + assert isinstance(null_func(ser), Series) + + +class TestIsNA: + def test_0d_array(self): + assert isna(np.array(np.nan)) + assert not isna(np.array(0.0)) + assert not isna(np.array(0)) + # test object dtype + assert isna(np.array(np.nan, dtype=object)) + assert not isna(np.array(0.0, dtype=object)) + assert not isna(np.array(0, dtype=object)) + + @pytest.mark.parametrize("shape", [(4, 0), (4,)]) + def test_empty_object(self, shape): + arr = np.empty(shape=shape, dtype=object) + result = isna(arr) + expected = np.ones(shape=shape, dtype=bool) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("isna_f", [isna, isnull]) + def test_isna_isnull(self, isna_f): + assert not isna_f(1.0) + assert isna_f(None) + assert isna_f(np.nan) + assert float("nan") + assert not isna_f(np.inf) + assert not isna_f(-np.inf) + + # type + assert not isna_f(type(Series(dtype=object))) + assert not isna_f(type(Series(dtype=np.float64))) + assert not isna_f(type(pd.DataFrame())) + + @pytest.mark.parametrize("isna_f", [isna, isnull]) + @pytest.mark.parametrize( + "data", + [ + np.arange(4, dtype=float), + [0.0, 1.0, 0.0, 1.0], + Series(list("abcd")), + date_range("2020-01-01", periods=4), + ], + ) + @pytest.mark.parametrize( + "index", + [ + date_range("2020-01-01", periods=4), + range(4), + period_range("2020-01-01", periods=4), + ], + ) + def test_isna_isnull_frame(self, isna_f, data, index): + # frame + df = pd.DataFrame(data, index=index) + result = isna_f(df) + expected = df.apply(isna_f) + tm.assert_frame_equal(result, expected) + + def test_isna_lists(self): + result = isna([[False]]) + exp = np.array([[False]]) + tm.assert_numpy_array_equal(result, exp) + + result = isna([[1], [2]]) + exp = np.array([[False], [False]]) + tm.assert_numpy_array_equal(result, exp) + + # list of strings / unicode + result = isna(["foo", "bar"]) + exp = np.array([False, False]) + tm.assert_numpy_array_equal(result, exp) + + result = isna(["foo", "bar"]) + exp = np.array([False, False]) + tm.assert_numpy_array_equal(result, exp) + + # GH20675 + result = isna([np.nan, "world"]) + exp = np.array([True, False]) + tm.assert_numpy_array_equal(result, exp) + + def test_isna_nat(self): + result = isna([NaT]) + exp = np.array([True]) + tm.assert_numpy_array_equal(result, exp) + + result = isna(np.array([NaT], dtype=object)) + exp = np.array([True]) + tm.assert_numpy_array_equal(result, exp) + + def test_isna_numpy_nat(self): + arr = np.array( + [ + NaT, + np.datetime64("NaT"), + np.timedelta64("NaT"), + np.datetime64("NaT", "s"), + ] + ) + result = isna(arr) + expected = np.array([True] * 4) + tm.assert_numpy_array_equal(result, expected) + + def test_isna_datetime(self): + assert not isna(datetime.now()) + assert notna(datetime.now()) + + idx = date_range("1/1/1990", periods=20) + exp = np.ones(len(idx), dtype=bool) + tm.assert_numpy_array_equal(notna(idx), exp) + + idx = np.asarray(idx) + idx[0] = iNaT + idx = DatetimeIndex(idx) + mask = isna(idx) + assert mask[0] + exp = np.array([True] + [False] * (len(idx) - 1), dtype=bool) + tm.assert_numpy_array_equal(mask, exp) + + # GH 9129 + pidx = idx.to_period(freq="M") + mask = isna(pidx) + assert mask[0] + exp = np.array([True] + [False] * (len(idx) - 1), dtype=bool) + tm.assert_numpy_array_equal(mask, exp) + + mask = isna(pidx[1:]) + exp = np.zeros(len(mask), dtype=bool) + tm.assert_numpy_array_equal(mask, exp) + + def test_isna_old_datetimelike(self): + # isna_old should work for dt64tz, td64, and period, not just tznaive + dti = date_range("2016-01-01", periods=3) + dta = dti._data + dta[-1] = NaT + expected = np.array([False, False, True], dtype=bool) + + objs = [dta, dta.tz_localize("US/Eastern"), dta - dta, dta.to_period("D")] + + for obj in objs: + msg = "use_inf_as_na option is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + with cf.option_context("mode.use_inf_as_na", True): + result = isna(obj) + + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize( + "value, expected", + [ + (np.complex128(np.nan), True), + (np.float64(1), False), + (np.array([1, 1 + 0j, np.nan, 3]), np.array([False, False, True, False])), + ( + np.array([1, 1 + 0j, np.nan, 3], dtype=object), + np.array([False, False, True, False]), + ), + ( + np.array([1, 1 + 0j, np.nan, 3]).astype(object), + np.array([False, False, True, False]), + ), + ], + ) + def test_complex(self, value, expected): + result = isna(value) + if is_scalar(result): + assert result is expected + else: + tm.assert_numpy_array_equal(result, expected) + + def test_datetime_other_units(self): + idx = DatetimeIndex(["2011-01-01", "NaT", "2011-01-02"]) + exp = np.array([False, True, False]) + tm.assert_numpy_array_equal(isna(idx), exp) + tm.assert_numpy_array_equal(notna(idx), ~exp) + tm.assert_numpy_array_equal(isna(idx.values), exp) + tm.assert_numpy_array_equal(notna(idx.values), ~exp) + + @pytest.mark.parametrize( + "dtype", + [ + "datetime64[D]", + "datetime64[h]", + "datetime64[m]", + "datetime64[s]", + "datetime64[ms]", + "datetime64[us]", + "datetime64[ns]", + ], + ) + def test_datetime_other_units_astype(self, dtype): + idx = DatetimeIndex(["2011-01-01", "NaT", "2011-01-02"]) + values = idx.values.astype(dtype) + + exp = np.array([False, True, False]) + tm.assert_numpy_array_equal(isna(values), exp) + tm.assert_numpy_array_equal(notna(values), ~exp) + + exp = Series([False, True, False]) + s = Series(values) + tm.assert_series_equal(isna(s), exp) + tm.assert_series_equal(notna(s), ~exp) + s = Series(values, dtype=object) + tm.assert_series_equal(isna(s), exp) + tm.assert_series_equal(notna(s), ~exp) + + def test_timedelta_other_units(self): + idx = TimedeltaIndex(["1 days", "NaT", "2 days"]) + exp = np.array([False, True, False]) + tm.assert_numpy_array_equal(isna(idx), exp) + tm.assert_numpy_array_equal(notna(idx), ~exp) + tm.assert_numpy_array_equal(isna(idx.values), exp) + tm.assert_numpy_array_equal(notna(idx.values), ~exp) + + @pytest.mark.parametrize( + "dtype", + [ + "timedelta64[D]", + "timedelta64[h]", + "timedelta64[m]", + "timedelta64[s]", + "timedelta64[ms]", + "timedelta64[us]", + "timedelta64[ns]", + ], + ) + def test_timedelta_other_units_dtype(self, dtype): + idx = TimedeltaIndex(["1 days", "NaT", "2 days"]) + values = idx.values.astype(dtype) + + exp = np.array([False, True, False]) + tm.assert_numpy_array_equal(isna(values), exp) + tm.assert_numpy_array_equal(notna(values), ~exp) + + exp = Series([False, True, False]) + s = Series(values) + tm.assert_series_equal(isna(s), exp) + tm.assert_series_equal(notna(s), ~exp) + s = Series(values, dtype=object) + tm.assert_series_equal(isna(s), exp) + tm.assert_series_equal(notna(s), ~exp) + + def test_period(self): + idx = pd.PeriodIndex(["2011-01", "NaT", "2012-01"], freq="M") + exp = np.array([False, True, False]) + tm.assert_numpy_array_equal(isna(idx), exp) + tm.assert_numpy_array_equal(notna(idx), ~exp) + + exp = Series([False, True, False]) + s = Series(idx) + tm.assert_series_equal(isna(s), exp) + tm.assert_series_equal(notna(s), ~exp) + s = Series(idx, dtype=object) + tm.assert_series_equal(isna(s), exp) + tm.assert_series_equal(notna(s), ~exp) + + def test_decimal(self): + # scalars GH#23530 + a = Decimal(1.0) + assert isna(a) is False + assert notna(a) is True + + b = Decimal("NaN") + assert isna(b) is True + assert notna(b) is False + + # array + arr = np.array([a, b]) + expected = np.array([False, True]) + result = isna(arr) + tm.assert_numpy_array_equal(result, expected) + + result = notna(arr) + tm.assert_numpy_array_equal(result, ~expected) + + # series + ser = Series(arr) + expected = Series(expected) + result = isna(ser) + tm.assert_series_equal(result, expected) + + result = notna(ser) + tm.assert_series_equal(result, ~expected) + + # index + idx = Index(arr) + expected = np.array([False, True]) + result = isna(idx) + tm.assert_numpy_array_equal(result, expected) + + result = notna(idx) + tm.assert_numpy_array_equal(result, ~expected) + + +@pytest.mark.parametrize("dtype_equal", [True, False]) +def test_array_equivalent(dtype_equal): + assert array_equivalent( + np.array([np.nan, np.nan]), np.array([np.nan, np.nan]), dtype_equal=dtype_equal + ) + assert array_equivalent( + np.array([np.nan, 1, np.nan]), + np.array([np.nan, 1, np.nan]), + dtype_equal=dtype_equal, + ) + assert array_equivalent( + np.array([np.nan, None], dtype="object"), + np.array([np.nan, None], dtype="object"), + dtype_equal=dtype_equal, + ) + # Check the handling of nested arrays in array_equivalent_object + assert array_equivalent( + np.array([np.array([np.nan, None], dtype="object"), None], dtype="object"), + np.array([np.array([np.nan, None], dtype="object"), None], dtype="object"), + dtype_equal=dtype_equal, + ) + assert array_equivalent( + np.array([np.nan, 1 + 1j], dtype="complex"), + np.array([np.nan, 1 + 1j], dtype="complex"), + dtype_equal=dtype_equal, + ) + assert not array_equivalent( + np.array([np.nan, 1 + 1j], dtype="complex"), + np.array([np.nan, 1 + 2j], dtype="complex"), + dtype_equal=dtype_equal, + ) + assert not array_equivalent( + np.array([np.nan, 1, np.nan]), + np.array([np.nan, 2, np.nan]), + dtype_equal=dtype_equal, + ) + assert not array_equivalent( + np.array(["a", "b", "c", "d"]), np.array(["e", "e"]), dtype_equal=dtype_equal + ) + assert array_equivalent( + Index([0, np.nan]), Index([0, np.nan]), dtype_equal=dtype_equal + ) + assert not array_equivalent( + Index([0, np.nan]), Index([1, np.nan]), dtype_equal=dtype_equal + ) + + +@pytest.mark.parametrize("dtype_equal", [True, False]) +def test_array_equivalent_tdi(dtype_equal): + assert array_equivalent( + TimedeltaIndex([0, np.nan]), + TimedeltaIndex([0, np.nan]), + dtype_equal=dtype_equal, + ) + assert not array_equivalent( + TimedeltaIndex([0, np.nan]), + TimedeltaIndex([1, np.nan]), + dtype_equal=dtype_equal, + ) + + +@pytest.mark.parametrize("dtype_equal", [True, False]) +def test_array_equivalent_dti(dtype_equal): + assert array_equivalent( + DatetimeIndex([0, np.nan]), DatetimeIndex([0, np.nan]), dtype_equal=dtype_equal + ) + assert not array_equivalent( + DatetimeIndex([0, np.nan]), DatetimeIndex([1, np.nan]), dtype_equal=dtype_equal + ) + + dti1 = DatetimeIndex([0, np.nan], tz="US/Eastern") + dti2 = DatetimeIndex([0, np.nan], tz="CET") + dti3 = DatetimeIndex([1, np.nan], tz="US/Eastern") + + assert array_equivalent( + dti1, + dti1, + dtype_equal=dtype_equal, + ) + assert not array_equivalent( + dti1, + dti3, + dtype_equal=dtype_equal, + ) + # The rest are not dtype_equal + assert not array_equivalent(DatetimeIndex([0, np.nan]), dti1) + assert array_equivalent( + dti2, + dti1, + ) + + assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan])) + + +@pytest.mark.parametrize( + "val", [1, 1.1, 1 + 1j, True, "abc", [1, 2], (1, 2), {1, 2}, {"a": 1}, None] +) +def test_array_equivalent_series(val): + arr = np.array([1, 2]) + msg = "elementwise comparison failed" + cm = ( + # stacklevel is chosen to make sense when called from .equals + tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False) + if isinstance(val, str) and not np_version_gte1p25 + else nullcontext() + ) + with cm: + assert not array_equivalent(Series([arr, arr]), Series([arr, val])) + + +def test_array_equivalent_array_mismatched_shape(): + # to trigger the motivating bug, the first N elements of the arrays need + # to match + first = np.array([1, 2, 3]) + second = np.array([1, 2]) + + left = Series([first, "a"], dtype=object) + right = Series([second, "a"], dtype=object) + assert not array_equivalent(left, right) + + +def test_array_equivalent_array_mismatched_dtype(): + # same shape, different dtype can still be equivalent + first = np.array([1, 2], dtype=np.float64) + second = np.array([1, 2]) + + left = Series([first, "a"], dtype=object) + right = Series([second, "a"], dtype=object) + assert array_equivalent(left, right) + + +def test_array_equivalent_different_dtype_but_equal(): + # Unclear if this is exposed anywhere in the public-facing API + assert array_equivalent(np.array([1, 2]), np.array([1.0, 2.0])) + + +@pytest.mark.parametrize( + "lvalue, rvalue", + [ + # There are 3 variants for each of lvalue and rvalue. We include all + # three for the tz-naive `now` and exclude the datetim64 variant + # for utcnow because it drops tzinfo. + (fix_now, fix_utcnow), + (fix_now.to_datetime64(), fix_utcnow), + (fix_now.to_pydatetime(), fix_utcnow), + (fix_now, fix_utcnow), + (fix_now.to_datetime64(), fix_utcnow.to_pydatetime()), + (fix_now.to_pydatetime(), fix_utcnow.to_pydatetime()), + ], +) +def test_array_equivalent_tzawareness(lvalue, rvalue): + # we shouldn't raise if comparing tzaware and tznaive datetimes + left = np.array([lvalue], dtype=object) + right = np.array([rvalue], dtype=object) + + assert not array_equivalent(left, right, strict_nan=True) + assert not array_equivalent(left, right, strict_nan=False) + + +def test_array_equivalent_compat(): + # see gh-13388 + m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)]) + n = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)]) + assert array_equivalent(m, n, strict_nan=True) + assert array_equivalent(m, n, strict_nan=False) + + m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)]) + n = np.array([(1, 2), (4, 3)], dtype=[("a", int), ("b", float)]) + assert not array_equivalent(m, n, strict_nan=True) + assert not array_equivalent(m, n, strict_nan=False) + + m = np.array([(1, 2), (3, 4)], dtype=[("a", int), ("b", float)]) + n = np.array([(1, 2), (3, 4)], dtype=[("b", int), ("a", float)]) + assert not array_equivalent(m, n, strict_nan=True) + assert not array_equivalent(m, n, strict_nan=False) + + +@pytest.mark.parametrize("dtype", ["O", "S", "U"]) +def test_array_equivalent_str(dtype): + assert array_equivalent( + np.array(["A", "B"], dtype=dtype), np.array(["A", "B"], dtype=dtype) + ) + assert not array_equivalent( + np.array(["A", "B"], dtype=dtype), np.array(["A", "X"], dtype=dtype) + ) + + +@pytest.mark.parametrize("strict_nan", [True, False]) +def test_array_equivalent_nested(strict_nan): + # reached in groupby aggregations, make sure we use np.any when checking + # if the comparison is truthy + left = np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object) + right = np.array([np.array([50, 70, 90]), np.array([20, 30])], dtype=object) + + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + left = np.empty(2, dtype=object) + left[:] = [np.array([50, 70, 90]), np.array([20, 30, 40])] + right = np.empty(2, dtype=object) + right[:] = [np.array([50, 70, 90]), np.array([20, 30, 40])] + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + left = np.array([np.array([50, 50, 50]), np.array([40, 40])], dtype=object) + right = np.array([50, 40]) + assert not array_equivalent(left, right, strict_nan=strict_nan) + + +@pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning") +@pytest.mark.parametrize("strict_nan", [True, False]) +def test_array_equivalent_nested2(strict_nan): + # more than one level of nesting + left = np.array( + [ + np.array([np.array([50, 70]), np.array([90])], dtype=object), + np.array([np.array([20, 30])], dtype=object), + ], + dtype=object, + ) + right = np.array( + [ + np.array([np.array([50, 70]), np.array([90])], dtype=object), + np.array([np.array([20, 30])], dtype=object), + ], + dtype=object, + ) + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + left = np.array([np.array([np.array([50, 50, 50])], dtype=object)], dtype=object) + right = np.array([50]) + assert not array_equivalent(left, right, strict_nan=strict_nan) + + +@pytest.mark.parametrize("strict_nan", [True, False]) +def test_array_equivalent_nested_list(strict_nan): + left = np.array([[50, 70, 90], [20, 30]], dtype=object) + right = np.array([[50, 70, 90], [20, 30]], dtype=object) + + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + left = np.array([[50, 50, 50], [40, 40]], dtype=object) + right = np.array([50, 40]) + assert not array_equivalent(left, right, strict_nan=strict_nan) + + +@pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning") +@pytest.mark.xfail(reason="failing") +@pytest.mark.parametrize("strict_nan", [True, False]) +def test_array_equivalent_nested_mixed_list(strict_nan): + # mixed arrays / lists in left and right + # https://github.com/pandas-dev/pandas/issues/50360 + left = np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object) + right = np.array([[1, 2, 3], [4, 5]], dtype=object) + + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + # multiple levels of nesting + left = np.array( + [ + np.array([np.array([1, 2, 3]), np.array([4, 5])], dtype=object), + np.array([np.array([6]), np.array([7, 8]), np.array([9])], dtype=object), + ], + dtype=object, + ) + right = np.array([[[1, 2, 3], [4, 5]], [[6], [7, 8], [9]]], dtype=object) + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + # same-length lists + subarr = np.empty(2, dtype=object) + subarr[:] = [ + np.array([None, "b"], dtype=object), + np.array(["c", "d"], dtype=object), + ] + left = np.array([subarr, None], dtype=object) + right = np.array([[[None, "b"], ["c", "d"]], None], dtype=object) + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + +@pytest.mark.xfail(reason="failing") +@pytest.mark.parametrize("strict_nan", [True, False]) +def test_array_equivalent_nested_dicts(strict_nan): + left = np.array([{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object) + right = np.array( + [{"f1": 1, "f2": np.array(["a", "b"], dtype=object)}], dtype=object + ) + assert array_equivalent(left, right, strict_nan=strict_nan) + assert not array_equivalent(left, right[::-1], strict_nan=strict_nan) + + right2 = np.array([{"f1": 1, "f2": ["a", "b"]}], dtype=object) + assert array_equivalent(left, right2, strict_nan=strict_nan) + assert not array_equivalent(left, right2[::-1], strict_nan=strict_nan) + + +def test_array_equivalent_index_with_tuples(): + # GH#48446 + idx1 = Index(np.array([(pd.NA, 4), (1, 1)], dtype="object")) + idx2 = Index(np.array([(1, 1), (pd.NA, 4)], dtype="object")) + assert not array_equivalent(idx1, idx2) + assert not idx1.equals(idx2) + assert not array_equivalent(idx2, idx1) + assert not idx2.equals(idx1) + + idx1 = Index(np.array([(4, pd.NA), (1, 1)], dtype="object")) + idx2 = Index(np.array([(1, 1), (4, pd.NA)], dtype="object")) + assert not array_equivalent(idx1, idx2) + assert not idx1.equals(idx2) + assert not array_equivalent(idx2, idx1) + assert not idx2.equals(idx1) + + +@pytest.mark.parametrize( + "dtype, na_value", + [ + # Datetime-like + (np.dtype("M8[ns]"), np.datetime64("NaT", "ns")), + (np.dtype("m8[ns]"), np.timedelta64("NaT", "ns")), + (DatetimeTZDtype.construct_from_string("datetime64[ns, US/Eastern]"), NaT), + (PeriodDtype("M"), NaT), + # Integer + ("u1", 0), + ("u2", 0), + ("u4", 0), + ("u8", 0), + ("i1", 0), + ("i2", 0), + ("i4", 0), + ("i8", 0), + # Bool + ("bool", False), + # Float + ("f2", np.nan), + ("f4", np.nan), + ("f8", np.nan), + # Object + ("O", np.nan), + # Interval + (IntervalDtype(), np.nan), + ], +) +def test_na_value_for_dtype(dtype, na_value): + result = na_value_for_dtype(pandas_dtype(dtype)) + # identify check doesn't work for datetime64/timedelta64("NaT") bc they + # are not singletons + assert result is na_value or ( + isna(result) and isna(na_value) and type(result) is type(na_value) + ) + + +class TestNAObj: + def _check_behavior(self, arr, expected): + result = libmissing.isnaobj(arr) + tm.assert_numpy_array_equal(result, expected) + result = libmissing.isnaobj(arr, inf_as_na=True) + tm.assert_numpy_array_equal(result, expected) + + arr = np.atleast_2d(arr) + expected = np.atleast_2d(expected) + + result = libmissing.isnaobj(arr) + tm.assert_numpy_array_equal(result, expected) + result = libmissing.isnaobj(arr, inf_as_na=True) + tm.assert_numpy_array_equal(result, expected) + + # Test fortran order + arr = arr.copy(order="F") + result = libmissing.isnaobj(arr) + tm.assert_numpy_array_equal(result, expected) + result = libmissing.isnaobj(arr, inf_as_na=True) + tm.assert_numpy_array_equal(result, expected) + + def test_basic(self): + arr = np.array([1, None, "foo", -5.1, NaT, np.nan]) + expected = np.array([False, True, False, False, True, True]) + + self._check_behavior(arr, expected) + + def test_non_obj_dtype(self): + arr = np.array([1, 3, np.nan, 5], dtype=float) + expected = np.array([False, False, True, False]) + + self._check_behavior(arr, expected) + + def test_empty_arr(self): + arr = np.array([]) + expected = np.array([], dtype=bool) + + self._check_behavior(arr, expected) + + def test_empty_str_inp(self): + arr = np.array([""]) # empty but not na + expected = np.array([False]) + + self._check_behavior(arr, expected) + + def test_empty_like(self): + # see gh-13717: no segfaults! + arr = np.empty_like([None]) + expected = np.array([True]) + + self._check_behavior(arr, expected) + + +m8_units = ["as", "ps", "ns", "us", "ms", "s", "m", "h", "D", "W", "M", "Y"] + +na_vals = ( + [ + None, + NaT, + float("NaN"), + complex("NaN"), + np.nan, + np.float64("NaN"), + np.float32("NaN"), + np.complex64(np.nan), + np.complex128(np.nan), + np.datetime64("NaT"), + np.timedelta64("NaT"), + ] + + [np.datetime64("NaT", unit) for unit in m8_units] + + [np.timedelta64("NaT", unit) for unit in m8_units] +) + +inf_vals = [ + float("inf"), + float("-inf"), + complex("inf"), + complex("-inf"), + np.inf, + -np.inf, +] + +int_na_vals = [ + # Values that match iNaT, which we treat as null in specific cases + np.int64(NaT._value), + int(NaT._value), +] + +sometimes_na_vals = [Decimal("NaN")] + +never_na_vals = [ + # float/complex values that when viewed as int64 match iNaT + -0.0, + np.float64("-0.0"), + -0j, + np.complex64(-0j), +] + + +class TestLibMissing: + @pytest.mark.parametrize("func", [libmissing.checknull, isna]) + @pytest.mark.parametrize( + "value", na_vals + sometimes_na_vals # type: ignore[operator] + ) + def test_checknull_na_vals(self, func, value): + assert func(value) + + @pytest.mark.parametrize("func", [libmissing.checknull, isna]) + @pytest.mark.parametrize("value", inf_vals) + def test_checknull_inf_vals(self, func, value): + assert not func(value) + + @pytest.mark.parametrize("func", [libmissing.checknull, isna]) + @pytest.mark.parametrize("value", int_na_vals) + def test_checknull_intna_vals(self, func, value): + assert not func(value) + + @pytest.mark.parametrize("func", [libmissing.checknull, isna]) + @pytest.mark.parametrize("value", never_na_vals) + def test_checknull_never_na_vals(self, func, value): + assert not func(value) + + @pytest.mark.parametrize( + "value", na_vals + sometimes_na_vals # type: ignore[operator] + ) + def test_checknull_old_na_vals(self, value): + assert libmissing.checknull(value, inf_as_na=True) + + @pytest.mark.parametrize("value", inf_vals) + def test_checknull_old_inf_vals(self, value): + assert libmissing.checknull(value, inf_as_na=True) + + @pytest.mark.parametrize("value", int_na_vals) + def test_checknull_old_intna_vals(self, value): + assert not libmissing.checknull(value, inf_as_na=True) + + @pytest.mark.parametrize("value", int_na_vals) + def test_checknull_old_never_na_vals(self, value): + assert not libmissing.checknull(value, inf_as_na=True) + + def test_is_matching_na(self, nulls_fixture, nulls_fixture2): + left = nulls_fixture + right = nulls_fixture2 + + assert libmissing.is_matching_na(left, left) + + if left is right: + assert libmissing.is_matching_na(left, right) + elif is_float(left) and is_float(right): + # np.nan vs float("NaN") we consider as matching + assert libmissing.is_matching_na(left, right) + elif type(left) is type(right): + # e.g. both Decimal("NaN") + assert libmissing.is_matching_na(left, right) + else: + assert not libmissing.is_matching_na(left, right) + + def test_is_matching_na_nan_matches_none(self): + assert not libmissing.is_matching_na(None, np.nan) + assert not libmissing.is_matching_na(np.nan, None) + + assert libmissing.is_matching_na(None, np.nan, nan_matches_none=True) + assert libmissing.is_matching_na(np.nan, None, nan_matches_none=True) + + +class TestIsValidNAForDtype: + def test_is_valid_na_for_dtype_interval(self): + dtype = IntervalDtype("int64", "left") + assert not is_valid_na_for_dtype(NaT, dtype) + + dtype = IntervalDtype("datetime64[ns]", "both") + assert not is_valid_na_for_dtype(NaT, dtype) + + def test_is_valid_na_for_dtype_categorical(self): + dtype = CategoricalDtype(categories=[0, 1, 2]) + assert is_valid_na_for_dtype(np.nan, dtype) + + assert not is_valid_na_for_dtype(NaT, dtype) + assert not is_valid_na_for_dtype(np.datetime64("NaT", "ns"), dtype) + assert not is_valid_na_for_dtype(np.timedelta64("NaT", "ns"), dtype) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/__init__.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..446d9da4377712b073d76dac7672dcf1de00cf04 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/__init__.py @@ -0,0 +1,25 @@ +def get_groupby_method_args(name, obj): + """ + Get required arguments for a groupby method. + + When parametrizing a test over groupby methods (e.g. "sum", "mean", "fillna"), + it is often the case that arguments are required for certain methods. + + Parameters + ---------- + name: str + Name of the method. + obj: Series or DataFrame + pandas object that is being grouped. + + Returns + ------- + A tuple of required arguments for the method. + """ + if name in ("nth", "fillna", "take"): + return (0,) + if name == "quantile": + return (0.5,) + if name == "corrwith": + return (obj,) + return () diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/conftest.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..dce3f072ed903ace4cb014f63d60ffde84c9bf4c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/conftest.py @@ -0,0 +1,208 @@ +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Index, + Series, + date_range, +) +from pandas.core.groupby.base import ( + reduction_kernels, + transformation_kernels, +) + + +@pytest.fixture(params=[True, False]) +def sort(request): + return request.param + + +@pytest.fixture(params=[True, False]) +def as_index(request): + return request.param + + +@pytest.fixture(params=[True, False]) +def dropna(request): + return request.param + + +@pytest.fixture(params=[True, False]) +def observed(request): + return request.param + + +@pytest.fixture +def df(): + return DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.default_rng(2).standard_normal(8), + "D": np.random.default_rng(2).standard_normal(8), + } + ) + + +@pytest.fixture +def ts(): + return Series( + np.random.default_rng(2).standard_normal(30), + index=date_range("2000-01-01", periods=30, freq="B"), + ) + + +@pytest.fixture +def tsframe(): + return DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=30, freq="B"), + ) + + +@pytest.fixture +def three_group(): + return DataFrame( + { + "A": [ + "foo", + "foo", + "foo", + "foo", + "bar", + "bar", + "bar", + "bar", + "foo", + "foo", + "foo", + ], + "B": [ + "one", + "one", + "one", + "two", + "one", + "one", + "one", + "two", + "two", + "two", + "one", + ], + "C": [ + "dull", + "dull", + "shiny", + "dull", + "dull", + "shiny", + "shiny", + "dull", + "shiny", + "shiny", + "shiny", + ], + "D": np.random.default_rng(2).standard_normal(11), + "E": np.random.default_rng(2).standard_normal(11), + "F": np.random.default_rng(2).standard_normal(11), + } + ) + + +@pytest.fixture() +def slice_test_df(): + data = [ + [0, "a", "a0_at_0"], + [1, "b", "b0_at_1"], + [2, "a", "a1_at_2"], + [3, "b", "b1_at_3"], + [4, "c", "c0_at_4"], + [5, "a", "a2_at_5"], + [6, "a", "a3_at_6"], + [7, "a", "a4_at_7"], + ] + df = DataFrame(data, columns=["Index", "Group", "Value"]) + return df.set_index("Index") + + +@pytest.fixture() +def slice_test_grouped(slice_test_df): + return slice_test_df.groupby("Group", as_index=False) + + +@pytest.fixture(params=sorted(reduction_kernels)) +def reduction_func(request): + """ + yields the string names of all groupby reduction functions, one at a time. + """ + return request.param + + +@pytest.fixture(params=sorted(transformation_kernels)) +def transformation_func(request): + """yields the string names of all groupby transformation functions.""" + return request.param + + +@pytest.fixture(params=sorted(reduction_kernels) + sorted(transformation_kernels)) +def groupby_func(request): + """yields both aggregation and transformation functions.""" + return request.param + + +@pytest.fixture(params=[True, False]) +def parallel(request): + """parallel keyword argument for numba.jit""" + return request.param + + +# Can parameterize nogil & nopython over True | False, but limiting per +# https://github.com/pandas-dev/pandas/pull/41971#issuecomment-860607472 + + +@pytest.fixture(params=[False]) +def nogil(request): + """nogil keyword argument for numba.jit""" + return request.param + + +@pytest.fixture(params=[True]) +def nopython(request): + """nopython keyword argument for numba.jit""" + return request.param + + +@pytest.fixture( + params=[ + ("mean", {}), + ("var", {"ddof": 1}), + ("var", {"ddof": 0}), + ("std", {"ddof": 1}), + ("std", {"ddof": 0}), + ("sum", {}), + ("min", {}), + ("max", {}), + ("sum", {"min_count": 2}), + ("min", {"min_count": 2}), + ("max", {"min_count": 2}), + ], + ids=[ + "mean", + "var_1", + "var_0", + "std_1", + "std_0", + "sum", + "min", + "max", + "sum-min_count", + "min-min_count", + "max-min_count", + ], +) +def numba_supported_reductions(request): + """reductions supported with engine='numba'""" + return request.param diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_all_methods.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_all_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..ad35bec70f668f1df9808d1aebec2b1405424bc1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_all_methods.py @@ -0,0 +1,83 @@ +""" +Tests that apply to all groupby operation methods. + +The only tests that should appear here are those that use the `groupby_func` fixture. +Even if it does use that fixture, prefer a more specific test file if it available +such as: + + - test_categorical + - test_groupby_dropna + - test_groupby_subclass + - test_raises +""" + +import pytest + +import pandas as pd +from pandas import DataFrame +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +def test_multiindex_group_all_columns_when_empty(groupby_func): + # GH 32464 + df = DataFrame({"a": [], "b": [], "c": []}).set_index(["a", "b", "c"]) + gb = df.groupby(["a", "b", "c"], group_keys=False) + method = getattr(gb, groupby_func) + args = get_groupby_method_args(groupby_func, df) + + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = method(*args).index + expected = df.index + tm.assert_index_equal(result, expected) + + +def test_duplicate_columns(request, groupby_func, as_index): + # GH#50806 + if groupby_func == "corrwith": + msg = "GH#50845 - corrwith fails when there are duplicate columns" + request.applymarker(pytest.mark.xfail(reason=msg)) + df = DataFrame([[1, 3, 6], [1, 4, 7], [2, 5, 8]], columns=list("abb")) + args = get_groupby_method_args(groupby_func, df) + gb = df.groupby("a", as_index=as_index) + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = getattr(gb, groupby_func)(*args) + + expected_df = df.set_axis(["a", "b", "c"], axis=1) + expected_args = get_groupby_method_args(groupby_func, expected_df) + expected_gb = expected_df.groupby("a", as_index=as_index) + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + expected = getattr(expected_gb, groupby_func)(*expected_args) + if groupby_func not in ("size", "ngroup", "cumcount"): + expected = expected.rename(columns={"c": "b"}) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "idx", + [ + pd.Index(["a", "a"], name="foo"), + pd.MultiIndex.from_tuples((("a", "a"), ("a", "a")), names=["foo", "bar"]), + ], +) +def test_dup_labels_output_shape(groupby_func, idx): + if groupby_func in {"size", "ngroup", "cumcount"}: + pytest.skip(f"Not applicable for {groupby_func}") + + df = DataFrame([[1, 1]], columns=idx) + grp_by = df.groupby([0]) + + args = get_groupby_method_args(groupby_func, df) + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = getattr(grp_by, groupby_func)(*args) + + assert result.shape == (1, 2) + tm.assert_index_equal(result.columns, idx) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_api.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5982954de2f889d3f23d30273cb1a10089315f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_api.py @@ -0,0 +1,265 @@ +""" +Tests of the groupby API, including internal consistency and with other pandas objects. + +Tests in this file should only check the existence, names, and arguments of groupby +methods. It should not test the results of any groupby operation. +""" + +import inspect + +import pytest + +from pandas import ( + DataFrame, + Series, +) +from pandas.core.groupby.base import ( + groupby_other_methods, + reduction_kernels, + transformation_kernels, +) +from pandas.core.groupby.generic import ( + DataFrameGroupBy, + SeriesGroupBy, +) + + +def test_tab_completion(multiindex_dataframe_random_data): + grp = multiindex_dataframe_random_data.groupby(level="second") + results = {v for v in dir(grp) if not v.startswith("_")} + expected = { + "A", + "B", + "C", + "agg", + "aggregate", + "apply", + "boxplot", + "filter", + "first", + "get_group", + "groups", + "hist", + "indices", + "last", + "max", + "mean", + "median", + "min", + "ngroups", + "nth", + "ohlc", + "plot", + "prod", + "size", + "std", + "sum", + "transform", + "var", + "sem", + "count", + "nunique", + "head", + "describe", + "cummax", + "quantile", + "rank", + "cumprod", + "tail", + "resample", + "cummin", + "fillna", + "cumsum", + "cumcount", + "ngroup", + "all", + "shift", + "skew", + "take", + "pct_change", + "any", + "corr", + "corrwith", + "cov", + "dtypes", + "ndim", + "diff", + "idxmax", + "idxmin", + "ffill", + "bfill", + "rolling", + "expanding", + "pipe", + "sample", + "ewm", + "value_counts", + } + assert results == expected + + +def test_all_methods_categorized(multiindex_dataframe_random_data): + grp = multiindex_dataframe_random_data.groupby( + multiindex_dataframe_random_data.iloc[:, 0] + ) + names = {_ for _ in dir(grp) if not _.startswith("_")} - set( + multiindex_dataframe_random_data.columns + ) + new_names = set(names) + new_names -= reduction_kernels + new_names -= transformation_kernels + new_names -= groupby_other_methods + + assert not reduction_kernels & transformation_kernels + assert not reduction_kernels & groupby_other_methods + assert not transformation_kernels & groupby_other_methods + + # new public method? + if new_names: + msg = f""" +There are uncategorized methods defined on the Grouper class: +{new_names}. + +Was a new method recently added? + +Every public method On Grouper must appear in exactly one the +following three lists defined in pandas.core.groupby.base: +- `reduction_kernels` +- `transformation_kernels` +- `groupby_other_methods` +see the comments in pandas/core/groupby/base.py for guidance on +how to fix this test. + """ + raise AssertionError(msg) + + # removed a public method? + all_categorized = reduction_kernels | transformation_kernels | groupby_other_methods + if names != all_categorized: + msg = f""" +Some methods which are supposed to be on the Grouper class +are missing: +{all_categorized - names}. + +They're still defined in one of the lists that live in pandas/core/groupby/base.py. +If you removed a method, you should update them +""" + raise AssertionError(msg) + + +def test_frame_consistency(groupby_func): + # GH#48028 + if groupby_func in ("first", "last"): + msg = "first and last are entirely different between frame and groupby" + pytest.skip(reason=msg) + + if groupby_func in ("cumcount", "ngroup"): + assert not hasattr(DataFrame, groupby_func) + return + + frame_method = getattr(DataFrame, groupby_func) + gb_method = getattr(DataFrameGroupBy, groupby_func) + result = set(inspect.signature(gb_method).parameters) + if groupby_func == "size": + # "size" is a method on GroupBy but property on DataFrame: + expected = {"self"} + else: + expected = set(inspect.signature(frame_method).parameters) + + # Exclude certain arguments from result and expected depending on the operation + # Some of these may be purposeful inconsistencies between the APIs + exclude_expected, exclude_result = set(), set() + if groupby_func in ("any", "all"): + exclude_expected = {"kwargs", "bool_only", "axis"} + elif groupby_func in ("count",): + exclude_expected = {"numeric_only", "axis"} + elif groupby_func in ("nunique",): + exclude_expected = {"axis"} + elif groupby_func in ("max", "min"): + exclude_expected = {"axis", "kwargs", "skipna"} + exclude_result = {"min_count", "engine", "engine_kwargs"} + elif groupby_func in ("mean", "std", "sum", "var"): + exclude_expected = {"axis", "kwargs", "skipna"} + exclude_result = {"engine", "engine_kwargs"} + elif groupby_func in ("median", "prod", "sem"): + exclude_expected = {"axis", "kwargs", "skipna"} + elif groupby_func in ("backfill", "bfill", "ffill", "pad"): + exclude_expected = {"downcast", "inplace", "axis", "limit_area"} + elif groupby_func in ("cummax", "cummin"): + exclude_expected = {"skipna", "args"} + exclude_result = {"numeric_only"} + elif groupby_func in ("cumprod", "cumsum"): + exclude_expected = {"skipna"} + elif groupby_func in ("pct_change",): + exclude_expected = {"kwargs"} + exclude_result = {"axis"} + elif groupby_func in ("rank",): + exclude_expected = {"numeric_only"} + elif groupby_func in ("quantile",): + exclude_expected = {"method", "axis"} + + # Ensure excluded arguments are actually in the signatures + assert result & exclude_result == exclude_result + assert expected & exclude_expected == exclude_expected + + result -= exclude_result + expected -= exclude_expected + assert result == expected + + +def test_series_consistency(request, groupby_func): + # GH#48028 + if groupby_func in ("first", "last"): + pytest.skip("first and last are entirely different between Series and groupby") + + if groupby_func in ("cumcount", "corrwith", "ngroup"): + assert not hasattr(Series, groupby_func) + return + + series_method = getattr(Series, groupby_func) + gb_method = getattr(SeriesGroupBy, groupby_func) + result = set(inspect.signature(gb_method).parameters) + if groupby_func == "size": + # "size" is a method on GroupBy but property on Series + expected = {"self"} + else: + expected = set(inspect.signature(series_method).parameters) + + # Exclude certain arguments from result and expected depending on the operation + # Some of these may be purposeful inconsistencies between the APIs + exclude_expected, exclude_result = set(), set() + if groupby_func in ("any", "all"): + exclude_expected = {"kwargs", "bool_only", "axis"} + elif groupby_func in ("diff",): + exclude_result = {"axis"} + elif groupby_func in ("max", "min"): + exclude_expected = {"axis", "kwargs", "skipna"} + exclude_result = {"min_count", "engine", "engine_kwargs"} + elif groupby_func in ("mean", "std", "sum", "var"): + exclude_expected = {"axis", "kwargs", "skipna"} + exclude_result = {"engine", "engine_kwargs"} + elif groupby_func in ("median", "prod", "sem"): + exclude_expected = {"axis", "kwargs", "skipna"} + elif groupby_func in ("backfill", "bfill", "ffill", "pad"): + exclude_expected = {"downcast", "inplace", "axis", "limit_area"} + elif groupby_func in ("cummax", "cummin"): + exclude_expected = {"skipna", "args"} + exclude_result = {"numeric_only"} + elif groupby_func in ("cumprod", "cumsum"): + exclude_expected = {"skipna"} + elif groupby_func in ("pct_change",): + exclude_expected = {"kwargs"} + exclude_result = {"axis"} + elif groupby_func in ("rank",): + exclude_expected = {"numeric_only"} + elif groupby_func in ("idxmin", "idxmax"): + exclude_expected = {"args", "kwargs"} + elif groupby_func in ("quantile",): + exclude_result = {"numeric_only"} + + # Ensure excluded arguments are actually in the signatures + assert result & exclude_result == exclude_result + assert expected & exclude_expected == exclude_expected + + result -= exclude_result + expected -= exclude_expected + assert result == expected diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_apply.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..8ee38a688a1a0e54976b6dcbdbba4a2c2696b535 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_apply.py @@ -0,0 +1,1605 @@ +from datetime import ( + date, + datetime, +) + +import numpy as np +import pytest + +from pandas._config import using_string_dtype + +import pandas as pd +from pandas import ( + DataFrame, + Index, + MultiIndex, + Series, + bdate_range, +) +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +def test_apply_func_that_appends_group_to_list_without_copy(): + # GH: 17718 + + df = DataFrame(1, index=list(range(10)) * 10, columns=[0]).reset_index() + groups = [] + + def store(group): + groups.append(group) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby("index").apply(store) + expected_value = DataFrame( + {"index": [0] * 10, 0: [1] * 10}, index=pd.RangeIndex(0, 100, 10) + ) + + tm.assert_frame_equal(groups[0], expected_value) + + +def test_apply_index_date(using_infer_string): + # GH 5788 + ts = [ + "2011-05-16 00:00", + "2011-05-16 01:00", + "2011-05-16 02:00", + "2011-05-16 03:00", + "2011-05-17 02:00", + "2011-05-17 03:00", + "2011-05-17 04:00", + "2011-05-17 05:00", + "2011-05-18 02:00", + "2011-05-18 03:00", + "2011-05-18 04:00", + "2011-05-18 05:00", + ] + df = DataFrame( + { + "value": [ + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + ], + }, + index=Index(pd.to_datetime(ts), name="date_time"), + ) + expected = df.groupby(df.index.date).idxmax() + result = df.groupby(df.index.date).apply(lambda x: x.idxmax()) + tm.assert_frame_equal(result, expected) + + +def test_apply_index_date_object(): + # GH 5789 + # don't auto coerce dates + ts = [ + "2011-05-16 00:00", + "2011-05-16 01:00", + "2011-05-16 02:00", + "2011-05-16 03:00", + "2011-05-17 02:00", + "2011-05-17 03:00", + "2011-05-17 04:00", + "2011-05-17 05:00", + "2011-05-18 02:00", + "2011-05-18 03:00", + "2011-05-18 04:00", + "2011-05-18 05:00", + ] + df = DataFrame([row.split() for row in ts], columns=["date", "time"]) + df["value"] = [ + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + 1.40893, + 1.40760, + 1.40750, + 1.40649, + ] + exp_idx = Index(["2011-05-16", "2011-05-17", "2011-05-18"], name="date") + expected = Series(["00:00", "02:00", "02:00"], index=exp_idx) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("date", group_keys=False).apply( + lambda x: x["time"][x["value"].idxmax()] + ) + tm.assert_series_equal(result, expected) + + +def test_apply_trivial(using_infer_string): + # GH 20066 + # trivial apply: ignore input and return a constant dataframe. + df = DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + dtype = "str" if using_infer_string else "object" + expected = pd.concat([df.iloc[1:], df.iloc[1:]], axis=1, keys=["float64", dtype]) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([str(x) for x in df.dtypes], axis=1) + result = gb.apply(lambda x: df.iloc[1:]) + + tm.assert_frame_equal(result, expected) + + +def test_apply_trivial_fail(using_infer_string): + # GH 20066 + df = DataFrame( + {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]}, + columns=["key", "data"], + ) + dtype = "str" if using_infer_string else "object" + expected = pd.concat([df, df], axis=1, keys=["float64", dtype]) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([str(x) for x in df.dtypes], axis=1, group_keys=True) + result = gb.apply(lambda x: df) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "df, group_names", + [ + (DataFrame({"a": [1, 1, 1, 2, 3], "b": ["a", "a", "a", "b", "c"]}), [1, 2, 3]), + (DataFrame({"a": [0, 0, 1, 1], "b": [0, 1, 0, 1]}), [0, 1]), + (DataFrame({"a": [1]}), [1]), + (DataFrame({"a": [1, 1, 1, 2, 2, 1, 1, 2], "b": range(8)}), [1, 2]), + (DataFrame({"a": [1, 2, 3, 1, 2, 3], "two": [4, 5, 6, 7, 8, 9]}), [1, 2, 3]), + ( + DataFrame( + { + "a": list("aaabbbcccc"), + "B": [3, 4, 3, 6, 5, 2, 1, 9, 5, 4], + "C": [4, 0, 2, 2, 2, 7, 8, 6, 2, 8], + } + ), + ["a", "b", "c"], + ), + (DataFrame([[1, 2, 3], [2, 2, 3]], columns=["a", "b", "c"]), [1, 2]), + ], + ids=[ + "GH2936", + "GH7739 & GH10519", + "GH10519", + "GH2656", + "GH12155", + "GH20084", + "GH21417", + ], +) +def test_group_apply_once_per_group(df, group_names): + # GH2936, GH7739, GH10519, GH2656, GH12155, GH20084, GH21417 + + # This test should ensure that a function is only evaluated + # once per group. Previously the function has been evaluated twice + # on the first group to check if the Cython index slider is safe to use + # This test ensures that the side effect (append to list) is only triggered + # once per group + + names = [] + # cannot parameterize over the functions since they need external + # `names` to detect side effects + + def f_copy(group): + # this takes the fast apply path + names.append(group.name) + return group.copy() + + def f_nocopy(group): + # this takes the slow apply path + names.append(group.name) + return group + + def f_scalar(group): + # GH7739, GH2656 + names.append(group.name) + return 0 + + def f_none(group): + # GH10519, GH12155, GH21417 + names.append(group.name) + + def f_constant_df(group): + # GH2936, GH20084 + names.append(group.name) + return DataFrame({"a": [1], "b": [1]}) + + for func in [f_copy, f_nocopy, f_scalar, f_none, f_constant_df]: + del names[:] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby("a", group_keys=False).apply(func) + assert names == group_names + + +def test_group_apply_once_per_group2(capsys): + # GH: 31111 + # groupby-apply need to execute len(set(group_by_columns)) times + + expected = 2 # Number of times `apply` should call a function for the current test + + df = DataFrame( + { + "group_by_column": [0, 0, 0, 0, 1, 1, 1, 1], + "test_column": ["0", "2", "4", "6", "8", "10", "12", "14"], + }, + index=["0", "2", "4", "6", "8", "10", "12", "14"], + ) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby("group_by_column", group_keys=False).apply( + lambda df: print("function_called") + ) + + result = capsys.readouterr().out.count("function_called") + # If `groupby` behaves unexpectedly, this test will break + assert result == expected + + +def test_apply_fast_slow_identical(): + # GH 31613 + + df = DataFrame({"A": [0, 0, 1], "b": range(3)}) + + # For simple index structures we check for fast/slow apply using + # an identity check on in/output + def slow(group): + return group + + def fast(group): + return group.copy() + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + fast_df = df.groupby("A", group_keys=False).apply(fast) + with tm.assert_produces_warning(FutureWarning, match=msg): + slow_df = df.groupby("A", group_keys=False).apply(slow) + + tm.assert_frame_equal(fast_df, slow_df) + + +@pytest.mark.parametrize( + "func", + [ + lambda x: x, + lambda x: x[:], + lambda x: x.copy(deep=False), + lambda x: x.copy(deep=True), + ], +) +def test_groupby_apply_identity_maybecopy_index_identical(func): + # GH 14927 + # Whether the function returns a copy of the input data or not should not + # have an impact on the index structure of the result since this is not + # transparent to the user + + df = DataFrame({"g": [1, 2, 2, 2], "a": [1, 2, 3, 4], "b": [5, 6, 7, 8]}) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("g", group_keys=False).apply(func) + tm.assert_frame_equal(result, df) + + +def test_apply_with_mixed_dtype(): + # GH3480, apply with mixed dtype on axis=1 breaks in 0.11 + df = DataFrame( + { + "foo1": np.random.default_rng(2).standard_normal(6), + "foo2": ["one", "two", "two", "three", "one", "two"], + } + ) + result = df.apply(lambda x: x, axis=1).dtypes + expected = df.dtypes + tm.assert_series_equal(result, expected) + + # GH 3610 incorrect dtype conversion with as_index=False + df = DataFrame({"c1": [1, 2, 6, 6, 8]}) + df["c2"] = df.c1 / 2.0 + result1 = df.groupby("c2").mean().reset_index().c2 + result2 = df.groupby("c2", as_index=False).mean().c2 + tm.assert_series_equal(result1, result2) + + +def test_groupby_as_index_apply(): + # GH #4648 and #3417 + df = DataFrame( + { + "item_id": ["b", "b", "a", "c", "a", "b"], + "user_id": [1, 2, 1, 1, 3, 1], + "time": range(6), + } + ) + + g_as = df.groupby("user_id", as_index=True) + g_not_as = df.groupby("user_id", as_index=False) + + res_as = g_as.head(2).index + res_not_as = g_not_as.head(2).index + exp = Index([0, 1, 2, 4]) + tm.assert_index_equal(res_as, exp) + tm.assert_index_equal(res_not_as, exp) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + res_as_apply = g_as.apply(lambda x: x.head(2)).index + with tm.assert_produces_warning(FutureWarning, match=msg): + res_not_as_apply = g_not_as.apply(lambda x: x.head(2)).index + + # apply doesn't maintain the original ordering + # changed in GH5610 as the as_index=False returns a MI here + exp_not_as_apply = MultiIndex.from_tuples([(0, 0), (0, 2), (1, 1), (2, 4)]) + tp = [(1, 0), (1, 2), (2, 1), (3, 4)] + exp_as_apply = MultiIndex.from_tuples(tp, names=["user_id", None]) + + tm.assert_index_equal(res_as_apply, exp_as_apply) + tm.assert_index_equal(res_not_as_apply, exp_not_as_apply) + + ind = Index(list("abcde")) + df = DataFrame([[1, 2], [2, 3], [1, 4], [1, 5], [2, 6]], index=ind) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = df.groupby(0, as_index=False, group_keys=False).apply(lambda x: x).index + tm.assert_index_equal(res, ind) + + +def test_apply_concat_preserve_names(three_group): + grouped = three_group.groupby(["A", "B"]) + + def desc(group): + result = group.describe() + result.index.name = "stat" + return result + + def desc2(group): + result = group.describe() + result.index.name = "stat" + result = result[: len(group)] + # weirdo + return result + + def desc3(group): + result = group.describe() + + # names are different + result.index.name = f"stat_{len(group):d}" + + result = result[: len(group)] + # weirdo + return result + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = grouped.apply(desc) + assert result.index.names == ("A", "B", "stat") + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result2 = grouped.apply(desc2) + assert result2.index.names == ("A", "B", "stat") + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result3 = grouped.apply(desc3) + assert result3.index.names == ("A", "B", None) + + +def test_apply_series_to_frame(): + def f(piece): + with np.errstate(invalid="ignore"): + logged = np.log(piece) + return DataFrame( + {"value": piece, "demeaned": piece - piece.mean(), "logged": logged} + ) + + dr = bdate_range("1/1/2000", periods=100) + ts = Series(np.random.default_rng(2).standard_normal(100), index=dr) + + grouped = ts.groupby(lambda x: x.month, group_keys=False) + result = grouped.apply(f) + + assert isinstance(result, DataFrame) + assert not hasattr(result, "name") # GH49907 + tm.assert_index_equal(result.index, ts.index) + + +def test_apply_series_yield_constant(df): + result = df.groupby(["A", "B"])["C"].apply(len) + assert result.index.names[:2] == ("A", "B") + + +def test_apply_frame_yield_constant(df): + # GH13568 + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(["A", "B"]).apply(len) + assert isinstance(result, Series) + assert result.name is None + + result = df.groupby(["A", "B"])[["C", "D"]].apply(len) + assert isinstance(result, Series) + assert result.name is None + + +def test_apply_frame_to_series(df): + grouped = df.groupby(["A", "B"]) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = grouped.apply(len) + expected = grouped.count()["C"] + tm.assert_index_equal(result.index, expected.index) + tm.assert_numpy_array_equal(result.values, expected.values) + + +def test_apply_frame_not_as_index_column_name(df): + # GH 35964 - path within _wrap_applied_output not hit by a test + grouped = df.groupby(["A", "B"], as_index=False) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = grouped.apply(len) + expected = grouped.count().rename(columns={"C": np.nan}).drop(columns="D") + # TODO(GH#34306): Use assert_frame_equal when column name is not np.nan + tm.assert_index_equal(result.index, expected.index) + tm.assert_numpy_array_equal(result.values, expected.values) + + +def test_apply_frame_concat_series(): + def trans(group): + return group.groupby("B")["C"].sum().sort_values().iloc[:2] + + def trans2(group): + grouped = group.groupby(df.reindex(group.index)["B"]) + return grouped.sum().sort_values().iloc[:2] + + df = DataFrame( + { + "A": np.random.default_rng(2).integers(0, 5, 1000), + "B": np.random.default_rng(2).integers(0, 5, 1000), + "C": np.random.default_rng(2).standard_normal(1000), + } + ) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(trans) + exp = df.groupby("A")["C"].apply(trans2) + tm.assert_series_equal(result, exp, check_names=False) + assert result.name == "C" + + +def test_apply_transform(ts): + grouped = ts.groupby(lambda x: x.month, group_keys=False) + result = grouped.apply(lambda x: x * 2) + expected = grouped.transform(lambda x: x * 2) + tm.assert_series_equal(result, expected) + + +def test_apply_multikey_corner(tsframe): + grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month]) + + def f(group): + return group.sort_values("A")[-5:] + + result = grouped.apply(f) + for key, group in grouped: + tm.assert_frame_equal(result.loc[key], f(group)) + + +@pytest.mark.parametrize("group_keys", [True, False]) +def test_apply_chunk_view(group_keys): + # Low level tinkering could be unsafe, make sure not + df = DataFrame({"key": [1, 1, 1, 2, 2, 2, 3, 3, 3], "value": range(9)}) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("key", group_keys=group_keys).apply(lambda x: x.iloc[:2]) + expected = df.take([0, 1, 3, 4, 6, 7]) + if group_keys: + expected.index = MultiIndex.from_arrays( + [[1, 1, 2, 2, 3, 3], expected.index], names=["key", None] + ) + + tm.assert_frame_equal(result, expected) + + +def test_apply_no_name_column_conflict(): + df = DataFrame( + { + "name": [1, 1, 1, 1, 1, 1, 2, 2, 2, 2], + "name2": [0, 0, 0, 1, 1, 1, 0, 0, 1, 1], + "value": range(9, -1, -1), + } + ) + + # it works! #2605 + grouped = df.groupby(["name", "name2"]) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped.apply(lambda x: x.sort_values("value", inplace=True)) + + +def test_apply_typecast_fail(): + df = DataFrame( + { + "d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], + "c": np.tile(["a", "b", "c"], 2), + "v": np.arange(1.0, 7.0), + } + ) + + def f(group): + v = group["v"] + group["v2"] = (v - v.min()) / (v.max() - v.min()) + return group + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("d", group_keys=False).apply(f) + + expected = df.copy() + expected["v2"] = np.tile([0.0, 0.5, 1], 2) + + tm.assert_frame_equal(result, expected) + + +def test_apply_multiindex_fail(): + index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]]) + df = DataFrame( + { + "d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], + "c": np.tile(["a", "b", "c"], 2), + "v": np.arange(1.0, 7.0), + }, + index=index, + ) + + def f(group): + v = group["v"] + group["v2"] = (v - v.min()) / (v.max() - v.min()) + return group + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("d", group_keys=False).apply(f) + + expected = df.copy() + expected["v2"] = np.tile([0.0, 0.5, 1], 2) + + tm.assert_frame_equal(result, expected) + + +def test_apply_corner(tsframe): + result = tsframe.groupby(lambda x: x.year, group_keys=False).apply(lambda x: x * 2) + expected = tsframe * 2 + tm.assert_frame_equal(result, expected) + + +def test_apply_without_copy(): + # GH 5545 + # returning a non-copy in an applied function fails + + data = DataFrame( + { + "id_field": [100, 100, 200, 300], + "category": ["a", "b", "c", "c"], + "value": [1, 2, 3, 4], + } + ) + + def filt1(x): + if x.shape[0] == 1: + return x.copy() + else: + return x[x.category == "c"] + + def filt2(x): + if x.shape[0] == 1: + return x + else: + return x[x.category == "c"] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = data.groupby("id_field").apply(filt1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = data.groupby("id_field").apply(filt2) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("test_series", [True, False]) +def test_apply_with_duplicated_non_sorted_axis(test_series): + # GH 30667 + df = DataFrame( + [["x", "p"], ["x", "p"], ["x", "o"]], columns=["X", "Y"], index=[1, 2, 2] + ) + if test_series: + ser = df.set_index("Y")["X"] + result = ser.groupby(level=0, group_keys=False).apply(lambda x: x) + + # not expecting the order to remain the same for duplicated axis + result = result.sort_index() + expected = ser.sort_index() + tm.assert_series_equal(result, expected) + else: + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("Y", group_keys=False).apply(lambda x: x) + + # not expecting the order to remain the same for duplicated axis + result = result.sort_values("Y") + expected = df.sort_values("Y") + tm.assert_frame_equal(result, expected) + + +def test_apply_reindex_values(): + # GH: 26209 + # reindexing from a single column of a groupby object with duplicate indices caused + # a ValueError (cannot reindex from duplicate axis) in 0.24.2, the problem was + # solved in #30679 + values = [1, 2, 3, 4] + indices = [1, 1, 2, 2] + df = DataFrame({"group": ["Group1", "Group2"] * 2, "value": values}, index=indices) + expected = Series(values, index=indices, name="value") + + def reindex_helper(x): + return x.reindex(np.arange(x.index.min(), x.index.max() + 1)) + + # the following group by raised a ValueError + result = df.groupby("group", group_keys=False).value.apply(reindex_helper) + tm.assert_series_equal(expected, result) + + +def test_apply_corner_cases(): + # #535, can't use sliding iterator + + N = 1000 + labels = np.random.default_rng(2).integers(0, 100, size=N) + df = DataFrame( + { + "key": labels, + "value1": np.random.default_rng(2).standard_normal(N), + "value2": ["foo", "bar", "baz", "qux"] * (N // 4), + } + ) + + grouped = df.groupby("key", group_keys=False) + + def f(g): + g["value3"] = g["value1"] * 2 + return g + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = grouped.apply(f) + assert "value3" in result + + +def test_apply_numeric_coercion_when_datetime(): + # In the past, group-by/apply operations have been over-eager + # in converting dtypes to numeric, in the presence of datetime + # columns. Various GH issues were filed, the reproductions + # for which are here. + + # GH 15670 + df = DataFrame( + {"Number": [1, 2], "Date": ["2017-03-02"] * 2, "Str": ["foo", "inf"]} + ) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.groupby(["Number"]).apply(lambda x: x.iloc[0]) + df.Date = pd.to_datetime(df.Date) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(["Number"]).apply(lambda x: x.iloc[0]) + tm.assert_series_equal(result["Str"], expected["Str"]) + + # GH 15421 + df = DataFrame( + {"A": [10, 20, 30], "B": ["foo", "3", "4"], "T": [pd.Timestamp("12:31:22")] * 3} + ) + + def get_B(g): + return g.iloc[0][["B"]] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(get_B)["B"] + expected = df.B + expected.index = df.A + tm.assert_series_equal(result, expected) + + # GH 14423 + def predictions(tool): + out = Series(index=["p1", "p2", "useTime"], dtype=object) + if "step1" in list(tool.State): + out["p1"] = str(tool[tool.State == "step1"].Machine.values[0]) + if "step2" in list(tool.State): + out["p2"] = str(tool[tool.State == "step2"].Machine.values[0]) + out["useTime"] = str(tool[tool.State == "step2"].oTime.values[0]) + return out + + df1 = DataFrame( + { + "Key": ["B", "B", "A", "A"], + "State": ["step1", "step2", "step1", "step2"], + "oTime": ["", "2016-09-19 05:24:33", "", "2016-09-19 23:59:04"], + "Machine": ["23", "36L", "36R", "36R"], + } + ) + df2 = df1.copy() + df2.oTime = pd.to_datetime(df2.oTime) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df1.groupby("Key").apply(predictions).p1 + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df2.groupby("Key").apply(predictions).p1 + tm.assert_series_equal(expected, result) + + +def test_apply_aggregating_timedelta_and_datetime(): + # Regression test for GH 15562 + # The following groupby caused ValueErrors and IndexErrors pre 0.20.0 + + df = DataFrame( + { + "clientid": ["A", "B", "C"], + "datetime": [np.datetime64("2017-02-01 00:00:00")] * 3, + } + ) + df["time_delta_zero"] = df.datetime - df.datetime + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("clientid").apply( + lambda ddf: Series( + {"clientid_age": ddf.time_delta_zero.min(), "date": ddf.datetime.min()} + ) + ) + expected = DataFrame( + { + "clientid": ["A", "B", "C"], + "clientid_age": [np.timedelta64(0, "D")] * 3, + "date": [np.datetime64("2017-02-01 00:00:00")] * 3, + } + ).set_index("clientid") + + tm.assert_frame_equal(result, expected) + + +def test_apply_groupby_datetimeindex(): + # GH 26182 + # groupby apply failed on dataframe with DatetimeIndex + + data = [["A", 10], ["B", 20], ["B", 30], ["C", 40], ["C", 50]] + df = DataFrame( + data, columns=["Name", "Value"], index=pd.date_range("2020-09-01", "2020-09-05") + ) + + result = df.groupby("Name").sum() + + expected = DataFrame({"Name": ["A", "B", "C"], "Value": [10, 50, 90]}) + expected.set_index("Name", inplace=True) + + tm.assert_frame_equal(result, expected) + + +def test_time_field_bug(): + # Test a fix for the following error related to GH issue 11324 When + # non-key fields in a group-by dataframe contained time-based fields + # that were not returned by the apply function, an exception would be + # raised. + + df = DataFrame({"a": 1, "b": [datetime.now() for nn in range(10)]}) + + def func_with_no_date(batch): + return Series({"c": 2}) + + def func_with_date(batch): + return Series({"b": datetime(2015, 1, 1), "c": 2}) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + dfg_no_conversion = df.groupby(by=["a"]).apply(func_with_no_date) + dfg_no_conversion_expected = DataFrame({"c": 2}, index=[1]) + dfg_no_conversion_expected.index.name = "a" + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + dfg_conversion = df.groupby(by=["a"]).apply(func_with_date) + dfg_conversion_expected = DataFrame( + {"b": pd.Timestamp(2015, 1, 1).as_unit("ns"), "c": 2}, index=[1] + ) + dfg_conversion_expected.index.name = "a" + + tm.assert_frame_equal(dfg_no_conversion, dfg_no_conversion_expected) + tm.assert_frame_equal(dfg_conversion, dfg_conversion_expected) + + +def test_gb_apply_list_of_unequal_len_arrays(): + # GH1738 + df = DataFrame( + { + "group1": ["a", "a", "a", "b", "b", "b", "a", "a", "a", "b", "b", "b"], + "group2": ["c", "c", "d", "d", "d", "e", "c", "c", "d", "d", "d", "e"], + "weight": [1.1, 2, 3, 4, 5, 6, 2, 4, 6, 8, 1, 2], + "value": [7.1, 8, 9, 10, 11, 12, 8, 7, 6, 5, 4, 3], + } + ) + df = df.set_index(["group1", "group2"]) + df_grouped = df.groupby(level=["group1", "group2"], sort=True) + + def noddy(value, weight): + out = np.array(value * weight).repeat(3) + return out + + # the kernel function returns arrays of unequal length + # pandas sniffs the first one, sees it's an array and not + # a list, and assumed the rest are of equal length + # and so tries a vstack + + # don't die + df_grouped.apply(lambda x: noddy(x.value, x.weight)) + + +def test_groupby_apply_all_none(): + # Tests to make sure no errors if apply function returns all None + # values. Issue 9684. + test_df = DataFrame({"groups": [0, 0, 1, 1], "random_vars": [8, 7, 4, 5]}) + + def test_func(x): + pass + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = test_df.groupby("groups").apply(test_func) + expected = DataFrame() + tm.assert_frame_equal(result, expected) + + +def test_groupby_apply_none_first(): + # GH 12824. Tests if apply returns None first. + test_df1 = DataFrame({"groups": [1, 1, 1, 2], "vars": [0, 1, 2, 3]}) + test_df2 = DataFrame({"groups": [1, 2, 2, 2], "vars": [0, 1, 2, 3]}) + + def test_func(x): + if x.shape[0] < 2: + return None + return x.iloc[[0, -1]] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result1 = test_df1.groupby("groups").apply(test_func) + with tm.assert_produces_warning(FutureWarning, match=msg): + result2 = test_df2.groupby("groups").apply(test_func) + index1 = MultiIndex.from_arrays([[1, 1], [0, 2]], names=["groups", None]) + index2 = MultiIndex.from_arrays([[2, 2], [1, 3]], names=["groups", None]) + expected1 = DataFrame({"groups": [1, 1], "vars": [0, 2]}, index=index1) + expected2 = DataFrame({"groups": [2, 2], "vars": [1, 3]}, index=index2) + tm.assert_frame_equal(result1, expected1) + tm.assert_frame_equal(result2, expected2) + + +def test_groupby_apply_return_empty_chunk(): + # GH 22221: apply filter which returns some empty groups + df = DataFrame({"value": [0, 1], "group": ["filled", "empty"]}) + groups = df.groupby("group") + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = groups.apply(lambda group: group[group.value != 1]["value"]) + expected = Series( + [0], + name="value", + index=MultiIndex.from_product( + [["empty", "filled"], [0]], names=["group", None] + ).drop("empty"), + ) + tm.assert_series_equal(result, expected) + + +def test_apply_with_mixed_types(): + # gh-20949 + df = DataFrame({"A": "a a b".split(), "B": [1, 2, 3], "C": [4, 6, 5]}) + g = df.groupby("A", group_keys=False) + + result = g.transform(lambda x: x / x.sum()) + expected = DataFrame({"B": [1 / 3.0, 2 / 3.0, 1], "C": [0.4, 0.6, 1.0]}) + tm.assert_frame_equal(result, expected) + + result = g.apply(lambda x: x / x.sum()) + tm.assert_frame_equal(result, expected) + + +def test_func_returns_object(): + # GH 28652 + df = DataFrame({"a": [1, 2]}, index=Index([1, 2])) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("a").apply(lambda g: g.index) + expected = Series([Index([1]), Index([2])], index=Index([1, 2], name="a")) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "group_column_dtlike", + [datetime.today(), datetime.today().date(), datetime.today().time()], +) +def test_apply_datetime_issue(group_column_dtlike): + # GH-28247 + # groupby-apply throws an error if one of the columns in the DataFrame + # is a datetime object and the column labels are different from + # standard int values in range(len(num_columns)) + + df = DataFrame({"a": ["foo"], "b": [group_column_dtlike]}) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("a").apply(lambda x: Series(["spam"], index=[42])) + + expected = DataFrame(["spam"], Index(["foo"], dtype="str", name="a"), columns=[42]) + tm.assert_frame_equal(result, expected) + + +def test_apply_series_return_dataframe_groups(): + # GH 10078 + tdf = DataFrame( + { + "day": { + 0: pd.Timestamp("2015-02-24 00:00:00"), + 1: pd.Timestamp("2015-02-24 00:00:00"), + 2: pd.Timestamp("2015-02-24 00:00:00"), + 3: pd.Timestamp("2015-02-24 00:00:00"), + 4: pd.Timestamp("2015-02-24 00:00:00"), + }, + "userAgent": { + 0: "some UA string", + 1: "some UA string", + 2: "some UA string", + 3: "another UA string", + 4: "some UA string", + }, + "userId": { + 0: "17661101", + 1: "17661101", + 2: "17661101", + 3: "17661101", + 4: "17661101", + }, + } + ) + + def most_common_values(df): + return Series({c: s.value_counts().index[0] for c, s in df.items()}) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = tdf.groupby("day").apply(most_common_values)["userId"] + expected = Series( + ["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId" + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("category", [False, True]) +def test_apply_multi_level_name(category): + # https://github.com/pandas-dev/pandas/issues/31068 + b = [1, 2] * 5 + if category: + b = pd.Categorical(b, categories=[1, 2, 3]) + expected_index = pd.CategoricalIndex([1, 2, 3], categories=[1, 2, 3], name="B") + expected_values = [20, 25, 0] + else: + expected_index = Index([1, 2], name="B") + expected_values = [20, 25] + expected = DataFrame( + {"C": expected_values, "D": expected_values}, index=expected_index + ) + + df = DataFrame( + {"A": np.arange(10), "B": b, "C": list(range(10)), "D": list(range(10))} + ).set_index(["A", "B"]) + result = df.groupby("B", observed=False).apply(lambda x: x.sum()) + tm.assert_frame_equal(result, expected) + assert df.index.names == ["A", "B"] + + +def test_groupby_apply_datetime_result_dtypes(using_infer_string): + # GH 14849 + data = DataFrame.from_records( + [ + (pd.Timestamp(2016, 1, 1), "red", "dark", 1, "8"), + (pd.Timestamp(2015, 1, 1), "green", "stormy", 2, "9"), + (pd.Timestamp(2014, 1, 1), "blue", "bright", 3, "10"), + (pd.Timestamp(2013, 1, 1), "blue", "calm", 4, "potato"), + ], + columns=["observation", "color", "mood", "intensity", "score"], + ) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = data.groupby("color").apply(lambda g: g.iloc[0]).dtypes + dtype = pd.StringDtype(na_value=np.nan) if using_infer_string else object + expected = Series( + [np.dtype("datetime64[ns]"), dtype, dtype, np.int64, dtype], + index=["observation", "color", "mood", "intensity", "score"], + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "index", + [ + pd.CategoricalIndex(list("abc")), + pd.interval_range(0, 3), + pd.period_range("2020", periods=3, freq="D"), + MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]), + ], +) +def test_apply_index_has_complex_internals(index): + # GH 31248 + df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("group", group_keys=False).apply(lambda x: x) + tm.assert_frame_equal(result, df) + + +@pytest.mark.parametrize( + "function, expected_values", + [ + (lambda x: x.index.to_list(), [[0, 1], [2, 3]]), + (lambda x: set(x.index.to_list()), [{0, 1}, {2, 3}]), + (lambda x: tuple(x.index.to_list()), [(0, 1), (2, 3)]), + ( + lambda x: dict(enumerate(x.index.to_list())), + [{0: 0, 1: 1}, {0: 2, 1: 3}], + ), + ( + lambda x: [{n: i} for (n, i) in enumerate(x.index.to_list())], + [[{0: 0}, {1: 1}], [{0: 2}, {1: 3}]], + ), + ], +) +def test_apply_function_returns_non_pandas_non_scalar(function, expected_values): + # GH 31441 + df = DataFrame(["A", "A", "B", "B"], columns=["groups"]) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("groups").apply(function) + expected = Series(expected_values, index=Index(["A", "B"], name="groups")) + tm.assert_series_equal(result, expected) + + +def test_apply_function_returns_numpy_array(): + # GH 31605 + def fct(group): + return group["B"].values.flatten() + + df = DataFrame({"A": ["a", "a", "b", "none"], "B": [1, 2, 3, np.nan]}) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(fct) + expected = Series( + [[1.0, 2.0], [3.0], [np.nan]], index=Index(["a", "b", "none"], name="A") + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("function", [lambda gr: gr.index, lambda gr: gr.index + 1 - 1]) +def test_apply_function_index_return(function): + # GH: 22541 + df = DataFrame([1, 2, 2, 2, 1, 2, 3, 1, 3, 1], columns=["id"]) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("id").apply(function) + expected = Series( + [Index([0, 4, 7, 9]), Index([1, 2, 3, 5]), Index([6, 8])], + index=Index([1, 2, 3], name="id"), + ) + tm.assert_series_equal(result, expected) + + +def test_apply_function_with_indexing_return_column(): + # GH#7002, GH#41480, GH#49256 + df = DataFrame( + { + "foo1": ["one", "two", "two", "three", "one", "two"], + "foo2": [1, 2, 4, 4, 5, 6], + } + ) + result = df.groupby("foo1", as_index=False).apply(lambda x: x.mean()) + expected = DataFrame( + { + "foo1": ["one", "three", "two"], + "foo2": [3.0, 4.0, 4.0], + } + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "udf", + [(lambda x: x.copy()), (lambda x: x.copy().rename(lambda y: y + 1))], +) +@pytest.mark.parametrize("group_keys", [True, False]) +def test_apply_result_type(group_keys, udf): + # https://github.com/pandas-dev/pandas/issues/34809 + # We'd like to control whether the group keys end up in the index + # regardless of whether the UDF happens to be a transform. + df = DataFrame({"A": ["a", "b"], "B": [1, 2]}) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + df_result = df.groupby("A", group_keys=group_keys).apply(udf) + series_result = df.B.groupby(df.A, group_keys=group_keys).apply(udf) + + if group_keys: + assert df_result.index.nlevels == 2 + assert series_result.index.nlevels == 2 + else: + assert df_result.index.nlevels == 1 + assert series_result.index.nlevels == 1 + + +def test_result_order_group_keys_false(): + # GH 34998 + # apply result order should not depend on whether index is the same or just equal + df = DataFrame({"A": [2, 1, 2], "B": [1, 2, 3]}) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A", group_keys=False).apply(lambda x: x) + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.groupby("A", group_keys=False).apply(lambda x: x.copy()) + tm.assert_frame_equal(result, expected) + + +def test_apply_with_timezones_aware(): + # GH: 27212 + dates = ["2001-01-01"] * 2 + ["2001-01-02"] * 2 + ["2001-01-03"] * 2 + index_no_tz = pd.DatetimeIndex(dates) + index_tz = pd.DatetimeIndex(dates, tz="UTC") + df1 = DataFrame({"x": list(range(2)) * 3, "y": range(6), "t": index_no_tz}) + df2 = DataFrame({"x": list(range(2)) * 3, "y": range(6), "t": index_tz}) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result1 = df1.groupby("x", group_keys=False).apply( + lambda df: df[["x", "y"]].copy() + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result2 = df2.groupby("x", group_keys=False).apply( + lambda df: df[["x", "y"]].copy() + ) + + tm.assert_frame_equal(result1, result2) + + +def test_apply_is_unchanged_when_other_methods_are_called_first(reduction_func): + # GH #34656 + # GH #34271 + df = DataFrame( + { + "a": [99, 99, 99, 88, 88, 88], + "b": [1, 2, 3, 4, 5, 6], + "c": [10, 20, 30, 40, 50, 60], + } + ) + + expected = DataFrame( + {"b": [15, 6], "c": [150, 60]}, + index=Index([88, 99], name="a"), + ) + + # Check output when no other methods are called before .apply() + grp = df.groupby(by="a") + msg = "The behavior of DataFrame.sum with axis=None is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): + result = grp.apply(sum, include_groups=False) + tm.assert_frame_equal(result, expected) + + # Check output when another method is called before .apply() + grp = df.groupby(by="a") + args = get_groupby_method_args(reduction_func, df) + _ = getattr(grp, reduction_func)(*args) + with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): + result = grp.apply(sum, include_groups=False) + tm.assert_frame_equal(result, expected) + + +def test_apply_with_date_in_multiindex_does_not_convert_to_timestamp(): + # GH 29617 + + df = DataFrame( + { + "A": ["a", "a", "a", "b"], + "B": [ + date(2020, 1, 10), + date(2020, 1, 10), + date(2020, 2, 10), + date(2020, 2, 10), + ], + "C": [1, 2, 3, 4], + }, + index=Index([100, 101, 102, 103], name="idx"), + ) + + grp = df.groupby(["A", "B"]) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = grp.apply(lambda x: x.head(1)) + + expected = df.iloc[[0, 2, 3]] + expected = expected.reset_index() + expected.index = MultiIndex.from_frame(expected[["A", "B", "idx"]]) + expected = expected.drop(columns="idx") + + tm.assert_frame_equal(result, expected) + for val in result.index.levels[1]: + assert type(val) is date + + +def test_apply_by_cols_equals_apply_by_rows_transposed(): + # GH 16646 + # Operating on the columns, or transposing and operating on the rows + # should give the same result. There was previously a bug where the + # by_rows operation would work fine, but by_cols would throw a ValueError + + df = DataFrame( + np.random.default_rng(2).random([6, 4]), + columns=MultiIndex.from_product([["A", "B"], [1, 2]]), + ) + + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.T.groupby(axis=0, level=0) + by_rows = gb.apply(lambda x: x.droplevel(axis=0, level=0)) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df.groupby(axis=1, level=0) + by_cols = gb2.apply(lambda x: x.droplevel(axis=1, level=0)) + + tm.assert_frame_equal(by_cols, by_rows.T) + tm.assert_frame_equal(by_cols, df) + + +@pytest.mark.parametrize("dropna", [True, False]) +def test_apply_dropna_with_indexed_same(dropna): + # GH 38227 + # GH#43205 + df = DataFrame( + { + "col": [1, 2, 3, 4, 5], + "group": ["a", np.nan, np.nan, "b", "b"], + }, + index=list("xxyxz"), + ) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("group", dropna=dropna, group_keys=False).apply(lambda x: x) + expected = df.dropna() if dropna else df.iloc[[0, 3, 1, 2, 4]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "as_index, expected", + [ + pytest.param( + False, + DataFrame( + [[1, 1, 1], [2, 2, 1]], columns=Index(["a", "b", None], dtype=object) + ), + marks=pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)"), + ), + [ + True, + Series( + [1, 1], index=MultiIndex.from_tuples([(1, 1), (2, 2)], names=["a", "b"]) + ), + ], + ], +) +def test_apply_as_index_constant_lambda(as_index, expected): + # GH 13217 + df = DataFrame({"a": [1, 1, 2, 2], "b": [1, 1, 2, 2], "c": [1, 1, 1, 1]}) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(["a", "b"], as_index=as_index).apply(lambda x: 1) + tm.assert_equal(result, expected) + + +def test_sort_index_groups(): + # GH 20420 + df = DataFrame( + {"A": [1, 2, 3, 4, 5], "B": [6, 7, 8, 9, 0], "C": [1, 1, 1, 2, 2]}, + index=range(5), + ) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("C").apply(lambda x: x.A.sort_index()) + expected = Series( + range(1, 6), + index=MultiIndex.from_tuples( + [(1, 0), (1, 1), (1, 2), (2, 3), (2, 4)], names=["C", None] + ), + name="A", + ) + tm.assert_series_equal(result, expected) + + +def test_positional_slice_groups_datetimelike(): + # GH 21651 + expected = DataFrame( + { + "date": pd.date_range("2010-01-01", freq="12h", periods=5), + "vals": range(5), + "let": list("abcde"), + } + ) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = expected.groupby( + [expected.let, expected.date.dt.date], group_keys=False + ).apply(lambda x: x.iloc[0:]) + tm.assert_frame_equal(result, expected) + + +def test_groupby_apply_shape_cache_safety(): + # GH#42702 this fails if we cache_readonly Block.shape + df = DataFrame({"A": ["a", "a", "b"], "B": [1, 2, 3], "C": [4, 6, 5]}) + gb = df.groupby("A") + result = gb[["B", "C"]].apply(lambda x: x.astype(float).max() - x.min()) + + expected = DataFrame( + {"B": [1.0, 0.0], "C": [2.0, 0.0]}, index=Index(["a", "b"], name="A") + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_apply_to_series_name(): + # GH52444 + df = DataFrame.from_dict( + { + "a": ["a", "b", "a", "b"], + "b1": ["aa", "ac", "ac", "ad"], + "b2": ["aa", "aa", "aa", "ac"], + } + ) + grp = df.groupby("a")[["b1", "b2"]] + result = grp.apply(lambda x: x.unstack().value_counts()) + + expected_idx = MultiIndex.from_arrays( + arrays=[["a", "a", "b", "b", "b"], ["aa", "ac", "ac", "ad", "aa"]], + names=["a", None], + ) + expected = Series([3, 1, 2, 1, 1], index=expected_idx, name="count") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("dropna", [True, False]) +def test_apply_na(dropna): + # GH#28984 + df = DataFrame( + {"grp": [1, 1, 2, 2], "y": [1, 0, 2, 5], "z": [1, 2, np.nan, np.nan]} + ) + dfgrp = df.groupby("grp", dropna=dropna) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = dfgrp.apply(lambda grp_df: grp_df.nlargest(1, "z")) + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = dfgrp.apply(lambda x: x.sort_values("z", ascending=False).head(1)) + tm.assert_frame_equal(result, expected) + + +def test_apply_empty_string_nan_coerce_bug(): + # GH#24903 + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ( + DataFrame( + { + "a": [1, 1, 2, 2], + "b": ["", "", "", ""], + "c": pd.to_datetime([1, 2, 3, 4], unit="s"), + } + ) + .groupby(["a", "b"]) + .apply(lambda df: df.iloc[-1]) + ) + expected = DataFrame( + [[1, "", pd.to_datetime(2, unit="s")], [2, "", pd.to_datetime(4, unit="s")]], + columns=["a", "b", "c"], + index=MultiIndex.from_tuples([(1, ""), (2, "")], names=["a", "b"]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("index_values", [[1, 2, 3], [1.0, 2.0, 3.0]]) +def test_apply_index_key_error_bug(index_values): + # GH 44310 + result = DataFrame( + { + "a": ["aa", "a2", "a3"], + "b": [1, 2, 3], + }, + index=Index(index_values), + ) + expected = DataFrame( + { + "b_mean": [2.0, 3.0, 1.0], + }, + index=Index(["a2", "a3", "aa"], name="a"), + ) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = result.groupby("a").apply( + lambda df: Series([df["b"].mean()], index=["b_mean"]) + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "arg,idx", + [ + [ + [ + 1, + 2, + 3, + ], + [ + 0.1, + 0.3, + 0.2, + ], + ], + [ + [ + 1, + 2, + 3, + ], + [ + 0.1, + 0.2, + 0.3, + ], + ], + [ + [ + 1, + 4, + 3, + ], + [ + 0.1, + 0.4, + 0.2, + ], + ], + ], +) +def test_apply_nonmonotonic_float_index(arg, idx): + # GH 34455 + expected = DataFrame({"col": arg}, index=idx) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = expected.groupby("col", group_keys=False).apply(lambda x: x) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("args, kwargs", [([True], {}), ([], {"numeric_only": True})]) +def test_apply_str_with_args(df, args, kwargs): + # GH#46479 + gb = df.groupby("A") + result = gb.apply("sum", *args, **kwargs) + expected = gb.sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("name", ["some_name", None]) +def test_result_name_when_one_group(name): + # GH 46369 + ser = Series([1, 2], name=name) + result = ser.groupby(["a", "a"], group_keys=False).apply(lambda x: x) + expected = Series([1, 2], name=name) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "method, op", + [ + ("apply", lambda gb: gb.values[-1]), + ("apply", lambda gb: gb["b"].iloc[0]), + ("agg", "skew"), + ("agg", "prod"), + ("agg", "sum"), + ], +) +def test_empty_df(method, op): + # GH 47985 + empty_df = DataFrame({"a": [], "b": []}) + gb = empty_df.groupby("a", group_keys=True) + group = getattr(gb, "b") + + result = getattr(group, method)(op) + expected = Series( + [], name="b", dtype="float64", index=Index([], dtype="float64", name="a") + ) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("include_groups", [True, False]) +def test_include_groups(include_groups): + # GH#7155 + df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + gb = df.groupby("a") + warn = FutureWarning if include_groups else None + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(warn, match=msg): + result = gb.apply(lambda x: x.sum(), include_groups=include_groups) + expected = DataFrame({"a": [2, 2], "b": [7, 5]}, index=Index([1, 2], name="a")) + if not include_groups: + expected = expected[["b"]] + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("f", [max, min, sum]) +@pytest.mark.parametrize("keys", ["jim", ["jim", "joe"]]) # Single key # Multi-key +def test_builtins_apply(keys, f): + # see gh-8155 + rs = np.random.default_rng(2) + df = DataFrame(rs.integers(1, 7, (10, 2)), columns=["jim", "joe"]) + df["jolie"] = rs.standard_normal(10) + + gb = df.groupby(keys) + + fname = f.__name__ + + warn = None if f is not sum else FutureWarning + msg = "The behavior of DataFrame.sum with axis=None is deprecated" + with tm.assert_produces_warning( + warn, match=msg, check_stacklevel=False, raise_on_extra_warnings=False + ): + # Also warns on deprecation GH#53425 + result = gb.apply(f) + ngroups = len(df.drop_duplicates(subset=keys)) + + assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))" + assert result.shape == (ngroups, 3), assert_msg + + npfunc = lambda x: getattr(np, fname)(x, axis=0) # numpy's equivalent function + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = gb.apply(npfunc) + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected2 = gb.apply(lambda x: npfunc(x)) + tm.assert_frame_equal(result, expected2) + + if f != sum: + expected = gb.agg(fname).reset_index() + expected.set_index(keys, inplace=True, drop=False) + tm.assert_frame_equal(result, expected, check_dtype=False) + + tm.assert_series_equal(getattr(result, fname)(axis=0), getattr(df, fname)(axis=0)) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_apply_mutate.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_apply_mutate.py new file mode 100644 index 0000000000000000000000000000000000000000..130a29abf9443d5da56df80e3f3fba9169cf7100 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_apply_mutate.py @@ -0,0 +1,163 @@ +import numpy as np + +import pandas as pd +import pandas._testing as tm + + +def test_group_by_copy(): + # GH#44803 + df = pd.DataFrame( + { + "name": ["Alice", "Bob", "Carl"], + "age": [20, 21, 20], + } + ).set_index("name") + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + grp_by_same_value = df.groupby(["age"], group_keys=False).apply( + lambda group: group + ) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + grp_by_copy = df.groupby(["age"], group_keys=False).apply( + lambda group: group.copy() + ) + tm.assert_frame_equal(grp_by_same_value, grp_by_copy) + + +def test_mutate_groups(): + # GH3380 + + df = pd.DataFrame( + { + "cat1": ["a"] * 8 + ["b"] * 6, + "cat2": ["c"] * 2 + + ["d"] * 2 + + ["e"] * 2 + + ["f"] * 2 + + ["c"] * 2 + + ["d"] * 2 + + ["e"] * 2, + "cat3": [f"g{x}" for x in range(1, 15)], + "val": np.random.default_rng(2).integers(100, size=14), + } + ) + + def f_copy(x): + x = x.copy() + x["rank"] = x.val.rank(method="min") + return x.groupby("cat2")["rank"].min() + + def f_no_copy(x): + x["rank"] = x.val.rank(method="min") + return x.groupby("cat2")["rank"].min() + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + grpby_copy = df.groupby("cat1").apply(f_copy) + with tm.assert_produces_warning(FutureWarning, match=msg): + grpby_no_copy = df.groupby("cat1").apply(f_no_copy) + tm.assert_series_equal(grpby_copy, grpby_no_copy) + + +def test_no_mutate_but_looks_like(): + # GH 8467 + # first show's mutation indicator + # second does not, but should yield the same results + df = pd.DataFrame({"key": [1, 1, 1, 2, 2, 2, 3, 3, 3], "value": range(9)}) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result1 = df.groupby("key", group_keys=True).apply(lambda x: x[:].key) + with tm.assert_produces_warning(FutureWarning, match=msg): + result2 = df.groupby("key", group_keys=True).apply(lambda x: x.key) + tm.assert_series_equal(result1, result2) + + +def test_apply_function_with_indexing(warn_copy_on_write): + # GH: 33058 + df = pd.DataFrame( + {"col1": ["A", "A", "A", "B", "B", "B"], "col2": [1, 2, 3, 4, 5, 6]} + ) + + def fn(x): + x.loc[x.index[-1], "col2"] = 0 + return x.col2 + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning( + FutureWarning, match=msg, raise_on_extra_warnings=not warn_copy_on_write + ): + result = df.groupby(["col1"], as_index=False).apply(fn) + expected = pd.Series( + [1, 2, 0, 4, 5, 0], + index=pd.MultiIndex.from_tuples( + [(0, 0), (0, 1), (0, 2), (1, 3), (1, 4), (1, 5)] + ), + name="col2", + ) + tm.assert_series_equal(result, expected) + + +def test_apply_mutate_columns_multiindex(): + # GH 12652 + df = pd.DataFrame( + { + ("C", "julian"): [1, 2, 3], + ("B", "geoffrey"): [1, 2, 3], + ("A", "julian"): [1, 2, 3], + ("B", "julian"): [1, 2, 3], + ("A", "geoffrey"): [1, 2, 3], + ("C", "geoffrey"): [1, 2, 3], + }, + columns=pd.MultiIndex.from_tuples( + [ + ("A", "julian"), + ("A", "geoffrey"), + ("B", "julian"), + ("B", "geoffrey"), + ("C", "julian"), + ("C", "geoffrey"), + ] + ), + ) + + def add_column(grouped): + name = grouped.columns[0][1] + grouped["sum", name] = grouped.sum(axis=1) + return grouped + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=1, axis=1) + result = gb.apply(add_column) + expected = pd.DataFrame( + [ + [1, 1, 1, 3, 1, 1, 1, 3], + [2, 2, 2, 6, 2, 2, 2, 6], + [ + 3, + 3, + 3, + 9, + 3, + 3, + 3, + 9, + ], + ], + columns=pd.MultiIndex.from_tuples( + [ + ("geoffrey", "A", "geoffrey"), + ("geoffrey", "B", "geoffrey"), + ("geoffrey", "C", "geoffrey"), + ("geoffrey", "sum", "geoffrey"), + ("julian", "A", "julian"), + ("julian", "B", "julian"), + ("julian", "C", "julian"), + ("julian", "sum", "julian"), + ] + ), + ) + tm.assert_frame_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_bin_groupby.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_bin_groupby.py new file mode 100644 index 0000000000000000000000000000000000000000..49b2e621b7adc97947ec9d6c376a9d0f10e672fb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_bin_groupby.py @@ -0,0 +1,65 @@ +import numpy as np +import pytest + +from pandas._libs import lib +import pandas.util._test_decorators as td + +import pandas as pd +import pandas._testing as tm + + +def assert_block_lengths(x): + assert len(x) == len(x._mgr.blocks[0].mgr_locs) + return 0 + + +def cumsum_max(x): + x.cumsum().max() + return 0 + + +@pytest.mark.parametrize( + "func", + [ + cumsum_max, + pytest.param(assert_block_lengths, marks=td.skip_array_manager_invalid_test), + ], +) +def test_mgr_locs_updated(func): + # https://github.com/pandas-dev/pandas/issues/31802 + # Some operations may require creating new blocks, which requires + # valid mgr_locs + df = pd.DataFrame({"A": ["a", "a", "a"], "B": ["a", "b", "b"], "C": [1, 1, 1]}) + result = df.groupby(["A", "B"]).agg(func) + expected = pd.DataFrame( + {"C": [0, 0]}, + index=pd.MultiIndex.from_product([["a"], ["a", "b"]], names=["A", "B"]), + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "binner,closed,expected", + [ + ( + np.array([0, 3, 6, 9], dtype=np.int64), + "left", + np.array([2, 5, 6], dtype=np.int64), + ), + ( + np.array([0, 3, 6, 9], dtype=np.int64), + "right", + np.array([3, 6, 6], dtype=np.int64), + ), + (np.array([0, 3, 6], dtype=np.int64), "left", np.array([2, 5], dtype=np.int64)), + ( + np.array([0, 3, 6], dtype=np.int64), + "right", + np.array([3, 6], dtype=np.int64), + ), + ], +) +def test_generate_bins(binner, closed, expected): + values = np.array([1, 2, 3, 4, 5, 6], dtype=np.int64) + result = lib.generate_bins_dt64(values, binner, closed=closed) + tm.assert_numpy_array_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_categorical.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_categorical.py new file mode 100644 index 0000000000000000000000000000000000000000..9a442a9609b5684a6a13f2fd0184ef3444ca9288 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_categorical.py @@ -0,0 +1,2187 @@ +from datetime import datetime + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + Categorical, + CategoricalIndex, + DataFrame, + Index, + MultiIndex, + Series, + qcut, +) +import pandas._testing as tm +from pandas.api.typing import SeriesGroupBy +from pandas.tests.groupby import get_groupby_method_args + + +def cartesian_product_for_groupers(result, args, names, fill_value=np.nan): + """Reindex to a cartesian production for the groupers, + preserving the nature (Categorical) of each grouper + """ + + def f(a): + if isinstance(a, (CategoricalIndex, Categorical)): + categories = a.categories + a = Categorical.from_codes( + np.arange(len(categories)), categories=categories, ordered=a.ordered + ) + return a + + index = MultiIndex.from_product(map(f, args), names=names) + if isinstance(fill_value, dict): + # fill_value is a dict mapping column names to fill values + # -> reindex column by column (reindex itself does not support this) + res = {} + for col in result.columns: + res[col] = result[col].reindex(index, fill_value=fill_value[col]) + return DataFrame(res, index=index).sort_index() + + return result.reindex(index, fill_value=fill_value).sort_index() + + +_results_for_groupbys_with_missing_categories = { + # This maps the builtin groupby functions to their expected outputs for + # missing categories when they are called on a categorical grouper with + # observed=False. Some functions are expected to return NaN, some zero. + # These expected values can be used across several tests (i.e. they are + # the same for SeriesGroupBy and DataFrameGroupBy) but they should only be + # hardcoded in one place. + "all": np.nan, + "any": np.nan, + "count": 0, + "corrwith": np.nan, + "first": np.nan, + "idxmax": np.nan, + "idxmin": np.nan, + "last": np.nan, + "max": np.nan, + "mean": np.nan, + "median": np.nan, + "min": np.nan, + "nth": np.nan, + "nunique": 0, + "prod": np.nan, + "quantile": np.nan, + "sem": np.nan, + "size": 0, + "skew": np.nan, + "std": np.nan, + "sum": 0, + "var": np.nan, +} + + +@pytest.mark.filterwarnings("ignore:invalid value encountered in cast:RuntimeWarning") +def test_apply_use_categorical_name(df): + cats = qcut(df.C, 4) + + def get_stats(group): + return { + "min": group.min(), + "max": group.max(), + "count": group.count(), + "mean": group.mean(), + } + + result = df.groupby(cats, observed=False).D.apply(get_stats) + assert result.index.names[0] == "C" + + +def test_basic(using_infer_string): # TODO: split this test + cats = Categorical( + ["a", "a", "a", "b", "b", "b", "c", "c", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats}) + + exp_index = CategoricalIndex(list("abcd"), name="b", ordered=True) + expected = DataFrame({"a": [1, 2, 4, np.nan]}, index=exp_index) + result = data.groupby("b", observed=False).mean() + tm.assert_frame_equal(result, expected) + + cat1 = Categorical(["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True) + cat2 = Categorical(["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + + # single grouper + gb = df.groupby("A", observed=False) + exp_idx = CategoricalIndex(["a", "b", "z"], name="A", ordered=True) + expected = DataFrame({"values": Series([3, 7, 0], index=exp_idx)}) + result = gb.sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + # GH 8623 + x = DataFrame( + [[1, "John P. Doe"], [2, "Jane Dove"], [1, "John P. Doe"]], + columns=["person_id", "person_name"], + ) + x["person_name"] = Categorical(x.person_name) + + g = x.groupby(["person_id"], observed=False) + result = g.transform(lambda x: x) + tm.assert_frame_equal(result, x[["person_name"]]) + + result = x.drop_duplicates("person_name") + expected = x.iloc[[0, 1]] + tm.assert_frame_equal(result, expected) + + def f(x): + return x.drop_duplicates("person_name").iloc[0] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = g.apply(f) + expected = x.iloc[[0, 1]].copy() + expected.index = Index([1, 2], name="person_id") + dtype = "str" if using_infer_string else object + expected["person_name"] = expected["person_name"].astype(dtype) + tm.assert_frame_equal(result, expected) + + # GH 9921 + # Monotonic + df = DataFrame({"a": [5, 15, 25]}) + c = pd.cut(df.a, bins=[0, 10, 20, 30, 40]) + + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.a.groupby(c, observed=False).transform(sum) + tm.assert_series_equal(result, df["a"]) + + tm.assert_series_equal( + df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"] + ) + msg = "using DataFrameGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.groupby(c, observed=False).transform(sum) + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + gbc = df.groupby(c, observed=False) + result = gbc.transform(lambda xs: np.max(xs, axis=0)) + tm.assert_frame_equal(result, df[["a"]]) + + result2 = gbc.transform(lambda xs: np.max(xs, axis=0)) + msg = "using DataFrameGroupBy.max" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result3 = gbc.transform(max) + result4 = gbc.transform(np.maximum.reduce) + result5 = gbc.transform(lambda xs: np.maximum.reduce(xs)) + tm.assert_frame_equal(result2, df[["a"]], check_dtype=False) + tm.assert_frame_equal(result3, df[["a"]], check_dtype=False) + tm.assert_frame_equal(result4, df[["a"]]) + tm.assert_frame_equal(result5, df[["a"]]) + + # Filter + tm.assert_series_equal(df.a.groupby(c, observed=False).filter(np.all), df["a"]) + tm.assert_frame_equal(df.groupby(c, observed=False).filter(np.all), df) + + # Non-monotonic + df = DataFrame({"a": [5, 15, 25, -5]}) + c = pd.cut(df.a, bins=[-10, 0, 10, 20, 30, 40]) + + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.a.groupby(c, observed=False).transform(sum) + tm.assert_series_equal(result, df["a"]) + + tm.assert_series_equal( + df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df["a"] + ) + msg = "using DataFrameGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = df.groupby(c, observed=False).transform(sum) + expected = df[["a"]] + tm.assert_frame_equal(result, expected) + + tm.assert_frame_equal( + df.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), df[["a"]] + ) + + # GH 9603 + df = DataFrame({"a": [1, 0, 0, 0]}) + c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=Categorical(list("abcd"))) + result = df.groupby(c, observed=False).apply(len) + + exp_index = CategoricalIndex(c.values.categories, ordered=c.values.ordered) + expected = Series([1, 0, 0, 0], index=exp_index) + expected.index.name = "a" + tm.assert_series_equal(result, expected) + + # more basic + levels = ["foo", "bar", "baz", "qux"] + codes = np.random.default_rng(2).integers(0, 4, size=100) + + cats = Categorical.from_codes(codes, levels, ordered=True) + + data = DataFrame(np.random.default_rng(2).standard_normal((100, 4))) + + result = data.groupby(cats, observed=False).mean() + + expected = data.groupby(np.asarray(cats), observed=False).mean() + exp_idx = CategoricalIndex(levels, categories=cats.categories, ordered=True) + expected = expected.reindex(exp_idx) + + tm.assert_frame_equal(result, expected) + + grouped = data.groupby(cats, observed=False) + desc_result = grouped.describe() + + idx = cats.codes.argsort() + ord_labels = np.asarray(cats).take(idx) + ord_data = data.take(idx) + + exp_cats = Categorical( + ord_labels, ordered=True, categories=["foo", "bar", "baz", "qux"] + ) + expected = ord_data.groupby(exp_cats, sort=False, observed=False).describe() + tm.assert_frame_equal(desc_result, expected) + + # GH 10460 + expc = Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True) + exp = CategoricalIndex(expc) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(0)), exp + ) + exp = Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(1)), exp + ) + + +def test_level_get_group(observed): + # GH15155 + df = DataFrame( + data=np.arange(2, 22, 2), + index=MultiIndex( + levels=[CategoricalIndex(["a", "b"]), range(10)], + codes=[[0] * 5 + [1] * 5, range(10)], + names=["Index1", "Index2"], + ), + ) + g = df.groupby(level=["Index1"], observed=observed) + + # expected should equal test.loc[["a"]] + # GH15166 + expected = DataFrame( + data=np.arange(2, 12, 2), + index=MultiIndex( + levels=[CategoricalIndex(["a", "b"]), range(5)], + codes=[[0] * 5, range(5)], + names=["Index1", "Index2"], + ), + ) + msg = "you will need to pass a length-1 tuple" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#25971 - warn when not passing a length-1 tuple + result = g.get_group("a") + + tm.assert_frame_equal(result, expected) + + +def test_sorting_with_different_categoricals(): + # GH 24271 + df = DataFrame( + { + "group": ["A"] * 6 + ["B"] * 6, + "dose": ["high", "med", "low"] * 4, + "outcomes": np.arange(12.0), + } + ) + + df.dose = Categorical(df.dose, categories=["low", "med", "high"], ordered=True) + + result = df.groupby("group")["dose"].value_counts() + result = result.sort_index(level=0, sort_remaining=True) + index = ["low", "med", "high", "low", "med", "high"] + index = Categorical(index, categories=["low", "med", "high"], ordered=True) + index = [["A", "A", "A", "B", "B", "B"], CategoricalIndex(index)] + index = MultiIndex.from_arrays(index, names=["group", "dose"]) + expected = Series([2] * 6, index=index, name="count") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_apply(ordered): + # GH 10138 + + dense = Categorical(list("abc"), ordered=ordered) + + # 'b' is in the categories but not in the list + missing = Categorical(list("aaa"), categories=["a", "b"], ordered=ordered) + values = np.arange(len(dense)) + df = DataFrame({"missing": missing, "dense": dense, "values": values}) + grouped = df.groupby(["missing", "dense"], observed=True) + + # missing category 'b' should still exist in the output index + idx = MultiIndex.from_arrays([missing, dense], names=["missing", "dense"]) + expected = DataFrame([0, 1, 2.0], index=idx, columns=["values"]) + + result = grouped.apply(lambda x: np.mean(x, axis=0)) + tm.assert_frame_equal(result, expected) + + result = grouped.mean() + tm.assert_frame_equal(result, expected) + + msg = "using DataFrameGroupBy.mean" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = grouped.agg(np.mean) + tm.assert_frame_equal(result, expected) + + # but for transform we should still get back the original index + idx = MultiIndex.from_arrays([missing, dense], names=["missing", "dense"]) + expected = Series(1, index=idx) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = grouped.apply(lambda x: 1) + tm.assert_series_equal(result, expected) + + +@pytest.mark.filterwarnings("ignore:invalid value encountered in cast:RuntimeWarning") +def test_observed(observed, using_infer_string): + # multiple groupers, don't re-expand the output space + # of the grouper + # gh-14942 (implement) + # gh-10132 (back-compat) + # gh-8138 (back-compat) + # gh-8869 + + cat1 = Categorical(["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True) + cat2 = Categorical(["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + df["C"] = ["foo", "bar"] * 2 + + # multiple groupers with a non-cat + gb = df.groupby(["A", "B", "C"], observed=observed) + exp_index = MultiIndex.from_arrays( + [cat1, cat2, ["foo", "bar"] * 2], names=["A", "B", "C"] + ) + expected = DataFrame({"values": Series([1, 2, 3, 4], index=exp_index)}).sort_index() + result = gb.sum() + if not observed: + expected = cartesian_product_for_groupers( + expected, [cat1, cat2, ["foo", "bar"]], list("ABC"), fill_value=0 + ) + + tm.assert_frame_equal(result, expected) + + gb = df.groupby(["A", "B"], observed=observed) + exp_index = MultiIndex.from_arrays([cat1, cat2], names=["A", "B"]) + expected = DataFrame( + {"values": [1, 2, 3, 4], "C": ["foo", "bar", "foo", "bar"]}, index=exp_index + ) + result = gb.sum() + if not observed: + expected = cartesian_product_for_groupers( + expected, + [cat1, cat2], + list("AB"), + fill_value={"values": 0, "C": ""} if using_infer_string else 0, + ) + + tm.assert_frame_equal(result, expected) + + result = gb["C"].sum() + expected = expected["C"] + tm.assert_series_equal(result, expected) + + # https://github.com/pandas-dev/pandas/issues/8138 + d = { + "cat": Categorical( + ["a", "b", "a", "b"], categories=["a", "b", "c"], ordered=True + ), + "ints": [1, 1, 2, 2], + "val": [10, 20, 30, 40], + } + df = DataFrame(d) + + # Grouping on a single column + groups_single_key = df.groupby("cat", observed=observed) + result = groups_single_key.mean() + + exp_index = CategoricalIndex( + list("ab"), name="cat", categories=list("abc"), ordered=True + ) + expected = DataFrame({"ints": [1.5, 1.5], "val": [20.0, 30]}, index=exp_index) + if not observed: + index = CategoricalIndex( + list("abc"), name="cat", categories=list("abc"), ordered=True + ) + expected = expected.reindex(index) + + tm.assert_frame_equal(result, expected) + + # Grouping on two columns + groups_double_key = df.groupby(["cat", "ints"], observed=observed) + result = groups_double_key.agg("mean") + expected = DataFrame( + { + "val": [10.0, 30.0, 20.0, 40.0], + "cat": Categorical( + ["a", "a", "b", "b"], categories=["a", "b", "c"], ordered=True + ), + "ints": [1, 2, 1, 2], + } + ).set_index(["cat", "ints"]) + if not observed: + expected = cartesian_product_for_groupers( + expected, [df.cat.values, [1, 2]], ["cat", "ints"] + ) + + tm.assert_frame_equal(result, expected) + + # GH 10132 + for key in [("a", 1), ("b", 2), ("b", 1), ("a", 2)]: + c, i = key + result = groups_double_key.get_group(key) + expected = df[(df.cat == c) & (df.ints == i)] + tm.assert_frame_equal(result, expected) + + # gh-8869 + # with as_index + d = { + "foo": [10, 8, 4, 8, 4, 1, 1], + "bar": [10, 20, 30, 40, 50, 60, 70], + "baz": ["d", "c", "e", "a", "a", "d", "c"], + } + df = DataFrame(d) + cat = pd.cut(df["foo"], np.linspace(0, 10, 3)) + df["range"] = cat + groups = df.groupby(["range", "baz"], as_index=False, observed=observed) + result = groups.agg("mean") + + groups2 = df.groupby(["range", "baz"], as_index=True, observed=observed) + expected = groups2.agg("mean").reset_index() + tm.assert_frame_equal(result, expected) + + +def test_observed_codes_remap(observed): + d = {"C1": [3, 3, 4, 5], "C2": [1, 2, 3, 4], "C3": [10, 100, 200, 34]} + df = DataFrame(d) + values = pd.cut(df["C1"], [1, 2, 3, 6]) + values.name = "cat" + groups_double_key = df.groupby([values, "C2"], observed=observed) + + idx = MultiIndex.from_arrays([values, [1, 2, 3, 4]], names=["cat", "C2"]) + expected = DataFrame( + {"C1": [3.0, 3.0, 4.0, 5.0], "C3": [10.0, 100.0, 200.0, 34.0]}, index=idx + ) + if not observed: + expected = cartesian_product_for_groupers( + expected, [values.values, [1, 2, 3, 4]], ["cat", "C2"] + ) + + result = groups_double_key.agg("mean") + tm.assert_frame_equal(result, expected) + + +def test_observed_perf(): + # we create a cartesian product, so this is + # non-performant if we don't use observed values + # gh-14942 + df = DataFrame( + { + "cat": np.random.default_rng(2).integers(0, 255, size=30000), + "int_id": np.random.default_rng(2).integers(0, 255, size=30000), + "other_id": np.random.default_rng(2).integers(0, 10000, size=30000), + "foo": 0, + } + ) + df["cat"] = df.cat.astype(str).astype("category") + + grouped = df.groupby(["cat", "int_id", "other_id"], observed=True) + result = grouped.count() + assert result.index.levels[0].nunique() == df.cat.nunique() + assert result.index.levels[1].nunique() == df.int_id.nunique() + assert result.index.levels[2].nunique() == df.other_id.nunique() + + +def test_observed_groups(observed): + # gh-20583 + # test that we have the appropriate groups + + cat = Categorical(["a", "c", "a"], categories=["a", "b", "c"]) + df = DataFrame({"cat": cat, "vals": [1, 2, 3]}) + g = df.groupby("cat", observed=observed) + + result = g.groups + if observed: + expected = {"a": Index([0, 2], dtype="int64"), "c": Index([1], dtype="int64")} + else: + expected = { + "a": Index([0, 2], dtype="int64"), + "b": Index([], dtype="int64"), + "c": Index([1], dtype="int64"), + } + + tm.assert_dict_equal(result, expected) + + +@pytest.mark.parametrize( + "keys, expected_values, expected_index_levels", + [ + ("a", [15, 9, 0], CategoricalIndex([1, 2, 3], name="a")), + ( + ["a", "b"], + [7, 8, 0, 0, 0, 9, 0, 0, 0], + [CategoricalIndex([1, 2, 3], name="a"), Index([4, 5, 6])], + ), + ( + ["a", "a2"], + [15, 0, 0, 0, 9, 0, 0, 0, 0], + [ + CategoricalIndex([1, 2, 3], name="a"), + CategoricalIndex([1, 2, 3], name="a"), + ], + ), + ], +) +@pytest.mark.parametrize("test_series", [True, False]) +def test_unobserved_in_index(keys, expected_values, expected_index_levels, test_series): + # GH#49354 - ensure unobserved cats occur when grouping by index levels + df = DataFrame( + { + "a": Categorical([1, 1, 2], categories=[1, 2, 3]), + "a2": Categorical([1, 1, 2], categories=[1, 2, 3]), + "b": [4, 5, 6], + "c": [7, 8, 9], + } + ).set_index(["a", "a2"]) + if "b" not in keys: + # Only keep b when it is used for grouping for consistent columns in the result + df = df.drop(columns="b") + + gb = df.groupby(keys, observed=False) + if test_series: + gb = gb["c"] + result = gb.sum() + + if len(keys) == 1: + index = expected_index_levels + else: + codes = [[0, 0, 0, 1, 1, 1, 2, 2, 2], 3 * [0, 1, 2]] + index = MultiIndex( + expected_index_levels, + codes=codes, + names=keys, + ) + expected = DataFrame({"c": expected_values}, index=index) + if test_series: + expected = expected["c"] + tm.assert_equal(result, expected) + + +def test_observed_groups_with_nan(observed): + # GH 24740 + df = DataFrame( + { + "cat": Categorical(["a", np.nan, "a"], categories=["a", "b", "d"]), + "vals": [1, 2, 3], + } + ) + g = df.groupby("cat", observed=observed) + result = g.groups + if observed: + expected = {"a": Index([0, 2], dtype="int64")} + else: + expected = { + "a": Index([0, 2], dtype="int64"), + "b": Index([], dtype="int64"), + "d": Index([], dtype="int64"), + } + tm.assert_dict_equal(result, expected) + + +def test_observed_nth(): + # GH 26385 + cat = Categorical(["a", np.nan, np.nan], categories=["a", "b", "c"]) + ser = Series([1, 2, 3]) + df = DataFrame({"cat": cat, "ser": ser}) + + result = df.groupby("cat", observed=False)["ser"].nth(0) + expected = df["ser"].iloc[[0]] + tm.assert_series_equal(result, expected) + + +def test_dataframe_categorical_with_nan(observed): + # GH 21151 + s1 = Categorical([np.nan, "a", np.nan, "a"], categories=["a", "b", "c"]) + s2 = Series([1, 2, 3, 4]) + df = DataFrame({"s1": s1, "s2": s2}) + result = df.groupby("s1", observed=observed).first().reset_index() + if observed: + expected = DataFrame( + {"s1": Categorical(["a"], categories=["a", "b", "c"]), "s2": [2]} + ) + else: + expected = DataFrame( + { + "s1": Categorical(["a", "b", "c"], categories=["a", "b", "c"]), + "s2": [2, np.nan, np.nan], + } + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("ordered", [True, False]) +@pytest.mark.parametrize("observed", [True, False]) +@pytest.mark.parametrize("sort", [True, False]) +def test_dataframe_categorical_ordered_observed_sort(ordered, observed, sort): + # GH 25871: Fix groupby sorting on ordered Categoricals + # GH 25167: Groupby with observed=True doesn't sort + + # Build a dataframe with cat having one unobserved category ('missing'), + # and a Series with identical values + label = Categorical( + ["d", "a", "b", "a", "d", "b"], + categories=["a", "b", "missing", "d"], + ordered=ordered, + ) + val = Series(["d", "a", "b", "a", "d", "b"]) + df = DataFrame({"label": label, "val": val}) + + # aggregate on the Categorical + result = df.groupby("label", observed=observed, sort=sort)["val"].aggregate("first") + + # If ordering works, we expect index labels equal to aggregation results, + # except for 'observed=False': label 'missing' has aggregation None + label = Series(result.index.array, dtype="object") + aggr = Series(result.array) + if not observed: + aggr[aggr.isna()] = "missing" + if not all(label == aggr): + msg = ( + "Labels and aggregation results not consistently sorted\n" + f"for (ordered={ordered}, observed={observed}, sort={sort})\n" + f"Result:\n{result}" + ) + assert False, msg + + +def test_datetime(): + # GH9049: ensure backward compatibility + levels = pd.date_range("2014-01-01", periods=4) + codes = np.random.default_rng(2).integers(0, 4, size=100) + + cats = Categorical.from_codes(codes, levels, ordered=True) + + data = DataFrame(np.random.default_rng(2).standard_normal((100, 4))) + result = data.groupby(cats, observed=False).mean() + + expected = data.groupby(np.asarray(cats), observed=False).mean() + expected = expected.reindex(levels) + expected.index = CategoricalIndex( + expected.index, categories=expected.index, ordered=True + ) + + tm.assert_frame_equal(result, expected) + + grouped = data.groupby(cats, observed=False) + desc_result = grouped.describe() + + idx = cats.codes.argsort() + ord_labels = cats.take(idx) + ord_data = data.take(idx) + expected = ord_data.groupby(ord_labels, observed=False).describe() + tm.assert_frame_equal(desc_result, expected) + tm.assert_index_equal(desc_result.index, expected.index) + tm.assert_index_equal( + desc_result.index.get_level_values(0), expected.index.get_level_values(0) + ) + + # GH 10460 + expc = Categorical.from_codes(np.arange(4).repeat(8), levels, ordered=True) + exp = CategoricalIndex(expc) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(0)), exp + ) + exp = Index(["count", "mean", "std", "min", "25%", "50%", "75%", "max"] * 4) + tm.assert_index_equal( + (desc_result.stack(future_stack=True).index.get_level_values(1)), exp + ) + + +def test_categorical_index(): + s = np.random.default_rng(2) + levels = ["foo", "bar", "baz", "qux"] + codes = s.integers(0, 4, size=20) + cats = Categorical.from_codes(codes, levels, ordered=True) + df = DataFrame(np.repeat(np.arange(20), 4).reshape(-1, 4), columns=list("abcd")) + df["cats"] = cats + + # with a cat index + result = df.set_index("cats").groupby(level=0, observed=False).sum() + expected = df[list("abcd")].groupby(cats.codes, observed=False).sum() + expected.index = CategoricalIndex( + Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats" + ) + tm.assert_frame_equal(result, expected) + + # with a cat column, should produce a cat index + result = df.groupby("cats", observed=False).sum() + expected = df[list("abcd")].groupby(cats.codes, observed=False).sum() + expected.index = CategoricalIndex( + Categorical.from_codes([0, 1, 2, 3], levels, ordered=True), name="cats" + ) + tm.assert_frame_equal(result, expected) + + +def test_describe_categorical_columns(): + # GH 11558 + cats = CategoricalIndex( + ["qux", "foo", "baz", "bar"], + categories=["foo", "bar", "baz", "qux"], + ordered=True, + ) + df = DataFrame(np.random.default_rng(2).standard_normal((20, 4)), columns=cats) + result = df.groupby([1, 2, 3, 4] * 5).describe() + + tm.assert_index_equal(result.stack(future_stack=True).columns, cats) + tm.assert_categorical_equal( + result.stack(future_stack=True).columns.values, cats.values + ) + + +def test_unstack_categorical(): + # GH11558 (example is taken from the original issue) + df = DataFrame( + {"a": range(10), "medium": ["A", "B"] * 5, "artist": list("XYXXY") * 2} + ) + df["medium"] = df["medium"].astype("category") + + gcat = df.groupby(["artist", "medium"], observed=False)["a"].count().unstack() + result = gcat.describe() + + exp_columns = CategoricalIndex(["A", "B"], ordered=False, name="medium") + tm.assert_index_equal(result.columns, exp_columns) + tm.assert_categorical_equal(result.columns.values, exp_columns.values) + + result = gcat["A"] + gcat["B"] + expected = Series([6, 4], index=Index(["X", "Y"], name="artist")) + tm.assert_series_equal(result, expected) + + +def test_bins_unequal_len(): + # GH3011 + series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4]) + bins = pd.cut(series.dropna().values, 4) + + # len(bins) != len(series) here + with pytest.raises(ValueError, match="Grouper and axis must be same length"): + series.groupby(bins).mean() + + +@pytest.mark.parametrize( + ["series", "data"], + [ + # Group a series with length and index equal to those of the grouper. + (Series(range(4)), {"A": [0, 3], "B": [1, 2]}), + # Group a series with length equal to that of the grouper and index unequal to + # that of the grouper. + (Series(range(4)).rename(lambda idx: idx + 1), {"A": [2], "B": [0, 1]}), + # GH44179: Group a series with length unequal to that of the grouper. + (Series(range(7)), {"A": [0, 3], "B": [1, 2]}), + ], +) +def test_categorical_series(series, data): + # Group the given series by a series with categorical data type such that group A + # takes indices 0 and 3 and group B indices 1 and 2, obtaining the values mapped in + # the given data. + groupby = series.groupby(Series(list("ABBA"), dtype="category"), observed=False) + result = groupby.aggregate(list) + expected = Series(data, index=CategoricalIndex(data.keys())) + tm.assert_series_equal(result, expected) + + +def test_as_index(): + # GH13204 + df = DataFrame( + { + "cat": Categorical([1, 2, 2], [1, 2, 3]), + "A": [10, 11, 11], + "B": [101, 102, 103], + } + ) + result = df.groupby(["cat", "A"], as_index=False, observed=True).sum() + expected = DataFrame( + { + "cat": Categorical([1, 2], categories=df.cat.cat.categories), + "A": [10, 11], + "B": [101, 205], + }, + columns=["cat", "A", "B"], + ) + tm.assert_frame_equal(result, expected) + + # function grouper + f = lambda r: df.loc[r, "A"] + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(["cat", f], as_index=False, observed=True).sum() + expected = DataFrame( + { + "cat": Categorical([1, 2], categories=df.cat.cat.categories), + "A": [10, 22], + "B": [101, 205], + }, + columns=["cat", "A", "B"], + ) + tm.assert_frame_equal(result, expected) + + # another not in-axis grouper (conflicting names in index) + s = Series(["a", "b", "b"], name="cat") + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(["cat", s], as_index=False, observed=True).sum() + tm.assert_frame_equal(result, expected) + + # is original index dropped? + group_columns = ["cat", "A"] + expected = DataFrame( + { + "cat": Categorical([1, 2], categories=df.cat.cat.categories), + "A": [10, 11], + "B": [101, 205], + }, + columns=["cat", "A", "B"], + ) + + for name in [None, "X", "B"]: + df.index = Index(list("abc"), name=name) + result = df.groupby(group_columns, as_index=False, observed=True).sum() + + tm.assert_frame_equal(result, expected) + + +def test_preserve_categories(): + # GH-13179 + categories = list("abc") + + # ordered=True + df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=True)}) + sort_index = CategoricalIndex(categories, categories, ordered=True, name="A") + nosort_index = CategoricalIndex(list("bac"), categories, ordered=True, name="A") + tm.assert_index_equal( + df.groupby("A", sort=True, observed=False).first().index, sort_index + ) + # GH#42482 - don't sort result when sort=False, even when ordered=True + tm.assert_index_equal( + df.groupby("A", sort=False, observed=False).first().index, nosort_index + ) + + # ordered=False + df = DataFrame({"A": Categorical(list("ba"), categories=categories, ordered=False)}) + sort_index = CategoricalIndex(categories, categories, ordered=False, name="A") + # GH#48749 - don't change order of categories + # GH#42482 - don't sort result when sort=False, even when ordered=True + nosort_index = CategoricalIndex(list("bac"), list("abc"), ordered=False, name="A") + tm.assert_index_equal( + df.groupby("A", sort=True, observed=False).first().index, sort_index + ) + tm.assert_index_equal( + df.groupby("A", sort=False, observed=False).first().index, nosort_index + ) + + +def test_preserve_categorical_dtype(): + # GH13743, GH13854 + df = DataFrame( + { + "A": [1, 2, 1, 1, 2], + "B": [10, 16, 22, 28, 34], + "C1": Categorical(list("abaab"), categories=list("bac"), ordered=False), + "C2": Categorical(list("abaab"), categories=list("bac"), ordered=True), + } + ) + # single grouper + exp_full = DataFrame( + { + "A": [2.0, 1.0, np.nan], + "B": [25.0, 20.0, np.nan], + "C1": Categorical(list("bac"), categories=list("bac"), ordered=False), + "C2": Categorical(list("bac"), categories=list("bac"), ordered=True), + } + ) + for col in ["C1", "C2"]: + result1 = df.groupby(by=col, as_index=False, observed=False).mean( + numeric_only=True + ) + result2 = ( + df.groupby(by=col, as_index=True, observed=False) + .mean(numeric_only=True) + .reset_index() + ) + expected = exp_full.reindex(columns=result1.columns) + tm.assert_frame_equal(result1, expected) + tm.assert_frame_equal(result2, expected) + + +@pytest.mark.parametrize( + "func, values", + [ + ("first", ["second", "first"]), + ("last", ["fourth", "third"]), + ("min", ["fourth", "first"]), + ("max", ["second", "third"]), + ], +) +def test_preserve_on_ordered_ops(func, values): + # gh-18502 + # preserve the categoricals on ops + c = Categorical(["first", "second", "third", "fourth"], ordered=True) + df = DataFrame({"payload": [-1, -2, -1, -2], "col": c}) + g = df.groupby("payload") + result = getattr(g, func)() + expected = DataFrame( + {"payload": [-2, -1], "col": Series(values, dtype=c.dtype)} + ).set_index("payload") + tm.assert_frame_equal(result, expected) + + # we should also preserve categorical for SeriesGroupBy + sgb = df.groupby("payload")["col"] + result = getattr(sgb, func)() + expected = expected["col"] + tm.assert_series_equal(result, expected) + + +def test_categorical_no_compress(): + data = Series(np.random.default_rng(2).standard_normal(9)) + + codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) + cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True) + + result = data.groupby(cats, observed=False).mean() + exp = data.groupby(codes, observed=False).mean() + + exp.index = CategoricalIndex( + exp.index, categories=cats.categories, ordered=cats.ordered + ) + tm.assert_series_equal(result, exp) + + codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3]) + cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True) + + result = data.groupby(cats, observed=False).mean() + exp = data.groupby(codes, observed=False).mean().reindex(cats.categories) + exp.index = CategoricalIndex( + exp.index, categories=cats.categories, ordered=cats.ordered + ) + tm.assert_series_equal(result, exp) + + cats = Categorical( + ["a", "a", "a", "b", "b", "b", "c", "c", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats}) + + result = data.groupby("b", observed=False).mean() + result = result["a"].values + exp = np.array([1, 2, 4, np.nan]) + tm.assert_numpy_array_equal(result, exp) + + +def test_groupby_empty_with_category(): + # GH-9614 + # test fix for when group by on None resulted in + # coercion of dtype categorical -> float + df = DataFrame({"A": [None] * 3, "B": Categorical(["train", "train", "test"])}) + result = df.groupby("A").first()["B"] + expected = Series( + Categorical([], categories=["test", "train"]), + index=Series([], dtype="object", name="A"), + name="B", + ) + tm.assert_series_equal(result, expected) + + +def test_sort(): + # https://stackoverflow.com/questions/23814368/sorting-pandas- + # categorical-labels-after-groupby + # This should result in a properly sorted Series so that the plot + # has a sorted x axis + # self.cat.groupby(['value_group'])['value_group'].count().plot(kind='bar') + + df = DataFrame({"value": np.random.default_rng(2).integers(0, 10000, 100)}) + labels = [f"{i} - {i+499}" for i in range(0, 10000, 500)] + cat_labels = Categorical(labels, labels) + + df = df.sort_values(by=["value"], ascending=True) + df["value_group"] = pd.cut( + df.value, range(0, 10500, 500), right=False, labels=cat_labels + ) + + res = df.groupby(["value_group"], observed=False)["value_group"].count() + exp = res[sorted(res.index, key=lambda x: float(x.split()[0]))] + exp.index = CategoricalIndex(exp.index, name=exp.index.name) + tm.assert_series_equal(res, exp) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_sort2(sort, ordered): + # dataframe groupby sort was being ignored # GH 8868 + # GH#48749 - don't change order of categories + # GH#42482 - don't sort result when sort=False, even when ordered=True + df = DataFrame( + [ + ["(7.5, 10]", 10, 10], + ["(7.5, 10]", 8, 20], + ["(2.5, 5]", 5, 30], + ["(5, 7.5]", 6, 40], + ["(2.5, 5]", 4, 50], + ["(0, 2.5]", 1, 60], + ["(5, 7.5]", 7, 70], + ], + columns=["range", "foo", "bar"], + ) + df["range"] = Categorical(df["range"], ordered=ordered) + result = df.groupby("range", sort=sort, observed=False).first() + + if sort: + data_values = [[1, 60], [5, 30], [6, 40], [10, 10]] + index_values = ["(0, 2.5]", "(2.5, 5]", "(5, 7.5]", "(7.5, 10]"] + else: + data_values = [[10, 10], [5, 30], [6, 40], [1, 60]] + index_values = ["(7.5, 10]", "(2.5, 5]", "(5, 7.5]", "(0, 2.5]"] + expected = DataFrame( + data_values, + columns=["foo", "bar"], + index=CategoricalIndex(index_values, name="range", ordered=ordered), + ) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("ordered", [True, False]) +def test_sort_datetimelike(sort, ordered): + # GH10505 + # GH#42482 - don't sort result when sort=False, even when ordered=True + + # use same data as test_groupby_sort_categorical, which category is + # corresponding to datetime.month + df = DataFrame( + { + "dt": [ + datetime(2011, 7, 1), + datetime(2011, 7, 1), + datetime(2011, 2, 1), + datetime(2011, 5, 1), + datetime(2011, 2, 1), + datetime(2011, 1, 1), + datetime(2011, 5, 1), + ], + "foo": [10, 8, 5, 6, 4, 1, 7], + "bar": [10, 20, 30, 40, 50, 60, 70], + }, + columns=["dt", "foo", "bar"], + ) + + # ordered=True + df["dt"] = Categorical(df["dt"], ordered=ordered) + if sort: + data_values = [[1, 60], [5, 30], [6, 40], [10, 10]] + index_values = [ + datetime(2011, 1, 1), + datetime(2011, 2, 1), + datetime(2011, 5, 1), + datetime(2011, 7, 1), + ] + else: + data_values = [[10, 10], [5, 30], [6, 40], [1, 60]] + index_values = [ + datetime(2011, 7, 1), + datetime(2011, 2, 1), + datetime(2011, 5, 1), + datetime(2011, 1, 1), + ] + expected = DataFrame( + data_values, + columns=["foo", "bar"], + index=CategoricalIndex(index_values, name="dt", ordered=ordered), + ) + result = df.groupby("dt", sort=sort, observed=False).first() + tm.assert_frame_equal(result, expected) + + +def test_empty_sum(): + # https://github.com/pandas-dev/pandas/issues/18678 + df = DataFrame( + {"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"]), "B": [1, 2, 1]} + ) + expected_idx = CategoricalIndex(["a", "b", "c"], name="A") + + # 0 by default + result = df.groupby("A", observed=False).B.sum() + expected = Series([3, 1, 0], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=0 + result = df.groupby("A", observed=False).B.sum(min_count=0) + expected = Series([3, 1, 0], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=1 + result = df.groupby("A", observed=False).B.sum(min_count=1) + expected = Series([3, 1, np.nan], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count>1 + result = df.groupby("A", observed=False).B.sum(min_count=2) + expected = Series([3, np.nan, np.nan], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + +def test_empty_prod(): + # https://github.com/pandas-dev/pandas/issues/18678 + df = DataFrame( + {"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"]), "B": [1, 2, 1]} + ) + + expected_idx = CategoricalIndex(["a", "b", "c"], name="A") + + # 1 by default + result = df.groupby("A", observed=False).B.prod() + expected = Series([2, 1, 1], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=0 + result = df.groupby("A", observed=False).B.prod(min_count=0) + expected = Series([2, 1, 1], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + # min_count=1 + result = df.groupby("A", observed=False).B.prod(min_count=1) + expected = Series([2, 1, np.nan], expected_idx, name="B") + tm.assert_series_equal(result, expected) + + +def test_groupby_multiindex_categorical_datetime(): + # https://github.com/pandas-dev/pandas/issues/21390 + + df = DataFrame( + { + "key1": Categorical(list("abcbabcba")), + "key2": Categorical( + list(pd.date_range("2018-06-01 00", freq="1min", periods=3)) * 3 + ), + "values": np.arange(9), + } + ) + result = df.groupby(["key1", "key2"], observed=False).mean() + + idx = MultiIndex.from_product( + [ + Categorical(["a", "b", "c"]), + Categorical(pd.date_range("2018-06-01 00", freq="1min", periods=3)), + ], + names=["key1", "key2"], + ) + expected = DataFrame({"values": [0, 4, 8, 3, 4, 5, 6, np.nan, 2]}, index=idx) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "as_index, expected", + [ + ( + True, + Series( + index=MultiIndex.from_arrays( + [Series([1, 1, 2], dtype="category"), [1, 2, 2]], names=["a", "b"] + ), + data=[1, 2, 3], + name="x", + ), + ), + ( + False, + DataFrame( + { + "a": Series([1, 1, 2], dtype="category"), + "b": [1, 2, 2], + "x": [1, 2, 3], + } + ), + ), + ], +) +def test_groupby_agg_observed_true_single_column(as_index, expected): + # GH-23970 + df = DataFrame( + {"a": Series([1, 1, 2], dtype="category"), "b": [1, 2, 2], "x": [1, 2, 3]} + ) + + result = df.groupby(["a", "b"], as_index=as_index, observed=True)["x"].sum() + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("fill_value", [None, np.nan, pd.NaT]) +def test_shift(fill_value): + ct = Categorical( + ["a", "b", "c", "d"], categories=["a", "b", "c", "d"], ordered=False + ) + expected = Categorical( + [None, "a", "b", "c"], categories=["a", "b", "c", "d"], ordered=False + ) + res = ct.shift(1, fill_value=fill_value) + tm.assert_equal(res, expected) + + +@pytest.fixture +def df_cat(df): + """ + DataFrame with multiple categorical columns and a column of integers. + Shortened so as not to contain all possible combinations of categories. + Useful for testing `observed` kwarg functionality on GroupBy objects. + + Parameters + ---------- + df: DataFrame + Non-categorical, longer DataFrame from another fixture, used to derive + this one + + Returns + ------- + df_cat: DataFrame + """ + df_cat = df.copy()[:4] # leave out some groups + df_cat["A"] = df_cat["A"].astype("category") + df_cat["B"] = df_cat["B"].astype("category") + df_cat["C"] = Series([1, 2, 3, 4]) + df_cat = df_cat.drop(["D"], axis=1) + return df_cat + + +@pytest.mark.parametrize("operation", ["agg", "apply"]) +def test_seriesgroupby_observed_true(df_cat, operation): + # GH#24880 + # GH#49223 - order of results was wrong when grouping by index levels + lev_a = Index(["bar", "bar", "foo", "foo"], dtype=df_cat["A"].dtype, name="A") + lev_b = Index(["one", "three", "one", "two"], dtype=df_cat["B"].dtype, name="B") + index = MultiIndex.from_arrays([lev_a, lev_b]) + expected = Series(data=[2, 4, 1, 3], index=index, name="C").sort_index() + + grouped = df_cat.groupby(["A", "B"], observed=True)["C"] + msg = "using np.sum" if operation == "apply" else "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = getattr(grouped, operation)(sum) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("operation", ["agg", "apply"]) +@pytest.mark.parametrize("observed", [False, None]) +def test_seriesgroupby_observed_false_or_none(df_cat, observed, operation): + # GH 24880 + # GH#49223 - order of results was wrong when grouping by index levels + index, _ = MultiIndex.from_product( + [ + CategoricalIndex(["bar", "foo"], ordered=False), + CategoricalIndex(["one", "three", "two"], ordered=False), + ], + names=["A", "B"], + ).sortlevel() + + expected = Series(data=[2, 4, np.nan, 1, np.nan, 3], index=index, name="C") + if operation == "agg": + msg = "The 'downcast' keyword in fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = expected.fillna(0, downcast="infer") + grouped = df_cat.groupby(["A", "B"], observed=observed)["C"] + msg = "using SeriesGroupBy.sum" if operation == "agg" else "using np.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = getattr(grouped, operation)(sum) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "observed, index, data", + [ + ( + True, + MultiIndex.from_arrays( + [ + Index(["bar"] * 4 + ["foo"] * 4, dtype="category", name="A"), + Index( + ["one", "one", "three", "three", "one", "one", "two", "two"], + dtype="category", + name="B", + ), + Index(["min", "max"] * 4), + ] + ), + [2, 2, 4, 4, 1, 1, 3, 3], + ), + ( + False, + MultiIndex.from_product( + [ + CategoricalIndex(["bar", "foo"], ordered=False), + CategoricalIndex(["one", "three", "two"], ordered=False), + Index(["min", "max"]), + ], + names=["A", "B", None], + ), + [2, 2, 4, 4, np.nan, np.nan, 1, 1, np.nan, np.nan, 3, 3], + ), + ( + None, + MultiIndex.from_product( + [ + CategoricalIndex(["bar", "foo"], ordered=False), + CategoricalIndex(["one", "three", "two"], ordered=False), + Index(["min", "max"]), + ], + names=["A", "B", None], + ), + [2, 2, 4, 4, np.nan, np.nan, 1, 1, np.nan, np.nan, 3, 3], + ), + ], +) +def test_seriesgroupby_observed_apply_dict(df_cat, observed, index, data): + # GH 24880 + expected = Series(data=data, index=index, name="C") + result = df_cat.groupby(["A", "B"], observed=observed)["C"].apply( + lambda x: {"min": x.min(), "max": x.max()} + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_categorical_series_dataframe_consistent(df_cat): + # GH 20416 + expected = df_cat.groupby(["A", "B"], observed=False)["C"].mean() + result = df_cat.groupby(["A", "B"], observed=False).mean()["C"] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("code", [([1, 0, 0]), ([0, 0, 0])]) +def test_groupby_categorical_axis_1(code): + # GH 13420 + df = DataFrame({"a": [1, 2, 3, 4], "b": [-1, -2, -3, -4], "c": [5, 6, 7, 8]}) + cat = Categorical.from_codes(code, categories=list("abc")) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(cat, axis=1, observed=False) + result = gb.mean() + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df.T.groupby(cat, axis=0, observed=False) + expected = gb2.mean().T + tm.assert_frame_equal(result, expected) + + +def test_groupby_cat_preserves_structure(observed, ordered): + # GH 28787 + df = DataFrame( + {"Name": Categorical(["Bob", "Greg"], ordered=ordered), "Item": [1, 2]}, + columns=["Name", "Item"], + ) + expected = df.copy() + + result = ( + df.groupby("Name", observed=observed) + .agg(DataFrame.sum, skipna=True) + .reset_index() + ) + + tm.assert_frame_equal(result, expected) + + +def test_get_nonexistent_category(): + # Accessing a Category that is not in the dataframe + df = DataFrame({"var": ["a", "a", "b", "b"], "val": range(4)}) + with pytest.raises(KeyError, match="'vau'"): + df.groupby("var").apply( + lambda rows: DataFrame( + {"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]} + ) + ) + + +def test_series_groupby_on_2_categoricals_unobserved(reduction_func, observed): + # GH 17605 + if reduction_func == "ngroup": + pytest.skip("ngroup is not truly a reduction") + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABCD")), + "cat_2": Categorical(list("AB") * 2, categories=list("ABCD")), + "value": [0.1] * 4, + } + ) + args = get_groupby_method_args(reduction_func, df) + + expected_length = 4 if observed else 16 + + series_groupby = df.groupby(["cat_1", "cat_2"], observed=observed)["value"] + + if reduction_func == "corrwith": + # TODO: implemented SeriesGroupBy.corrwith. See GH 32293 + assert not hasattr(series_groupby, reduction_func) + return + + agg = getattr(series_groupby, reduction_func) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + agg(*args) + return + + result = agg(*args) + + assert len(result) == expected_length + + +def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans( + reduction_func, request +): + # GH 17605 + # Tests whether the unobserved categories in the result contain 0 or NaN + + if reduction_func == "ngroup": + pytest.skip("ngroup is not truly a reduction") + + if reduction_func == "corrwith": # GH 32293 + mark = pytest.mark.xfail( + reason="TODO: implemented SeriesGroupBy.corrwith. See GH 32293" + ) + request.applymarker(mark) + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("AB") * 2, categories=list("ABC")), + "value": [0.1] * 4, + } + ) + unobserved = [tuple("AC"), tuple("BC"), tuple("CA"), tuple("CB"), tuple("CC")] + args = get_groupby_method_args(reduction_func, df) + + series_groupby = df.groupby(["cat_1", "cat_2"], observed=False)["value"] + agg = getattr(series_groupby, reduction_func) + + if reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + agg(*args) + return + + result = agg(*args) + + zero_or_nan = _results_for_groupbys_with_missing_categories[reduction_func] + + for idx in unobserved: + val = result.loc[idx] + assert (pd.isna(zero_or_nan) and pd.isna(val)) or (val == zero_or_nan) + + # If we expect unobserved values to be zero, we also expect the dtype to be int. + # Except for .sum(). If the observed categories sum to dtype=float (i.e. their + # sums have decimals), then the zeros for the missing categories should also be + # floats. + if zero_or_nan == 0 and reduction_func != "sum": + assert np.issubdtype(result.dtype, np.integer) + + +def test_dataframe_groupby_on_2_categoricals_when_observed_is_true(reduction_func): + # GH 23865 + # GH 27075 + # Ensure that df.groupby, when 'by' is two Categorical variables, + # does not return the categories that are not in df when observed=True + if reduction_func == "ngroup": + pytest.skip("ngroup does not return the Categories on the index") + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("1111"), categories=list("12")), + "value": [0.1, 0.1, 0.1, 0.1], + } + ) + unobserved_cats = [("A", "2"), ("B", "2"), ("C", "1"), ("C", "2")] + + df_grp = df.groupby(["cat_1", "cat_2"], observed=True) + + args = get_groupby_method_args(reduction_func, df) + res = getattr(df_grp, reduction_func)(*args) + + for cat in unobserved_cats: + assert cat not in res.index + + +@pytest.mark.parametrize("observed", [False, None]) +def test_dataframe_groupby_on_2_categoricals_when_observed_is_false( + reduction_func, observed +): + # GH 23865 + # GH 27075 + # Ensure that df.groupby, when 'by' is two Categorical variables, + # returns the categories that are not in df when observed=False/None + + if reduction_func == "ngroup": + pytest.skip("ngroup does not return the Categories on the index") + + df = DataFrame( + { + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("1111"), categories=list("12")), + "value": [0.1, 0.1, 0.1, 0.1], + } + ) + unobserved_cats = [("A", "2"), ("B", "2"), ("C", "1"), ("C", "2")] + + df_grp = df.groupby(["cat_1", "cat_2"], observed=observed) + + args = get_groupby_method_args(reduction_func, df) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(df_grp, reduction_func)(*args) + return + + res = getattr(df_grp, reduction_func)(*args) + + expected = _results_for_groupbys_with_missing_categories[reduction_func] + + if expected is np.nan: + assert res.loc[unobserved_cats].isnull().all().all() + else: + assert (res.loc[unobserved_cats] == expected).all().all() + + +@pytest.mark.filterwarnings("ignore:invalid value encountered in cast:RuntimeWarning") +def test_series_groupby_categorical_aggregation_getitem(): + # GH 8870 + d = {"foo": [10, 8, 4, 1], "bar": [10, 20, 30, 40], "baz": ["d", "c", "d", "c"]} + df = DataFrame(d) + cat = pd.cut(df["foo"], np.linspace(0, 20, 5)) + df["range"] = cat + groups = df.groupby(["range", "baz"], as_index=True, sort=True, observed=False) + result = groups["foo"].agg("mean") + expected = groups.agg("mean")["foo"] + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func, expected_values", + [(Series.nunique, [1, 1, 2]), (Series.count, [1, 2, 2])], +) +def test_groupby_agg_categorical_columns(func, expected_values): + # 31256 + df = DataFrame( + { + "id": [0, 1, 2, 3, 4], + "groups": [0, 1, 1, 2, 2], + "value": Categorical([0, 0, 0, 0, 1]), + } + ).set_index("id") + result = df.groupby("groups").agg(func) + + expected = DataFrame( + {"value": expected_values}, index=Index([0, 1, 2], name="groups") + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_agg_non_numeric(): + df = DataFrame({"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"])}) + expected = DataFrame({"A": [2, 1]}, index=np.array([1, 2])) + + result = df.groupby([1, 2, 1]).agg(Series.nunique) + tm.assert_frame_equal(result, expected) + + result = df.groupby([1, 2, 1]).nunique() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_groupby_first_returned_categorical_instead_of_dataframe(func): + # GH 28641: groupby drops index, when grouping over categorical column with + # first/last. Renamed Categorical instead of DataFrame previously. + df = DataFrame({"A": [1997], "B": Series(["b"], dtype="category").cat.as_ordered()}) + df_grouped = df.groupby("A")["B"] + result = getattr(df_grouped, func)() + + # ordered categorical dtype should be preserved + expected = Series( + ["b"], index=Index([1997], name="A"), name="B", dtype=df["B"].dtype + ) + tm.assert_series_equal(result, expected) + + +def test_read_only_category_no_sort(): + # GH33410 + cats = np.array([1, 2]) + cats.flags.writeable = False + df = DataFrame( + {"a": [1, 3, 5, 7], "b": Categorical([1, 1, 2, 2], categories=Index(cats))} + ) + expected = DataFrame(data={"a": [2.0, 6.0]}, index=CategoricalIndex(cats, name="b")) + result = df.groupby("b", sort=False, observed=False).mean() + tm.assert_frame_equal(result, expected) + + +def test_sorted_missing_category_values(): + # GH 28597 + df = DataFrame( + { + "foo": [ + "small", + "large", + "large", + "large", + "medium", + "large", + "large", + "medium", + ], + "bar": ["C", "A", "A", "C", "A", "C", "A", "C"], + } + ) + df["foo"] = ( + df["foo"] + .astype("category") + .cat.set_categories(["tiny", "small", "medium", "large"], ordered=True) + ) + + expected = DataFrame( + { + "tiny": {"A": 0, "C": 0}, + "small": {"A": 0, "C": 1}, + "medium": {"A": 1, "C": 1}, + "large": {"A": 3, "C": 2}, + } + ) + expected = expected.rename_axis("bar", axis="index") + expected.columns = CategoricalIndex( + ["tiny", "small", "medium", "large"], + categories=["tiny", "small", "medium", "large"], + ordered=True, + name="foo", + dtype="category", + ) + + result = df.groupby(["bar", "foo"], observed=False).size().unstack() + + tm.assert_frame_equal(result, expected) + + +def test_agg_cython_category_not_implemented_fallback(): + # https://github.com/pandas-dev/pandas/issues/31450 + df = DataFrame({"col_num": [1, 1, 2, 3]}) + df["col_cat"] = df["col_num"].astype("category") + + result = df.groupby("col_num").col_cat.first() + + # ordered categorical dtype should definitely be preserved; + # this is unordered, so is less-clear case (if anything, it should raise) + expected = Series( + [1, 2, 3], + index=Index([1, 2, 3], name="col_num"), + name="col_cat", + dtype=df["col_cat"].dtype, + ) + tm.assert_series_equal(result, expected) + + result = df.groupby("col_num").agg({"col_cat": "first"}) + expected = expected.to_frame() + tm.assert_frame_equal(result, expected) + + +def test_aggregate_categorical_with_isnan(): + # GH 29837 + df = DataFrame( + { + "A": [1, 1, 1, 1], + "B": [1, 2, 1, 2], + "numerical_col": [0.1, 0.2, np.nan, 0.3], + "object_col": ["foo", "bar", "foo", "fee"], + "categorical_col": ["foo", "bar", "foo", "fee"], + } + ) + + df = df.astype({"categorical_col": "category"}) + + result = df.groupby(["A", "B"]).agg(lambda df: df.isna().sum()) + index = MultiIndex.from_arrays([[1, 1], [1, 2]], names=("A", "B")) + expected = DataFrame( + data={ + "numerical_col": [1, 0], + "object_col": [0, 0], + "categorical_col": [0, 0], + }, + index=index, + ) + tm.assert_frame_equal(result, expected) + + +def test_categorical_transform(): + # GH 29037 + df = DataFrame( + { + "package_id": [1, 1, 1, 2, 2, 3], + "status": [ + "Waiting", + "OnTheWay", + "Delivered", + "Waiting", + "OnTheWay", + "Waiting", + ], + } + ) + + delivery_status_type = pd.CategoricalDtype( + categories=["Waiting", "OnTheWay", "Delivered"], ordered=True + ) + df["status"] = df["status"].astype(delivery_status_type) + msg = "using SeriesGroupBy.max" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + df["last_status"] = df.groupby("package_id")["status"].transform(max) + result = df.copy() + + expected = DataFrame( + { + "package_id": [1, 1, 1, 2, 2, 3], + "status": [ + "Waiting", + "OnTheWay", + "Delivered", + "Waiting", + "OnTheWay", + "Waiting", + ], + "last_status": [ + "Delivered", + "Delivered", + "Delivered", + "OnTheWay", + "OnTheWay", + "Waiting", + ], + } + ) + + expected["status"] = expected["status"].astype(delivery_status_type) + + # .transform(max) should preserve ordered categoricals + expected["last_status"] = expected["last_status"].astype(delivery_status_type) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_series_groupby_first_on_categorical_col_grouped_on_2_categoricals( + func: str, observed: bool +): + # GH 34951 + cat = Categorical([0, 0, 1, 1]) + val = [0, 1, 1, 0] + df = DataFrame({"a": cat, "b": cat, "c": val}) + + cat2 = Categorical([0, 1]) + idx = MultiIndex.from_product([cat2, cat2], names=["a", "b"]) + expected_dict = { + "first": Series([0, np.nan, np.nan, 1], idx, name="c"), + "last": Series([1, np.nan, np.nan, 0], idx, name="c"), + } + + expected = expected_dict[func] + if observed: + expected = expected.dropna().astype(np.int64) + + srs_grp = df.groupby(["a", "b"], observed=observed)["c"] + result = getattr(srs_grp, func)() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_df_groupby_first_on_categorical_col_grouped_on_2_categoricals( + func: str, observed: bool +): + # GH 34951 + cat = Categorical([0, 0, 1, 1]) + val = [0, 1, 1, 0] + df = DataFrame({"a": cat, "b": cat, "c": val}) + + cat2 = Categorical([0, 1]) + idx = MultiIndex.from_product([cat2, cat2], names=["a", "b"]) + expected_dict = { + "first": Series([0, np.nan, np.nan, 1], idx, name="c"), + "last": Series([1, np.nan, np.nan, 0], idx, name="c"), + } + + expected = expected_dict[func].to_frame() + if observed: + expected = expected.dropna().astype(np.int64) + + df_grp = df.groupby(["a", "b"], observed=observed) + result = getattr(df_grp, func)() + tm.assert_frame_equal(result, expected) + + +def test_groupby_categorical_indices_unused_categories(): + # GH#38642 + df = DataFrame( + { + "key": Categorical(["b", "b", "a"], categories=["a", "b", "c"]), + "col": range(3), + } + ) + grouped = df.groupby("key", sort=False, observed=False) + result = grouped.indices + expected = { + "b": np.array([0, 1], dtype="intp"), + "a": np.array([2], dtype="intp"), + "c": np.array([], dtype="intp"), + } + assert result.keys() == expected.keys() + for key in result.keys(): + tm.assert_numpy_array_equal(result[key], expected[key]) + + +@pytest.mark.parametrize("func", ["first", "last"]) +def test_groupby_last_first_preserve_categoricaldtype(func): + # GH#33090 + df = DataFrame({"a": [1, 2, 3]}) + df["b"] = df["a"].astype("category") + result = getattr(df.groupby("a")["b"], func)() + expected = Series( + Categorical([1, 2, 3]), name="b", index=Index([1, 2, 3], name="a") + ) + tm.assert_series_equal(expected, result) + + +def test_groupby_categorical_observed_nunique(): + # GH#45128 + df = DataFrame({"a": [1, 2], "b": [1, 2], "c": [10, 11]}) + df = df.astype(dtype={"a": "category", "b": "category"}) + result = df.groupby(["a", "b"], observed=True).nunique()["c"] + expected = Series( + [1, 1], + index=MultiIndex.from_arrays( + [CategoricalIndex([1, 2], name="a"), CategoricalIndex([1, 2], name="b")] + ), + name="c", + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_categorical_aggregate_functions(): + # GH#37275 + dtype = pd.CategoricalDtype(categories=["small", "big"], ordered=True) + df = DataFrame( + [[1, "small"], [1, "big"], [2, "small"]], columns=["grp", "description"] + ).astype({"description": dtype}) + + result = df.groupby("grp")["description"].max() + expected = Series( + ["big", "small"], + index=Index([1, 2], name="grp"), + name="description", + dtype=pd.CategoricalDtype(categories=["small", "big"], ordered=True), + ) + + tm.assert_series_equal(result, expected) + + +def test_groupby_categorical_dropna(observed, dropna): + # GH#48645 - dropna should have no impact on the result when there are no NA values + cat = Categorical([1, 2], categories=[1, 2, 3]) + df = DataFrame({"x": Categorical([1, 2], categories=[1, 2, 3]), "y": [3, 4]}) + gb = df.groupby("x", observed=observed, dropna=dropna) + result = gb.sum() + + if observed: + expected = DataFrame({"y": [3, 4]}, index=cat) + else: + index = CategoricalIndex([1, 2, 3], [1, 2, 3]) + expected = DataFrame({"y": [3, 4, 0]}, index=index) + expected.index.name = "x" + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_reducer( + request, as_index, sort, observed, reduction_func, index_kind, ordered +): + # GH#48749 + if reduction_func == "corrwith" and not as_index: + msg = "GH#49950 - corrwith with as_index=False may not have grouping column" + request.applymarker(pytest.mark.xfail(reason=msg)) + elif index_kind != "range" and not as_index: + pytest.skip(reason="Result doesn't have categories, nothing to test") + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + args = get_groupby_method_args(reduction_func, df) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + # idxmin and idxmax are designed to fail on empty inputs + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(gb, reduction_func)(*args) + return + + op_result = getattr(gb, reduction_func)(*args) + if as_index: + result = op_result.index.get_level_values("a").categories + else: + result = op_result["a"].cat.categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["single", "multi"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_transformer( + as_index, sort, observed, transformation_func, index_kind, ordered +): + # GH#48749 + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + args = get_groupby_method_args(transformation_func, df) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + warn = FutureWarning if transformation_func == "fillna" else None + msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=msg): + op_result = getattr(gb, transformation_func)(*args) + result = op_result.index.get_level_values("a").categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +@pytest.mark.parametrize("method", ["head", "tail"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_head_tail( + as_index, sort, observed, method, index_kind, ordered +): + # GH#48749 + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + op_result = getattr(gb, method)() + if index_kind == "range": + result = op_result["a"].cat.categories + else: + result = op_result.index.get_level_values("a").categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +@pytest.mark.parametrize("method", ["apply", "agg", "transform"]) +@pytest.mark.parametrize("ordered", [True, False]) +def test_category_order_apply(as_index, sort, observed, method, index_kind, ordered): + # GH#48749 + if (method == "transform" and index_kind == "range") or ( + not as_index and index_kind != "range" + ): + pytest.skip("No categories in result, nothing to test") + df = DataFrame( + { + "a": Categorical([2, 1, 2, 3], categories=[1, 4, 3, 2], ordered=ordered), + "b": range(4), + } + ) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=observed) + warn = FutureWarning if method == "apply" and index_kind == "range" else None + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(warn, match=msg): + op_result = getattr(gb, method)(lambda x: x.sum(numeric_only=True)) + if (method == "transform" or not as_index) and index_kind == "range": + result = op_result["a"].cat.categories + else: + result = op_result.index.get_level_values("a").categories + expected = Index([1, 4, 3, 2]) + tm.assert_index_equal(result, expected) + + if index_kind == "multi": + result = op_result.index.get_level_values("a2").categories + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +def test_many_categories(as_index, sort, index_kind, ordered): + # GH#48749 - Test when the grouper has many categories + if index_kind != "range" and not as_index: + pytest.skip(reason="Result doesn't have categories, nothing to test") + categories = np.arange(9999, -1, -1) + grouper = Categorical([2, 1, 2, 3], categories=categories, ordered=ordered) + df = DataFrame({"a": grouper, "b": range(4)}) + if index_kind == "range": + keys = ["a"] + elif index_kind == "single": + keys = ["a"] + df = df.set_index(keys) + elif index_kind == "multi": + keys = ["a", "a2"] + df["a2"] = df["a"] + df = df.set_index(keys) + gb = df.groupby(keys, as_index=as_index, sort=sort, observed=True) + result = gb.sum() + + # Test is setup so that data and index are the same values + data = [3, 2, 1] if sort else [2, 1, 3] + + index = CategoricalIndex( + data, categories=grouper.categories, ordered=ordered, name="a" + ) + if as_index: + expected = DataFrame({"b": data}) + if index_kind == "multi": + expected.index = MultiIndex.from_frame(DataFrame({"a": index, "a2": index})) + else: + expected.index = index + elif index_kind == "multi": + expected = DataFrame({"a": Series(index), "a2": Series(index), "b": data}) + else: + expected = DataFrame({"a": Series(index), "b": data}) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("cat_columns", ["a", "b", ["a", "b"]]) +@pytest.mark.parametrize("keys", ["a", "b", ["a", "b"]]) +def test_groupby_default_depr(cat_columns, keys): + # GH#43999 + df = DataFrame({"a": [1, 1, 2, 3], "b": [4, 5, 6, 7]}) + df[cat_columns] = df[cat_columns].astype("category") + msg = "The default of observed=False is deprecated" + klass = FutureWarning if set(cat_columns) & set(keys) else None + with tm.assert_produces_warning(klass, match=msg): + df.groupby(keys) + + +@pytest.mark.parametrize("test_series", [True, False]) +@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) +def test_agg_list(request, as_index, observed, reduction_func, test_series, keys): + # GH#52760 + if test_series and reduction_func == "corrwith": + assert not hasattr(SeriesGroupBy, "corrwith") + pytest.skip("corrwith not implemented for SeriesGroupBy") + elif reduction_func == "corrwith": + msg = "GH#32293: attempts to call SeriesGroupBy.corrwith" + request.applymarker(pytest.mark.xfail(reason=msg)) + elif ( + reduction_func == "nunique" + and not test_series + and len(keys) != 1 + and not observed + and not as_index + ): + msg = "GH#52848 - raises a ValueError" + request.applymarker(pytest.mark.xfail(reason=msg)) + + df = DataFrame({"a1": [0, 0, 1], "a2": [2, 3, 3], "b": [4, 5, 6]}) + df = df.astype({"a1": "category", "a2": "category"}) + if "a2" not in keys: + df = df.drop(columns="a2") + gb = df.groupby(by=keys, as_index=as_index, observed=observed) + if test_series: + gb = gb["b"] + args = get_groupby_method_args(reduction_func, df) + + if not observed and reduction_func in ["idxmin", "idxmax"] and keys == ["a1", "a2"]: + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + gb.agg([reduction_func], *args) + return + + result = gb.agg([reduction_func], *args) + expected = getattr(gb, reduction_func)(*args) + + if as_index and (test_series or reduction_func == "size"): + expected = expected.to_frame(reduction_func) + if not test_series: + expected.columns = MultiIndex.from_tuples( + [(ind, "") for ind in expected.columns[:-1]] + [("b", reduction_func)] + ) + elif not as_index: + expected.columns = keys + [reduction_func] + + tm.assert_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_counting.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_counting.py new file mode 100644 index 0000000000000000000000000000000000000000..16d7fe61b90ad3eece2d16345407d21fbece6962 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_counting.py @@ -0,0 +1,394 @@ +from itertools import product +from string import ascii_lowercase + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Index, + MultiIndex, + Period, + Series, + Timedelta, + Timestamp, + date_range, +) +import pandas._testing as tm + + +class TestCounting: + def test_cumcount(self): + df = DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"]) + g = df.groupby("A") + sg = g.A + + expected = Series([0, 1, 2, 0, 3]) + + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) + + def test_cumcount_empty(self): + ge = DataFrame().groupby(level=0) + se = Series(dtype=object).groupby(level=0) + + # edge case, as this is usually considered float + e = Series(dtype="int64") + + tm.assert_series_equal(e, ge.cumcount()) + tm.assert_series_equal(e, se.cumcount()) + + def test_cumcount_dupe_index(self): + df = DataFrame( + [["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5 + ) + g = df.groupby("A") + sg = g.A + + expected = Series([0, 1, 2, 0, 3], index=[0] * 5) + + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) + + def test_cumcount_mi(self): + mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]]) + df = DataFrame([["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=mi) + g = df.groupby("A") + sg = g.A + + expected = Series([0, 1, 2, 0, 3], index=mi) + + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) + + def test_cumcount_groupby_not_col(self): + df = DataFrame( + [["a"], ["a"], ["a"], ["b"], ["a"]], columns=["A"], index=[0] * 5 + ) + g = df.groupby([0, 0, 0, 1, 0]) + sg = g.A + + expected = Series([0, 1, 2, 0, 3], index=[0] * 5) + + tm.assert_series_equal(expected, g.cumcount()) + tm.assert_series_equal(expected, sg.cumcount()) + + def test_ngroup(self): + df = DataFrame({"A": list("aaaba")}) + g = df.groupby("A") + sg = g.A + + expected = Series([0, 0, 0, 1, 0]) + + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) + + def test_ngroup_distinct(self): + df = DataFrame({"A": list("abcde")}) + g = df.groupby("A") + sg = g.A + + expected = Series(range(5), dtype="int64") + + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) + + def test_ngroup_one_group(self): + df = DataFrame({"A": [0] * 5}) + g = df.groupby("A") + sg = g.A + + expected = Series([0] * 5) + + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) + + def test_ngroup_empty(self): + ge = DataFrame().groupby(level=0) + se = Series(dtype=object).groupby(level=0) + + # edge case, as this is usually considered float + e = Series(dtype="int64") + + tm.assert_series_equal(e, ge.ngroup()) + tm.assert_series_equal(e, se.ngroup()) + + def test_ngroup_series_matches_frame(self): + df = DataFrame({"A": list("aaaba")}) + s = Series(list("aaaba")) + + tm.assert_series_equal(df.groupby(s).ngroup(), s.groupby(s).ngroup()) + + def test_ngroup_dupe_index(self): + df = DataFrame({"A": list("aaaba")}, index=[0] * 5) + g = df.groupby("A") + sg = g.A + + expected = Series([0, 0, 0, 1, 0], index=[0] * 5) + + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) + + def test_ngroup_mi(self): + mi = MultiIndex.from_tuples([[0, 1], [1, 2], [2, 2], [2, 2], [1, 0]]) + df = DataFrame({"A": list("aaaba")}, index=mi) + g = df.groupby("A") + sg = g.A + expected = Series([0, 0, 0, 1, 0], index=mi) + + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) + + def test_ngroup_groupby_not_col(self): + df = DataFrame({"A": list("aaaba")}, index=[0] * 5) + g = df.groupby([0, 0, 0, 1, 0]) + sg = g.A + + expected = Series([0, 0, 0, 1, 0], index=[0] * 5) + + tm.assert_series_equal(expected, g.ngroup()) + tm.assert_series_equal(expected, sg.ngroup()) + + def test_ngroup_descending(self): + df = DataFrame(["a", "a", "b", "a", "b"], columns=["A"]) + g = df.groupby(["A"]) + + ascending = Series([0, 0, 1, 0, 1]) + descending = Series([1, 1, 0, 1, 0]) + + tm.assert_series_equal(descending, (g.ngroups - 1) - ascending) + tm.assert_series_equal(ascending, g.ngroup(ascending=True)) + tm.assert_series_equal(descending, g.ngroup(ascending=False)) + + def test_ngroup_matches_cumcount(self): + # verify one manually-worked out case works + df = DataFrame( + [["a", "x"], ["a", "y"], ["b", "x"], ["a", "x"], ["b", "y"]], + columns=["A", "X"], + ) + g = df.groupby(["A", "X"]) + g_ngroup = g.ngroup() + g_cumcount = g.cumcount() + expected_ngroup = Series([0, 1, 2, 0, 3]) + expected_cumcount = Series([0, 0, 0, 1, 0]) + + tm.assert_series_equal(g_ngroup, expected_ngroup) + tm.assert_series_equal(g_cumcount, expected_cumcount) + + def test_ngroup_cumcount_pair(self): + # brute force comparison for all small series + for p in product(range(3), repeat=4): + df = DataFrame({"a": p}) + g = df.groupby(["a"]) + + order = sorted(set(p)) + ngroupd = [order.index(val) for val in p] + cumcounted = [p[:i].count(val) for i, val in enumerate(p)] + + tm.assert_series_equal(g.ngroup(), Series(ngroupd)) + tm.assert_series_equal(g.cumcount(), Series(cumcounted)) + + def test_ngroup_respects_groupby_order(self, sort): + df = DataFrame({"a": np.random.default_rng(2).choice(list("abcdef"), 100)}) + g = df.groupby("a", sort=sort) + df["group_id"] = -1 + df["group_index"] = -1 + + for i, (_, group) in enumerate(g): + df.loc[group.index, "group_id"] = i + for j, ind in enumerate(group.index): + df.loc[ind, "group_index"] = j + + tm.assert_series_equal(Series(df["group_id"].values), g.ngroup()) + tm.assert_series_equal(Series(df["group_index"].values), g.cumcount()) + + @pytest.mark.parametrize( + "datetimelike", + [ + [Timestamp(f"2016-05-{i:02d} 20:09:25+00:00") for i in range(1, 4)], + [Timestamp(f"2016-05-{i:02d} 20:09:25") for i in range(1, 4)], + [Timestamp(f"2016-05-{i:02d} 20:09:25", tz="UTC") for i in range(1, 4)], + [Timedelta(x, unit="h") for x in range(1, 4)], + [Period(freq="2W", year=2017, month=x) for x in range(1, 4)], + ], + ) + def test_count_with_datetimelike(self, datetimelike): + # test for #13393, where DataframeGroupBy.count() fails + # when counting a datetimelike column. + + df = DataFrame({"x": ["a", "a", "b"], "y": datetimelike}) + res = df.groupby("x").count() + expected = DataFrame({"y": [2, 1]}, index=["a", "b"]) + expected.index.name = "x" + tm.assert_frame_equal(expected, res) + + def test_count_with_only_nans_in_first_group(self): + # GH21956 + df = DataFrame({"A": [np.nan, np.nan], "B": ["a", "b"], "C": [1, 2]}) + result = df.groupby(["A", "B"]).C.count() + mi = MultiIndex(levels=[[], ["a", "b"]], codes=[[], []], names=["A", "B"]) + expected = Series([], index=mi, dtype=np.int64, name="C") + tm.assert_series_equal(result, expected, check_index_type=False) + + def test_count_groupby_column_with_nan_in_groupby_column(self): + # https://github.com/pandas-dev/pandas/issues/32841 + df = DataFrame({"A": [1, 1, 1, 1, 1], "B": [5, 4, np.nan, 3, 0]}) + res = df.groupby(["B"]).count() + expected = DataFrame( + index=Index([0.0, 3.0, 4.0, 5.0], name="B"), data={"A": [1, 1, 1, 1]} + ) + tm.assert_frame_equal(expected, res) + + def test_groupby_count_dateparseerror(self): + dr = date_range(start="1/1/2012", freq="5min", periods=10) + + # BAD Example, datetimes first + ser = Series(np.arange(10), index=[dr, np.arange(10)]) + grouped = ser.groupby(lambda x: x[1] % 2 == 0) + result = grouped.count() + + ser = Series(np.arange(10), index=[np.arange(10), dr]) + grouped = ser.groupby(lambda x: x[0] % 2 == 0) + expected = grouped.count() + + tm.assert_series_equal(result, expected) + + +def test_groupby_timedelta_cython_count(): + df = DataFrame( + {"g": list("ab" * 2), "delta": np.arange(4).astype("timedelta64[ns]")} + ) + expected = Series([2, 2], index=Index(["a", "b"], name="g"), name="delta") + result = df.groupby("g").delta.count() + tm.assert_series_equal(expected, result) + + +def test_count(): + n = 1 << 15 + dr = date_range("2015-08-30", periods=n // 10, freq="min") + + df = DataFrame( + { + "1st": np.random.default_rng(2).choice(list(ascii_lowercase), n), + "2nd": np.random.default_rng(2).integers(0, 5, n), + "3rd": np.random.default_rng(2).standard_normal(n).round(3), + "4th": np.random.default_rng(2).integers(-10, 10, n), + "5th": np.random.default_rng(2).choice(dr, n), + "6th": np.random.default_rng(2).standard_normal(n).round(3), + "7th": np.random.default_rng(2).standard_normal(n).round(3), + "8th": np.random.default_rng(2).choice(dr, n) + - np.random.default_rng(2).choice(dr, 1), + "9th": np.random.default_rng(2).choice(list(ascii_lowercase), n), + } + ) + + for col in df.columns.drop(["1st", "2nd", "4th"]): + df.loc[np.random.default_rng(2).choice(n, n // 10), col] = np.nan + + df["9th"] = df["9th"].astype("category") + + for key in ["1st", "2nd", ["1st", "2nd"]]: + left = df.groupby(key).count() + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + right = df.groupby(key).apply(DataFrame.count).drop(key, axis=1) + tm.assert_frame_equal(left, right) + + +def test_count_non_nulls(): + # GH#5610 + # count counts non-nulls + df = DataFrame( + [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, np.nan]], + columns=["A", "B", "C"], + ) + + count_as = df.groupby("A").count() + count_not_as = df.groupby("A", as_index=False).count() + + expected = DataFrame([[1, 2], [0, 0]], columns=["B", "C"], index=[1, 3]) + expected.index.name = "A" + tm.assert_frame_equal(count_not_as, expected.reset_index()) + tm.assert_frame_equal(count_as, expected) + + count_B = df.groupby("A")["B"].count() + tm.assert_series_equal(count_B, expected["B"]) + + +def test_count_object(): + df = DataFrame({"a": ["a"] * 3 + ["b"] * 3, "c": [2] * 3 + [3] * 3}) + result = df.groupby("c").a.count() + expected = Series([3, 3], index=Index([2, 3], name="c"), name="a") + tm.assert_series_equal(result, expected) + + df = DataFrame({"a": ["a", np.nan, np.nan] + ["b"] * 3, "c": [2] * 3 + [3] * 3}) + result = df.groupby("c").a.count() + expected = Series([1, 3], index=Index([2, 3], name="c"), name="a") + tm.assert_series_equal(result, expected) + + +def test_count_cross_type(): + # GH8169 + # Set float64 dtype to avoid upcast when setting nan below + vals = np.hstack( + ( + np.random.default_rng(2).integers(0, 5, (100, 2)), + np.random.default_rng(2).integers(0, 2, (100, 2)), + ) + ).astype("float64") + + df = DataFrame(vals, columns=["a", "b", "c", "d"]) + df[df == 2] = np.nan + expected = df.groupby(["c", "d"]).count() + + for t in ["float32", "object"]: + df["a"] = df["a"].astype(t) + df["b"] = df["b"].astype(t) + result = df.groupby(["c", "d"]).count() + tm.assert_frame_equal(result, expected) + + +def test_lower_int_prec_count(): + df = DataFrame( + { + "a": np.array([0, 1, 2, 100], np.int8), + "b": np.array([1, 2, 3, 6], np.uint32), + "c": np.array([4, 5, 6, 8], np.int16), + "grp": list("ab" * 2), + } + ) + result = df.groupby("grp").count() + expected = DataFrame( + {"a": [2, 2], "b": [2, 2], "c": [2, 2]}, index=Index(list("ab"), name="grp") + ) + tm.assert_frame_equal(result, expected) + + +def test_count_uses_size_on_exception(): + class RaisingObjectException(Exception): + pass + + class RaisingObject: + def __init__(self, msg="I will raise inside Cython") -> None: + super().__init__() + self.msg = msg + + def __eq__(self, other): + # gets called in Cython to check that raising calls the method + raise RaisingObjectException(self.msg) + + df = DataFrame({"a": [RaisingObject() for _ in range(4)], "grp": list("ab" * 2)}) + result = df.groupby("grp").count() + expected = DataFrame({"a": [2, 2]}, index=Index(list("ab"), name="grp")) + tm.assert_frame_equal(result, expected) + + +def test_count_arrow_string_array(any_string_dtype): + # GH#54751 + pytest.importorskip("pyarrow") + df = DataFrame( + {"a": [1, 2, 3], "b": Series(["a", "b", "a"], dtype=any_string_dtype)} + ) + result = df.groupby("a").count() + expected = DataFrame({"b": 1}, index=Index([1, 2, 3], name="a")) + tm.assert_frame_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_cumulative.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_cumulative.py new file mode 100644 index 0000000000000000000000000000000000000000..1bdbef6d50c4c23db86060493dcd4f6df4bc4728 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_cumulative.py @@ -0,0 +1,319 @@ +import numpy as np +import pytest + +from pandas.errors import UnsupportedFunctionCall +import pandas.util._test_decorators as td + +import pandas as pd +from pandas import ( + DataFrame, + Series, +) +import pandas._testing as tm + + +@pytest.fixture( + params=[np.int32, np.int64, np.float32, np.float64, "Int64", "Float64"], + ids=["np.int32", "np.int64", "np.float32", "np.float64", "Int64", "Float64"], +) +def dtypes_for_minmax(request): + """ + Fixture of dtypes with min and max values used for testing + cummin and cummax + """ + dtype = request.param + + np_type = dtype + if dtype == "Int64": + np_type = np.int64 + elif dtype == "Float64": + np_type = np.float64 + + min_val = ( + np.iinfo(np_type).min + if np.dtype(np_type).kind == "i" + else np.finfo(np_type).min + ) + max_val = ( + np.iinfo(np_type).max + if np.dtype(np_type).kind == "i" + else np.finfo(np_type).max + ) + + return (dtype, min_val, max_val) + + +def test_groupby_cumprod(): + # GH 4095 + df = DataFrame({"key": ["b"] * 10, "value": 2}) + + actual = df.groupby("key")["value"].cumprod() + expected = df.groupby("key", group_keys=False)["value"].apply(lambda x: x.cumprod()) + expected.name = "value" + tm.assert_series_equal(actual, expected) + + df = DataFrame({"key": ["b"] * 100, "value": 2}) + df["value"] = df["value"].astype(float) + actual = df.groupby("key")["value"].cumprod() + expected = df.groupby("key", group_keys=False)["value"].apply(lambda x: x.cumprod()) + expected.name = "value" + tm.assert_series_equal(actual, expected) + + +@pytest.mark.skip_ubsan +def test_groupby_cumprod_overflow(): + # GH#37493 if we overflow we return garbage consistent with numpy + df = DataFrame({"key": ["b"] * 4, "value": 100_000}) + actual = df.groupby("key")["value"].cumprod() + expected = Series( + [100_000, 10_000_000_000, 1_000_000_000_000_000, 7766279631452241920], + name="value", + ) + tm.assert_series_equal(actual, expected) + + numpy_result = df.groupby("key", group_keys=False)["value"].apply( + lambda x: x.cumprod() + ) + numpy_result.name = "value" + tm.assert_series_equal(actual, numpy_result) + + +def test_groupby_cumprod_nan_influences_other_columns(): + # GH#48064 + df = DataFrame( + { + "a": 1, + "b": [1, np.nan, 2], + "c": [1, 2, 3.0], + } + ) + result = df.groupby("a").cumprod(numeric_only=True, skipna=False) + expected = DataFrame({"b": [1, np.nan, np.nan], "c": [1, 2, 6.0]}) + tm.assert_frame_equal(result, expected) + + +def test_cummin(dtypes_for_minmax): + dtype = dtypes_for_minmax[0] + min_val = dtypes_for_minmax[1] + + # GH 15048 + base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]}) + expected_mins = [3, 3, 3, 2, 2, 2, 2, 1] + + df = base_df.astype(dtype) + + expected = DataFrame({"B": expected_mins}).astype(dtype) + result = df.groupby("A").cummin() + tm.assert_frame_equal(result, expected) + result = df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame() + tm.assert_frame_equal(result, expected) + + # Test w/ min value for dtype + df.loc[[2, 6], "B"] = min_val + df.loc[[1, 5], "B"] = min_val + 1 + expected.loc[[2, 3, 6, 7], "B"] = min_val + expected.loc[[1, 5], "B"] = min_val + 1 # should not be rounded to min_val + result = df.groupby("A").cummin() + tm.assert_frame_equal(result, expected, check_exact=True) + expected = ( + df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame() + ) + tm.assert_frame_equal(result, expected, check_exact=True) + + # Test nan in some values + # Explicit cast to float to avoid implicit cast when setting nan + base_df = base_df.astype({"B": "float"}) + base_df.loc[[0, 2, 4, 6], "B"] = np.nan + expected = DataFrame({"B": [np.nan, 4, np.nan, 2, np.nan, 3, np.nan, 1]}) + result = base_df.groupby("A").cummin() + tm.assert_frame_equal(result, expected) + expected = ( + base_df.groupby("A", group_keys=False).B.apply(lambda x: x.cummin()).to_frame() + ) + tm.assert_frame_equal(result, expected) + + # GH 15561 + df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) + expected = Series(pd.to_datetime("2001"), index=[0], name="b") + + result = df.groupby("a")["b"].cummin() + tm.assert_series_equal(expected, result) + + # GH 15635 + df = DataFrame({"a": [1, 2, 1], "b": [1, 2, 2]}) + result = df.groupby("a").b.cummin() + expected = Series([1, 2, 1], name="b") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +@pytest.mark.parametrize("dtype", ["UInt64", "Int64", "Float64", "float", "boolean"]) +def test_cummin_max_all_nan_column(method, dtype): + base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [np.nan] * 8}) + base_df["B"] = base_df["B"].astype(dtype) + grouped = base_df.groupby("A") + + expected = DataFrame({"B": [np.nan] * 8}, dtype=dtype) + result = getattr(grouped, method)() + tm.assert_frame_equal(expected, result) + + result = getattr(grouped["B"], method)().to_frame() + tm.assert_frame_equal(expected, result) + + +def test_cummax(dtypes_for_minmax): + dtype = dtypes_for_minmax[0] + max_val = dtypes_for_minmax[2] + + # GH 15048 + base_df = DataFrame({"A": [1, 1, 1, 1, 2, 2, 2, 2], "B": [3, 4, 3, 2, 2, 3, 2, 1]}) + expected_maxs = [3, 4, 4, 4, 2, 3, 3, 3] + + df = base_df.astype(dtype) + + expected = DataFrame({"B": expected_maxs}).astype(dtype) + result = df.groupby("A").cummax() + tm.assert_frame_equal(result, expected) + result = df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame() + tm.assert_frame_equal(result, expected) + + # Test w/ max value for dtype + df.loc[[2, 6], "B"] = max_val + expected.loc[[2, 3, 6, 7], "B"] = max_val + result = df.groupby("A").cummax() + tm.assert_frame_equal(result, expected) + expected = ( + df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame() + ) + tm.assert_frame_equal(result, expected) + + # Test nan in some values + # Explicit cast to float to avoid implicit cast when setting nan + base_df = base_df.astype({"B": "float"}) + base_df.loc[[0, 2, 4, 6], "B"] = np.nan + expected = DataFrame({"B": [np.nan, 4, np.nan, 4, np.nan, 3, np.nan, 3]}) + result = base_df.groupby("A").cummax() + tm.assert_frame_equal(result, expected) + expected = ( + base_df.groupby("A", group_keys=False).B.apply(lambda x: x.cummax()).to_frame() + ) + tm.assert_frame_equal(result, expected) + + # GH 15561 + df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) + expected = Series(pd.to_datetime("2001"), index=[0], name="b") + + result = df.groupby("a")["b"].cummax() + tm.assert_series_equal(expected, result) + + # GH 15635 + df = DataFrame({"a": [1, 2, 1], "b": [2, 1, 1]}) + result = df.groupby("a").b.cummax() + expected = Series([2, 1, 2], name="b") + tm.assert_series_equal(result, expected) + + +def test_cummax_i8_at_implementation_bound(): + # the minimum value used to be treated as NPY_NAT+1 instead of NPY_NAT + # for int64 dtype GH#46382 + ser = Series([pd.NaT._value + n for n in range(5)]) + df = DataFrame({"A": 1, "B": ser, "C": ser._values.view("M8[ns]")}) + gb = df.groupby("A") + + res = gb.cummax() + exp = df[["B", "C"]] + tm.assert_frame_equal(res, exp) + + +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +@pytest.mark.parametrize("dtype", ["float", "Int64", "Float64"]) +@pytest.mark.parametrize( + "groups,expected_data", + [ + ([1, 1, 1], [1, None, None]), + ([1, 2, 3], [1, None, 2]), + ([1, 3, 3], [1, None, None]), + ], +) +def test_cummin_max_skipna(method, dtype, groups, expected_data): + # GH-34047 + df = DataFrame({"a": Series([1, None, 2], dtype=dtype)}) + orig = df.copy() + gb = df.groupby(groups)["a"] + + result = getattr(gb, method)(skipna=False) + expected = Series(expected_data, dtype=dtype, name="a") + + # check we didn't accidentally alter df + tm.assert_frame_equal(df, orig) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +def test_cummin_max_skipna_multiple_cols(method): + # Ensure missing value in "a" doesn't cause "b" to be nan-filled + df = DataFrame({"a": [np.nan, 2.0, 2.0], "b": [2.0, 2.0, 2.0]}) + gb = df.groupby([1, 1, 1])[["a", "b"]] + + result = getattr(gb, method)(skipna=False) + expected = DataFrame({"a": [np.nan, np.nan, np.nan], "b": [2.0, 2.0, 2.0]}) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["cumprod", "cumsum"]) +def test_numpy_compat(func): + # see gh-12811 + df = DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]}) + g = df.groupby("A") + + msg = "numpy operations are not valid with groupby" + + with pytest.raises(UnsupportedFunctionCall, match=msg): + getattr(g, func)(1, 2, 3) + with pytest.raises(UnsupportedFunctionCall, match=msg): + getattr(g, func)(foo=1) + + +@td.skip_if_32bit +@pytest.mark.parametrize("method", ["cummin", "cummax"]) +@pytest.mark.parametrize( + "dtype,val", [("UInt64", np.iinfo("uint64").max), ("Int64", 2**53 + 1)] +) +def test_nullable_int_not_cast_as_float(method, dtype, val): + data = [val, pd.NA] + df = DataFrame({"grp": [1, 1], "b": data}, dtype=dtype) + grouped = df.groupby("grp") + + result = grouped.transform(method) + expected = DataFrame({"b": data}, dtype=dtype) + + tm.assert_frame_equal(result, expected) + + +def test_cython_api2(): + # this takes the fast apply path + + # cumsum (GH5614) + df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"]) + expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"]) + result = df.groupby("A").cumsum() + tm.assert_frame_equal(result, expected) + + # GH 5755 - cumsum is a transformer and should ignore as_index + result = df.groupby("A", as_index=False).cumsum() + tm.assert_frame_equal(result, expected) + + # GH 13994 + msg = "DataFrameGroupBy.cumsum with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").cumsum(axis=1) + expected = df.cumsum(axis=1) + tm.assert_frame_equal(result, expected) + + msg = "DataFrameGroupBy.cumprod with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").cumprod(axis=1) + expected = df.cumprod(axis=1) + tm.assert_frame_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_filters.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..309c4b7b57e84f68e13ed974790c87c16244aae7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_filters.py @@ -0,0 +1,636 @@ +from string import ascii_lowercase + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Series, + Timestamp, +) +import pandas._testing as tm + + +def test_filter_series(): + s = Series([1, 3, 20, 5, 22, 24, 7]) + expected_odd = Series([1, 3, 5, 7], index=[0, 1, 3, 6]) + expected_even = Series([20, 22, 24], index=[2, 4, 5]) + grouper = s.apply(lambda x: x % 2) + grouped = s.groupby(grouper) + tm.assert_series_equal(grouped.filter(lambda x: x.mean() < 10), expected_odd) + tm.assert_series_equal(grouped.filter(lambda x: x.mean() > 10), expected_even) + # Test dropna=False. + tm.assert_series_equal( + grouped.filter(lambda x: x.mean() < 10, dropna=False), + expected_odd.reindex(s.index), + ) + tm.assert_series_equal( + grouped.filter(lambda x: x.mean() > 10, dropna=False), + expected_even.reindex(s.index), + ) + + +def test_filter_single_column_df(): + df = DataFrame([1, 3, 20, 5, 22, 24, 7]) + expected_odd = DataFrame([1, 3, 5, 7], index=[0, 1, 3, 6]) + expected_even = DataFrame([20, 22, 24], index=[2, 4, 5]) + grouper = df[0].apply(lambda x: x % 2) + grouped = df.groupby(grouper) + tm.assert_frame_equal(grouped.filter(lambda x: x.mean() < 10), expected_odd) + tm.assert_frame_equal(grouped.filter(lambda x: x.mean() > 10), expected_even) + # Test dropna=False. + tm.assert_frame_equal( + grouped.filter(lambda x: x.mean() < 10, dropna=False), + expected_odd.reindex(df.index), + ) + tm.assert_frame_equal( + grouped.filter(lambda x: x.mean() > 10, dropna=False), + expected_even.reindex(df.index), + ) + + +def test_filter_multi_column_df(): + df = DataFrame({"A": [1, 12, 12, 1], "B": [1, 1, 1, 1]}) + grouper = df["A"].apply(lambda x: x % 2) + grouped = df.groupby(grouper) + expected = DataFrame({"A": [12, 12], "B": [1, 1]}, index=[1, 2]) + tm.assert_frame_equal( + grouped.filter(lambda x: x["A"].sum() - x["B"].sum() > 10), expected + ) + + +def test_filter_mixed_df(): + df = DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()}) + grouper = df["A"].apply(lambda x: x % 2) + grouped = df.groupby(grouper) + expected = DataFrame({"A": [12, 12], "B": ["b", "c"]}, index=[1, 2]) + tm.assert_frame_equal(grouped.filter(lambda x: x["A"].sum() > 10), expected) + + +def test_filter_out_all_groups(): + s = Series([1, 3, 20, 5, 22, 24, 7]) + grouper = s.apply(lambda x: x % 2) + grouped = s.groupby(grouper) + tm.assert_series_equal(grouped.filter(lambda x: x.mean() > 1000), s[[]]) + df = DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()}) + grouper = df["A"].apply(lambda x: x % 2) + grouped = df.groupby(grouper) + tm.assert_frame_equal(grouped.filter(lambda x: x["A"].sum() > 1000), df.loc[[]]) + + +def test_filter_out_no_groups(): + s = Series([1, 3, 20, 5, 22, 24, 7]) + grouper = s.apply(lambda x: x % 2) + grouped = s.groupby(grouper) + filtered = grouped.filter(lambda x: x.mean() > 0) + tm.assert_series_equal(filtered, s) + df = DataFrame({"A": [1, 12, 12, 1], "B": "a b c d".split()}) + grouper = df["A"].apply(lambda x: x % 2) + grouped = df.groupby(grouper) + filtered = grouped.filter(lambda x: x["A"].mean() > 0) + tm.assert_frame_equal(filtered, df) + + +def test_filter_out_all_groups_in_df(): + # GH12768 + df = DataFrame({"a": [1, 1, 2], "b": [1, 2, 0]}) + res = df.groupby("a") + res = res.filter(lambda x: x["b"].sum() > 5, dropna=False) + expected = DataFrame({"a": [np.nan] * 3, "b": [np.nan] * 3}) + tm.assert_frame_equal(expected, res) + + df = DataFrame({"a": [1, 1, 2], "b": [1, 2, 0]}) + res = df.groupby("a") + res = res.filter(lambda x: x["b"].sum() > 5, dropna=True) + expected = DataFrame({"a": [], "b": []}, dtype="int64") + tm.assert_frame_equal(expected, res) + + +def test_filter_condition_raises(): + def raise_if_sum_is_zero(x): + if x.sum() == 0: + raise ValueError + return x.sum() > 0 + + s = Series([-1, 0, 1, 2]) + grouper = s.apply(lambda x: x % 2) + grouped = s.groupby(grouper) + msg = "the filter must return a boolean result" + with pytest.raises(TypeError, match=msg): + grouped.filter(raise_if_sum_is_zero) + + +def test_filter_with_axis_in_groupby(): + # issue 11041 + index = pd.MultiIndex.from_product([range(10), [0, 1]]) + data = DataFrame(np.arange(100).reshape(-1, 20), columns=index, dtype="int64") + + msg = "DataFrame.groupby with axis=1" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = data.groupby(level=0, axis=1) + result = gb.filter(lambda x: x.iloc[0, 0] > 10) + expected = data.iloc[:, 12:20] + tm.assert_frame_equal(result, expected) + + +def test_filter_bad_shapes(): + df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)}) + s = df["B"] + g_df = df.groupby("B") + g_s = s.groupby(s) + + f = lambda x: x + msg = "filter function returned a DataFrame, but expected a scalar bool" + with pytest.raises(TypeError, match=msg): + g_df.filter(f) + msg = "the filter must return a boolean result" + with pytest.raises(TypeError, match=msg): + g_s.filter(f) + + f = lambda x: x == 1 + msg = "filter function returned a DataFrame, but expected a scalar bool" + with pytest.raises(TypeError, match=msg): + g_df.filter(f) + msg = "the filter must return a boolean result" + with pytest.raises(TypeError, match=msg): + g_s.filter(f) + + f = lambda x: np.outer(x, x) + msg = "can't multiply sequence by non-int of type 'str'" + with pytest.raises(TypeError, match=msg): + g_df.filter(f) + msg = "the filter must return a boolean result" + with pytest.raises(TypeError, match=msg): + g_s.filter(f) + + +def test_filter_nan_is_false(): + df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)}) + s = df["B"] + g_df = df.groupby(df["B"]) + g_s = s.groupby(s) + + f = lambda x: np.nan + tm.assert_frame_equal(g_df.filter(f), df.loc[[]]) + tm.assert_series_equal(g_s.filter(f), s[[]]) + + +def test_filter_pdna_is_false(): + # in particular, dont raise in filter trying to call bool(pd.NA) + df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)}) + ser = df["B"] + g_df = df.groupby(df["B"]) + g_s = ser.groupby(ser) + + func = lambda x: pd.NA + res = g_df.filter(func) + tm.assert_frame_equal(res, df.loc[[]]) + res = g_s.filter(func) + tm.assert_series_equal(res, ser[[]]) + + +def test_filter_against_workaround_ints(): + # Series of ints + s = Series(np.random.default_rng(2).integers(0, 100, 100)) + grouper = s.apply(lambda x: np.round(x, -1)) + grouped = s.groupby(grouper) + f = lambda x: x.mean() > 10 + + old_way = s[grouped.transform(f).astype("bool")] + new_way = grouped.filter(f) + tm.assert_series_equal(new_way.sort_values(), old_way.sort_values()) + + +def test_filter_against_workaround_floats(): + # Series of floats + s = 100 * Series(np.random.default_rng(2).random(100)) + grouper = s.apply(lambda x: np.round(x, -1)) + grouped = s.groupby(grouper) + f = lambda x: x.mean() > 10 + old_way = s[grouped.transform(f).astype("bool")] + new_way = grouped.filter(f) + tm.assert_series_equal(new_way.sort_values(), old_way.sort_values()) + + +def test_filter_against_workaround_dataframe(): + # Set up DataFrame of ints, floats, strings. + letters = np.array(list(ascii_lowercase)) + N = 100 + random_letters = letters.take( + np.random.default_rng(2).integers(0, 26, N, dtype=int) + ) + df = DataFrame( + { + "ints": Series(np.random.default_rng(2).integers(0, 100, N)), + "floats": N / 10 * Series(np.random.default_rng(2).random(N)), + "letters": Series(random_letters), + } + ) + + # Group by ints; filter on floats. + grouped = df.groupby("ints") + old_way = df[grouped.floats.transform(lambda x: x.mean() > N / 20).astype("bool")] + new_way = grouped.filter(lambda x: x["floats"].mean() > N / 20) + tm.assert_frame_equal(new_way, old_way) + + # Group by floats (rounded); filter on strings. + grouper = df.floats.apply(lambda x: np.round(x, -1)) + grouped = df.groupby(grouper) + old_way = df[grouped.letters.transform(lambda x: len(x) < N / 10).astype("bool")] + new_way = grouped.filter(lambda x: len(x.letters) < N / 10) + tm.assert_frame_equal(new_way, old_way) + + # Group by strings; filter on ints. + grouped = df.groupby("letters") + old_way = df[grouped.ints.transform(lambda x: x.mean() > N / 20).astype("bool")] + new_way = grouped.filter(lambda x: x["ints"].mean() > N / 20) + tm.assert_frame_equal(new_way, old_way) + + +def test_filter_using_len(): + # BUG GH4447 + df = DataFrame({"A": np.arange(8), "B": list("aabbbbcc"), "C": np.arange(8)}) + grouped = df.groupby("B") + actual = grouped.filter(lambda x: len(x) > 2) + expected = DataFrame( + {"A": np.arange(2, 6), "B": list("bbbb"), "C": np.arange(2, 6)}, + index=np.arange(2, 6, dtype=np.int64), + ) + tm.assert_frame_equal(actual, expected) + + actual = grouped.filter(lambda x: len(x) > 4) + expected = df.loc[[]] + tm.assert_frame_equal(actual, expected) + + # Series have always worked properly, but we'll test anyway. + s = df["B"] + grouped = s.groupby(s) + actual = grouped.filter(lambda x: len(x) > 2) + expected = Series(4 * ["b"], index=np.arange(2, 6, dtype=np.int64), name="B") + tm.assert_series_equal(actual, expected) + + actual = grouped.filter(lambda x: len(x) > 4) + expected = s[[]] + tm.assert_series_equal(actual, expected) + + +def test_filter_maintains_ordering(): + # Simple case: index is sequential. #4621 + df = DataFrame( + {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]} + ) + s = df["pid"] + grouped = df.groupby("tag") + actual = grouped.filter(lambda x: len(x) > 1) + expected = df.iloc[[1, 2, 4, 7]] + tm.assert_frame_equal(actual, expected) + + grouped = s.groupby(df["tag"]) + actual = grouped.filter(lambda x: len(x) > 1) + expected = s.iloc[[1, 2, 4, 7]] + tm.assert_series_equal(actual, expected) + + # Now index is sequentially decreasing. + df.index = np.arange(len(df) - 1, -1, -1) + s = df["pid"] + grouped = df.groupby("tag") + actual = grouped.filter(lambda x: len(x) > 1) + expected = df.iloc[[1, 2, 4, 7]] + tm.assert_frame_equal(actual, expected) + + grouped = s.groupby(df["tag"]) + actual = grouped.filter(lambda x: len(x) > 1) + expected = s.iloc[[1, 2, 4, 7]] + tm.assert_series_equal(actual, expected) + + # Index is shuffled. + SHUFFLED = [4, 6, 7, 2, 1, 0, 5, 3] + df.index = df.index[SHUFFLED] + s = df["pid"] + grouped = df.groupby("tag") + actual = grouped.filter(lambda x: len(x) > 1) + expected = df.iloc[[1, 2, 4, 7]] + tm.assert_frame_equal(actual, expected) + + grouped = s.groupby(df["tag"]) + actual = grouped.filter(lambda x: len(x) > 1) + expected = s.iloc[[1, 2, 4, 7]] + tm.assert_series_equal(actual, expected) + + +def test_filter_multiple_timestamp(): + # GH 10114 + df = DataFrame( + { + "A": np.arange(5, dtype="int64"), + "B": ["foo", "bar", "foo", "bar", "bar"], + "C": Timestamp("20130101"), + } + ) + + grouped = df.groupby(["B", "C"]) + + result = grouped["A"].filter(lambda x: True) + tm.assert_series_equal(df["A"], result) + + result = grouped["A"].transform(len) + expected = Series([2, 3, 2, 3, 3], name="A") + tm.assert_series_equal(result, expected) + + result = grouped.filter(lambda x: True) + tm.assert_frame_equal(df, result) + + result = grouped.transform("sum") + expected = DataFrame({"A": [2, 8, 2, 8, 8]}) + tm.assert_frame_equal(result, expected) + + result = grouped.transform(len) + expected = DataFrame({"A": [2, 3, 2, 3, 3]}) + tm.assert_frame_equal(result, expected) + + +def test_filter_and_transform_with_non_unique_int_index(): + # GH4620 + index = [1, 1, 1, 2, 1, 1, 0, 1] + df = DataFrame( + {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}, + index=index, + ) + grouped_df = df.groupby("tag") + ser = df["pid"] + grouped_ser = ser.groupby(df["tag"]) + expected_indexes = [1, 2, 4, 7] + + # Filter DataFrame + actual = grouped_df.filter(lambda x: len(x) > 1) + expected = df.iloc[expected_indexes] + tm.assert_frame_equal(actual, expected) + + actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False) + # Cast to avoid upcast when setting nan below + expected = df.copy().astype("float64") + expected.iloc[[0, 3, 5, 6]] = np.nan + tm.assert_frame_equal(actual, expected) + + # Filter Series + actual = grouped_ser.filter(lambda x: len(x) > 1) + expected = ser.take(expected_indexes) + tm.assert_series_equal(actual, expected) + + actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") + # ^ made manually because this can get confusing! + tm.assert_series_equal(actual, expected) + + # Transform Series + actual = grouped_ser.transform(len) + expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid") + tm.assert_series_equal(actual, expected) + + # Transform (a column from) DataFrameGroupBy + actual = grouped_df.pid.transform(len) + tm.assert_series_equal(actual, expected) + + +def test_filter_and_transform_with_multiple_non_unique_int_index(): + # GH4620 + index = [1, 1, 1, 2, 0, 0, 0, 1] + df = DataFrame( + {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}, + index=index, + ) + grouped_df = df.groupby("tag") + ser = df["pid"] + grouped_ser = ser.groupby(df["tag"]) + expected_indexes = [1, 2, 4, 7] + + # Filter DataFrame + actual = grouped_df.filter(lambda x: len(x) > 1) + expected = df.iloc[expected_indexes] + tm.assert_frame_equal(actual, expected) + + actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False) + # Cast to avoid upcast when setting nan below + expected = df.copy().astype("float64") + expected.iloc[[0, 3, 5, 6]] = np.nan + tm.assert_frame_equal(actual, expected) + + # Filter Series + actual = grouped_ser.filter(lambda x: len(x) > 1) + expected = ser.take(expected_indexes) + tm.assert_series_equal(actual, expected) + + actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") + # ^ made manually because this can get confusing! + tm.assert_series_equal(actual, expected) + + # Transform Series + actual = grouped_ser.transform(len) + expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid") + tm.assert_series_equal(actual, expected) + + # Transform (a column from) DataFrameGroupBy + actual = grouped_df.pid.transform(len) + tm.assert_series_equal(actual, expected) + + +def test_filter_and_transform_with_non_unique_float_index(): + # GH4620 + index = np.array([1, 1, 1, 2, 1, 1, 0, 1], dtype=float) + df = DataFrame( + {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}, + index=index, + ) + grouped_df = df.groupby("tag") + ser = df["pid"] + grouped_ser = ser.groupby(df["tag"]) + expected_indexes = [1, 2, 4, 7] + + # Filter DataFrame + actual = grouped_df.filter(lambda x: len(x) > 1) + expected = df.iloc[expected_indexes] + tm.assert_frame_equal(actual, expected) + + actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False) + # Cast to avoid upcast when setting nan below + expected = df.copy().astype("float64") + expected.iloc[[0, 3, 5, 6]] = np.nan + tm.assert_frame_equal(actual, expected) + + # Filter Series + actual = grouped_ser.filter(lambda x: len(x) > 1) + expected = ser.take(expected_indexes) + tm.assert_series_equal(actual, expected) + + actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") + # ^ made manually because this can get confusing! + tm.assert_series_equal(actual, expected) + + # Transform Series + actual = grouped_ser.transform(len) + expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid") + tm.assert_series_equal(actual, expected) + + # Transform (a column from) DataFrameGroupBy + actual = grouped_df.pid.transform(len) + tm.assert_series_equal(actual, expected) + + +def test_filter_and_transform_with_non_unique_timestamp_index(): + # GH4620 + t0 = Timestamp("2013-09-30 00:05:00") + t1 = Timestamp("2013-10-30 00:05:00") + t2 = Timestamp("2013-11-30 00:05:00") + index = [t1, t1, t1, t2, t1, t1, t0, t1] + df = DataFrame( + {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}, + index=index, + ) + grouped_df = df.groupby("tag") + ser = df["pid"] + grouped_ser = ser.groupby(df["tag"]) + expected_indexes = [1, 2, 4, 7] + + # Filter DataFrame + actual = grouped_df.filter(lambda x: len(x) > 1) + expected = df.iloc[expected_indexes] + tm.assert_frame_equal(actual, expected) + + actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False) + # Cast to avoid upcast when setting nan below + expected = df.copy().astype("float64") + expected.iloc[[0, 3, 5, 6]] = np.nan + tm.assert_frame_equal(actual, expected) + + # Filter Series + actual = grouped_ser.filter(lambda x: len(x) > 1) + expected = ser.take(expected_indexes) + tm.assert_series_equal(actual, expected) + + actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") + # ^ made manually because this can get confusing! + tm.assert_series_equal(actual, expected) + + # Transform Series + actual = grouped_ser.transform(len) + expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid") + tm.assert_series_equal(actual, expected) + + # Transform (a column from) DataFrameGroupBy + actual = grouped_df.pid.transform(len) + tm.assert_series_equal(actual, expected) + + +def test_filter_and_transform_with_non_unique_string_index(): + # GH4620 + index = list("bbbcbbab") + df = DataFrame( + {"pid": [1, 1, 1, 2, 2, 3, 3, 3], "tag": [23, 45, 62, 24, 45, 34, 25, 62]}, + index=index, + ) + grouped_df = df.groupby("tag") + ser = df["pid"] + grouped_ser = ser.groupby(df["tag"]) + expected_indexes = [1, 2, 4, 7] + + # Filter DataFrame + actual = grouped_df.filter(lambda x: len(x) > 1) + expected = df.iloc[expected_indexes] + tm.assert_frame_equal(actual, expected) + + actual = grouped_df.filter(lambda x: len(x) > 1, dropna=False) + # Cast to avoid upcast when setting nan below + expected = df.copy().astype("float64") + expected.iloc[[0, 3, 5, 6]] = np.nan + tm.assert_frame_equal(actual, expected) + + # Filter Series + actual = grouped_ser.filter(lambda x: len(x) > 1) + expected = ser.take(expected_indexes) + tm.assert_series_equal(actual, expected) + + actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") + # ^ made manually because this can get confusing! + tm.assert_series_equal(actual, expected) + + # Transform Series + actual = grouped_ser.transform(len) + expected = Series([1, 2, 2, 1, 2, 1, 1, 2], index, name="pid") + tm.assert_series_equal(actual, expected) + + # Transform (a column from) DataFrameGroupBy + actual = grouped_df.pid.transform(len) + tm.assert_series_equal(actual, expected) + + +def test_filter_has_access_to_grouped_cols(): + df = DataFrame([[1, 2], [1, 3], [5, 6]], columns=["A", "B"]) + g = df.groupby("A") + # previously didn't have access to col A #???? + filt = g.filter(lambda x: x["A"].sum() == 2) + tm.assert_frame_equal(filt, df.iloc[[0, 1]]) + + +def test_filter_enforces_scalarness(): + df = DataFrame( + [ + ["best", "a", "x"], + ["worst", "b", "y"], + ["best", "c", "x"], + ["best", "d", "y"], + ["worst", "d", "y"], + ["worst", "d", "y"], + ["best", "d", "z"], + ], + columns=["a", "b", "c"], + ) + with pytest.raises(TypeError, match="filter function returned a.*"): + df.groupby("c").filter(lambda g: g["a"] == "best") + + +def test_filter_non_bool_raises(): + df = DataFrame( + [ + ["best", "a", 1], + ["worst", "b", 1], + ["best", "c", 1], + ["best", "d", 1], + ["worst", "d", 1], + ["worst", "d", 1], + ["best", "d", 1], + ], + columns=["a", "b", "c"], + ) + with pytest.raises(TypeError, match="filter function returned a.*"): + df.groupby("a").filter(lambda g: g.c.mean()) + + +def test_filter_dropna_with_empty_groups(): + # GH 10780 + data = Series(np.random.default_rng(2).random(9), index=np.repeat([1, 2, 3], 3)) + grouped = data.groupby(level=0) + result_false = grouped.filter(lambda x: x.mean() > 1, dropna=False) + expected_false = Series([np.nan] * 9, index=np.repeat([1, 2, 3], 3)) + tm.assert_series_equal(result_false, expected_false) + + result_true = grouped.filter(lambda x: x.mean() > 1, dropna=True) + expected_true = Series(index=pd.Index([], dtype=int), dtype=np.float64) + tm.assert_series_equal(result_true, expected_true) + + +def test_filter_consistent_result_before_after_agg_func(): + # GH 17091 + df = DataFrame({"data": range(6), "key": list("ABCABC")}) + grouper = df.groupby("key") + result = grouper.filter(lambda x: True) + expected = DataFrame({"data": range(6), "key": list("ABCABC")}) + tm.assert_frame_equal(result, expected) + + grouper.sum() + result = grouper.filter(lambda x: True) + tm.assert_frame_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby.py new file mode 100644 index 0000000000000000000000000000000000000000..7ebecdafdc8aede3f2851b9d82f3de6669034719 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby.py @@ -0,0 +1,3363 @@ +from datetime import datetime +import decimal +from decimal import Decimal +import re + +import numpy as np +import pytest + +from pandas.errors import ( + PerformanceWarning, + SpecificationError, +) +import pandas.util._test_decorators as td + +import pandas as pd +from pandas import ( + Categorical, + DataFrame, + Grouper, + Index, + Interval, + MultiIndex, + RangeIndex, + Series, + Timedelta, + Timestamp, + date_range, + to_datetime, +) +import pandas._testing as tm +from pandas.core.arrays import BooleanArray +import pandas.core.common as com + +pytestmark = pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning") + + +def test_repr(): + # GH18203 + result = repr(Grouper(key="A", level="B")) + expected = "Grouper(key='A', level='B', axis=0, sort=False, dropna=True)" + assert result == expected + + +def test_groupby_std_datetimelike(warn_copy_on_write): + # GH#48481 + tdi = pd.timedelta_range("1 Day", periods=10000) + ser = Series(tdi) + ser[::5] *= 2 # get different std for different groups + + df = ser.to_frame("A").copy() + + df["B"] = ser + Timestamp(0) + df["C"] = ser + Timestamp(0, tz="UTC") + df.iloc[-1] = pd.NaT # last group includes NaTs + + gb = df.groupby(list(range(5)) * 2000) + + result = gb.std() + + # Note: this does not _exactly_ match what we would get if we did + # [gb.get_group(i).std() for i in gb.groups] + # but it _does_ match the floating point error we get doing the + # same operation on int64 data xref GH#51332 + td1 = Timedelta("2887 days 11:21:02.326710176") + td4 = Timedelta("2886 days 00:42:34.664668096") + exp_ser = Series([td1 * 2, td1, td1, td1, td4], index=np.arange(5)) + expected = DataFrame({"A": exp_ser, "B": exp_ser, "C": exp_ser}) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"]) +def test_basic_aggregations(dtype): + data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype) + + index = np.arange(9) + np.random.default_rng(2).shuffle(index) + data = data.reindex(index) + + grouped = data.groupby(lambda x: x // 3, group_keys=False) + + for k, v in grouped: + assert len(v) == 3 + + msg = "using SeriesGroupBy.mean" + with tm.assert_produces_warning(FutureWarning, match=msg): + agged = grouped.aggregate(np.mean) + assert agged[1] == 1 + + msg = "using SeriesGroupBy.mean" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = grouped.agg(np.mean) + tm.assert_series_equal(agged, expected) # shorthand + tm.assert_series_equal(agged, grouped.mean()) + result = grouped.sum() + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = grouped.agg(np.sum) + tm.assert_series_equal(result, expected) + + expected = grouped.apply(lambda x: x * x.sum()) + transformed = grouped.transform(lambda x: x * x.sum()) + assert transformed[7] == 12 + tm.assert_series_equal(transformed, expected) + + value_grouped = data.groupby(data) + msg = "using SeriesGroupBy.mean" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = value_grouped.aggregate(np.mean) + tm.assert_series_equal(result, agged, check_index_type=False) + + # complex agg + msg = "using SeriesGroupBy.[mean|std]" + with tm.assert_produces_warning(FutureWarning, match=msg): + agged = grouped.aggregate([np.mean, np.std]) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + grouped.aggregate({"one": np.mean, "two": np.std}) + + group_constants = {0: 10, 1: 20, 2: 30} + msg = ( + "Pinning the groupby key to each group in SeriesGroupBy.agg is deprecated, " + "and cases that relied on it will raise in a future version" + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#41090 + agged = grouped.agg(lambda x: group_constants[x.name] + x.mean()) + assert agged[1] == 21 + + # corner cases + msg = "Must produce aggregated value" + # exception raised is type Exception + with pytest.raises(Exception, match=msg): + grouped.aggregate(lambda x: x * 2) + + +def test_groupby_nonobject_dtype(multiindex_dataframe_random_data): + key = multiindex_dataframe_random_data.index.codes[0] + grouped = multiindex_dataframe_random_data.groupby(key) + result = grouped.sum() + + expected = multiindex_dataframe_random_data.groupby(key.astype("O")).sum() + assert result.index.dtype == np.int8 + assert expected.index.dtype == np.int64 + tm.assert_frame_equal(result, expected, check_index_type=False) + + +def test_groupby_nonobject_dtype_mixed(): + # GH 3911, mixed frame non-conversion + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.default_rng(2).standard_normal(8), + "D": np.array(np.random.default_rng(2).standard_normal(8), dtype="float32"), + } + ) + df["value"] = range(len(df)) + + def max_value(group): + return group.loc[group["value"].idxmax()] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + applied = df.groupby("A").apply(max_value) + result = applied.dtypes + expected = df.dtypes + tm.assert_series_equal(result, expected) + + +def test_inconsistent_return_type(): + # GH5592 + # inconsistent return type + df = DataFrame( + { + "A": ["Tiger", "Tiger", "Tiger", "Lamb", "Lamb", "Pony", "Pony"], + "B": Series(np.arange(7), dtype="int64"), + "C": date_range("20130101", periods=7), + } + ) + + def f_0(grp): + return grp.iloc[0] + + expected = df.groupby("A").first()[["B"]] + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(f_0)[["B"]] + tm.assert_frame_equal(result, expected) + + def f_1(grp): + if grp.name == "Tiger": + return None + return grp.iloc[0] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(f_1)[["B"]] + e = expected.copy() + e.loc["Tiger"] = np.nan + tm.assert_frame_equal(result, e) + + def f_2(grp): + if grp.name == "Pony": + return None + return grp.iloc[0] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(f_2)[["B"]] + e = expected.copy() + e.loc["Pony"] = np.nan + tm.assert_frame_equal(result, e) + + # 5592 revisited, with datetimes + def f_3(grp): + if grp.name == "Pony": + return None + return grp.iloc[0] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(f_3)[["C"]] + e = df.groupby("A").first()[["C"]] + e.loc["Pony"] = pd.NaT + tm.assert_frame_equal(result, e) + + # scalar outputs + def f_4(grp): + if grp.name == "Pony": + return None + return grp.iloc[0].loc["C"] + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").apply(f_4) + e = df.groupby("A").first()["C"].copy() + e.loc["Pony"] = np.nan + e.name = None + tm.assert_series_equal(result, e) + + +def test_pass_args_kwargs(ts, tsframe): + def f(x, q=None, axis=0): + return np.percentile(x, q, axis=axis) + + g = lambda x: np.percentile(x, 80, axis=0) + + # Series + ts_grouped = ts.groupby(lambda x: x.month) + agg_result = ts_grouped.agg(np.percentile, 80, axis=0) + apply_result = ts_grouped.apply(np.percentile, 80, axis=0) + trans_result = ts_grouped.transform(np.percentile, 80, axis=0) + + agg_expected = ts_grouped.quantile(0.8) + trans_expected = ts_grouped.transform(g) + + tm.assert_series_equal(apply_result, agg_expected) + tm.assert_series_equal(agg_result, agg_expected) + tm.assert_series_equal(trans_result, trans_expected) + + agg_result = ts_grouped.agg(f, q=80) + apply_result = ts_grouped.apply(f, q=80) + trans_result = ts_grouped.transform(f, q=80) + tm.assert_series_equal(agg_result, agg_expected) + tm.assert_series_equal(apply_result, agg_expected) + tm.assert_series_equal(trans_result, trans_expected) + + # DataFrame + for as_index in [True, False]: + df_grouped = tsframe.groupby(lambda x: x.month, as_index=as_index) + warn = None if as_index else FutureWarning + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(warn, match=msg): + agg_result = df_grouped.agg(np.percentile, 80, axis=0) + with tm.assert_produces_warning(warn, match=msg): + apply_result = df_grouped.apply(DataFrame.quantile, 0.8) + with tm.assert_produces_warning(warn, match=msg): + expected = df_grouped.quantile(0.8) + tm.assert_frame_equal(apply_result, expected, check_names=False) + tm.assert_frame_equal(agg_result, expected) + + apply_result = df_grouped.apply(DataFrame.quantile, [0.4, 0.8]) + with tm.assert_produces_warning(warn, match=msg): + expected_seq = df_grouped.quantile([0.4, 0.8]) + tm.assert_frame_equal(apply_result, expected_seq, check_names=False) + + with tm.assert_produces_warning(warn, match=msg): + agg_result = df_grouped.agg(f, q=80) + with tm.assert_produces_warning(warn, match=msg): + apply_result = df_grouped.apply(DataFrame.quantile, q=0.8) + tm.assert_frame_equal(agg_result, expected) + tm.assert_frame_equal(apply_result, expected, check_names=False) + + +@pytest.mark.parametrize("as_index", [True, False]) +def test_pass_args_kwargs_duplicate_columns(tsframe, as_index): + # go through _aggregate_frame with self.axis == 0 and duplicate columns + tsframe.columns = ["A", "B", "A", "C"] + gb = tsframe.groupby(lambda x: x.month, as_index=as_index) + + warn = None if as_index else FutureWarning + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(warn, match=msg): + res = gb.agg(np.percentile, 80, axis=0) + + ex_data = { + 1: tsframe[tsframe.index.month == 1].quantile(0.8), + 2: tsframe[tsframe.index.month == 2].quantile(0.8), + } + expected = DataFrame(ex_data).T + if not as_index: + # TODO: try to get this more consistent? + expected.index = Index(range(2)) + + tm.assert_frame_equal(res, expected) + + +def test_len(): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) + assert len(grouped) == len(df) + + grouped = df.groupby([lambda x: x.year, lambda x: x.month]) + expected = len({(x.year, x.month) for x in df.index}) + assert len(grouped) == expected + + +def test_len_nan_group(): + # issue 11016 + df = DataFrame({"a": [np.nan] * 3, "b": [1, 2, 3]}) + assert len(df.groupby("a")) == 0 + assert len(df.groupby("b")) == 3 + assert len(df.groupby(["a", "b"])) == 3 + + +def test_basic_regression(): + # regression + result = Series([1.0 * x for x in list(range(1, 10)) * 10]) + + data = np.random.default_rng(2).random(1100) * 10.0 + groupings = Series(data) + + grouped = result.groupby(groupings) + grouped.mean() + + +@pytest.mark.parametrize( + "dtype", ["float64", "float32", "int64", "int32", "int16", "int8"] +) +def test_with_na_groups(dtype): + index = Index(np.arange(10)) + values = Series(np.ones(10), index, dtype=dtype) + labels = Series( + [np.nan, "foo", "bar", "bar", np.nan, np.nan, "bar", "bar", np.nan, "foo"], + index=index, + ) + + # this SHOULD be an int + grouped = values.groupby(labels) + agged = grouped.agg(len) + expected = Series([4, 2], index=["bar", "foo"]) + + tm.assert_series_equal(agged, expected, check_dtype=False) + + # assert issubclass(agged.dtype.type, np.integer) + + # explicitly return a float from my function + def f(x): + return float(len(x)) + + agged = grouped.agg(f) + expected = Series([4.0, 2.0], index=["bar", "foo"]) + + tm.assert_series_equal(agged, expected) + + +def test_indices_concatenation_order(): + # GH 2808 + + def f1(x): + y = x[(x.b % 2) == 1] ** 2 + if y.empty: + multiindex = MultiIndex(levels=[[]] * 2, codes=[[]] * 2, names=["b", "c"]) + res = DataFrame(columns=["a"], index=multiindex) + return res + else: + y = y.set_index(["b", "c"]) + return y + + def f2(x): + y = x[(x.b % 2) == 1] ** 2 + if y.empty: + return DataFrame() + else: + y = y.set_index(["b", "c"]) + return y + + def f3(x): + y = x[(x.b % 2) == 1] ** 2 + if y.empty: + multiindex = MultiIndex( + levels=[[]] * 2, codes=[[]] * 2, names=["foo", "bar"] + ) + res = DataFrame(columns=["a", "b"], index=multiindex) + return res + else: + return y + + df = DataFrame({"a": [1, 2, 2, 2], "b": range(4), "c": range(5, 9)}) + + df2 = DataFrame({"a": [3, 2, 2, 2], "b": range(4), "c": range(5, 9)}) + + depr_msg = "The behavior of array concatenation with empty entries is deprecated" + + # correct result + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result1 = df.groupby("a").apply(f1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result2 = df2.groupby("a").apply(f1) + tm.assert_frame_equal(result1, result2) + + # should fail (not the same number of levels) + msg = "Cannot concat indices that do not have the same number of levels" + with pytest.raises(AssertionError, match=msg): + df.groupby("a").apply(f2) + with pytest.raises(AssertionError, match=msg): + df2.groupby("a").apply(f2) + + # should fail (incorrect shape) + with pytest.raises(AssertionError, match=msg): + df.groupby("a").apply(f3) + with pytest.raises(AssertionError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df2.groupby("a").apply(f3) + + +def test_attr_wrapper(ts): + grouped = ts.groupby(lambda x: x.weekday()) + + result = grouped.std() + expected = grouped.agg(lambda x: np.std(x, ddof=1)) + tm.assert_series_equal(result, expected) + + # this is pretty cool + result = grouped.describe() + expected = {name: gp.describe() for name, gp in grouped} + expected = DataFrame(expected).T + tm.assert_frame_equal(result, expected) + + # get attribute + result = grouped.dtype + expected = grouped.agg(lambda x: x.dtype) + tm.assert_series_equal(result, expected) + + # make sure raises error + msg = "'SeriesGroupBy' object has no attribute 'foo'" + with pytest.raises(AttributeError, match=msg): + getattr(grouped, "foo") + + +def test_frame_groupby(tsframe): + grouped = tsframe.groupby(lambda x: x.weekday()) + + # aggregate + aggregated = grouped.aggregate("mean") + assert len(aggregated) == 5 + assert len(aggregated.columns) == 4 + + # by string + tscopy = tsframe.copy() + tscopy["weekday"] = [x.weekday() for x in tscopy.index] + stragged = tscopy.groupby("weekday").aggregate("mean") + tm.assert_frame_equal(stragged, aggregated, check_names=False) + + # transform + grouped = tsframe.head(30).groupby(lambda x: x.weekday()) + transformed = grouped.transform(lambda x: x - x.mean()) + assert len(transformed) == 30 + assert len(transformed.columns) == 4 + + # transform propagate + transformed = grouped.transform(lambda x: x.mean()) + for name, group in grouped: + mean = group.mean() + for idx in group.index: + tm.assert_series_equal(transformed.xs(idx), mean, check_names=False) + + # iterate + for weekday, group in grouped: + assert group.index[0].weekday() == weekday + + # groups / group_indices + groups = grouped.groups + indices = grouped.indices + + for k, v in groups.items(): + samething = tsframe.index.take(indices[k]) + assert (samething == v).all() + + +def test_frame_groupby_columns(tsframe): + mapping = {"A": 0, "B": 0, "C": 1, "D": 1} + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = tsframe.groupby(mapping, axis=1) + + # aggregate + aggregated = grouped.aggregate("mean") + assert len(aggregated) == len(tsframe) + assert len(aggregated.columns) == 2 + + # transform + tf = lambda x: x - x.mean() + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + groupedT = tsframe.T.groupby(mapping, axis=0) + tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf)) + + # iterate + for k, v in grouped: + assert len(v.columns) == 2 + + +def test_frame_set_name_single(df): + grouped = df.groupby("A") + + result = grouped.mean(numeric_only=True) + assert result.index.name == "A" + + result = df.groupby("A", as_index=False).mean(numeric_only=True) + assert result.index.name != "A" + + result = grouped[["C", "D"]].agg("mean") + assert result.index.name == "A" + + result = grouped.agg({"C": "mean", "D": "std"}) + assert result.index.name == "A" + + result = grouped["C"].mean() + assert result.index.name == "A" + result = grouped["C"].agg("mean") + assert result.index.name == "A" + result = grouped["C"].agg(["mean", "std"]) + assert result.index.name == "A" + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + grouped["C"].agg({"foo": "mean", "bar": "std"}) + + +def test_multi_func(df): + col1 = df["A"] + col2 = df["B"] + + grouped = df.groupby([col1.get, col2.get]) + agged = grouped.mean(numeric_only=True) + expected = df.groupby(["A", "B"]).mean() + + # TODO groupby get drops names + tm.assert_frame_equal( + agged.loc[:, ["C", "D"]], expected.loc[:, ["C", "D"]], check_names=False + ) + + # some "groups" with no data + df = DataFrame( + { + "v1": np.random.default_rng(2).standard_normal(6), + "v2": np.random.default_rng(2).standard_normal(6), + "k1": np.array(["b", "b", "b", "a", "a", "a"]), + "k2": np.array(["1", "1", "1", "2", "2", "2"]), + }, + index=["one", "two", "three", "four", "five", "six"], + ) + # only verify that it works for now + grouped = df.groupby(["k1", "k2"]) + grouped.agg("sum") + + +def test_multi_key_multiple_functions(df): + grouped = df.groupby(["A", "B"])["C"] + + agged = grouped.agg(["mean", "std"]) + expected = DataFrame({"mean": grouped.agg("mean"), "std": grouped.agg("std")}) + tm.assert_frame_equal(agged, expected) + + +def test_frame_multi_key_function_list(): + data = DataFrame( + { + "A": [ + "foo", + "foo", + "foo", + "foo", + "bar", + "bar", + "bar", + "bar", + "foo", + "foo", + "foo", + ], + "B": [ + "one", + "one", + "one", + "two", + "one", + "one", + "one", + "two", + "two", + "two", + "one", + ], + "D": np.random.default_rng(2).standard_normal(11), + "E": np.random.default_rng(2).standard_normal(11), + "F": np.random.default_rng(2).standard_normal(11), + } + ) + + grouped = data.groupby(["A", "B"]) + funcs = ["mean", "std"] + agged = grouped.agg(funcs) + expected = pd.concat( + [grouped["D"].agg(funcs), grouped["E"].agg(funcs), grouped["F"].agg(funcs)], + keys=["D", "E", "F"], + axis=1, + ) + assert isinstance(agged.index, MultiIndex) + assert isinstance(expected.index, MultiIndex) + tm.assert_frame_equal(agged, expected) + + +def test_frame_multi_key_function_list_partial_failure(using_infer_string): + data = DataFrame( + { + "A": [ + "foo", + "foo", + "foo", + "foo", + "bar", + "bar", + "bar", + "bar", + "foo", + "foo", + "foo", + ], + "B": [ + "one", + "one", + "one", + "two", + "one", + "one", + "one", + "two", + "two", + "two", + "one", + ], + "C": [ + "dull", + "dull", + "shiny", + "dull", + "dull", + "shiny", + "shiny", + "dull", + "shiny", + "shiny", + "shiny", + ], + "D": np.random.default_rng(2).standard_normal(11), + "E": np.random.default_rng(2).standard_normal(11), + "F": np.random.default_rng(2).standard_normal(11), + } + ) + + grouped = data.groupby(["A", "B"]) + funcs = ["mean", "std"] + msg = re.escape("agg function failed [how->mean,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + with pytest.raises(TypeError, match=msg): + grouped.agg(funcs) + + +@pytest.mark.parametrize("op", [lambda x: x.sum(), lambda x: x.mean()]) +def test_groupby_multiple_columns(df, op): + data = df + grouped = data.groupby(["A", "B"]) + + result1 = op(grouped) + + keys = [] + values = [] + for n1, gp1 in data.groupby("A"): + for n2, gp2 in gp1.groupby("B"): + keys.append((n1, n2)) + values.append(op(gp2.loc[:, ["C", "D"]])) + + mi = MultiIndex.from_tuples(keys, names=["A", "B"]) + expected = pd.concat(values, axis=1).T + expected.index = mi + + # a little bit crude + for col in ["C", "D"]: + result_col = op(grouped[col]) + pivoted = result1[col] + exp = expected[col] + tm.assert_series_equal(result_col, exp) + tm.assert_series_equal(pivoted, exp) + + # test single series works the same + result = data["C"].groupby([data["A"], data["B"]]).mean() + expected = data.groupby(["A", "B"]).mean()["C"] + + tm.assert_series_equal(result, expected) + + +def test_as_index_select_column(): + # GH 5764 + df = DataFrame([[1, 2], [1, 4], [5, 6]], columns=["A", "B"]) + result = df.groupby("A", as_index=False)["B"].get_group(1) + expected = Series([2, 4], name="B") + tm.assert_series_equal(result, expected) + + result = df.groupby("A", as_index=False, group_keys=True)["B"].apply( + lambda x: x.cumsum() + ) + expected = Series( + [2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)]) + ) + tm.assert_series_equal(result, expected) + + +def test_obj_arg_get_group_deprecated(): + depr_msg = "obj is deprecated" + + df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + expected = df.iloc[df.groupby("b").indices.get(4)] + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = df.groupby("b").get_group(4, obj=df) + tm.assert_frame_equal(result, expected) + + +def test_groupby_as_index_select_column_sum_empty_df(): + # GH 35246 + df = DataFrame(columns=Index(["A", "B", "C"], name="alpha")) + left = df.groupby(by="A", as_index=False)["B"].sum(numeric_only=False) + + expected = DataFrame(columns=df.columns[:2], index=range(0)) + # GH#50744 - Columns after selection shouldn't retain names + expected.columns.names = [None] + tm.assert_frame_equal(left, expected) + + +def test_groupby_as_index_agg(df): + grouped = df.groupby("A", as_index=False) + + # single-key + + result = grouped[["C", "D"]].agg("mean") + expected = grouped.mean(numeric_only=True) + tm.assert_frame_equal(result, expected) + + result2 = grouped.agg({"C": "mean", "D": "sum"}) + expected2 = grouped.mean(numeric_only=True) + expected2["D"] = grouped.sum()["D"] + tm.assert_frame_equal(result2, expected2) + + grouped = df.groupby("A", as_index=True) + + msg = r"nested renamer is not supported" + with pytest.raises(SpecificationError, match=msg): + grouped["C"].agg({"Q": "sum"}) + + # multi-key + + grouped = df.groupby(["A", "B"], as_index=False) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + result2 = grouped.agg({"C": "mean", "D": "sum"}) + expected2 = grouped.mean() + expected2["D"] = grouped.sum()["D"] + tm.assert_frame_equal(result2, expected2) + + expected3 = grouped["C"].sum() + expected3 = DataFrame(expected3).rename(columns={"C": "Q"}) + msg = "Passing a dictionary to SeriesGroupBy.agg is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result3 = grouped["C"].agg({"Q": "sum"}) + tm.assert_frame_equal(result3, expected3) + + # GH7115 & GH8112 & GH8582 + df = DataFrame( + np.random.default_rng(2).integers(0, 100, (50, 3)), + columns=["jim", "joe", "jolie"], + ) + ts = Series(np.random.default_rng(2).integers(5, 10, 50), name="jim") + + gr = df.groupby(ts) + gr.nth(0) # invokes set_selection_from_grouper internally + + msg = "The behavior of DataFrame.sum with axis=None is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): + res = gr.apply(sum) + with tm.assert_produces_warning(FutureWarning, match=msg, check_stacklevel=False): + alt = df.groupby(ts).apply(sum) + tm.assert_frame_equal(res, alt) + + for attr in ["mean", "max", "count", "idxmax", "cumsum", "all"]: + gr = df.groupby(ts, as_index=False) + left = getattr(gr, attr)() + + gr = df.groupby(ts.values, as_index=True) + right = getattr(gr, attr)().reset_index(drop=True) + + tm.assert_frame_equal(left, right) + + +def test_ops_not_as_index(reduction_func): + # GH 10355, 21090 + # Using as_index=False should not modify grouped column + + if reduction_func in ("corrwith", "nth", "ngroup"): + pytest.skip(f"GH 5755: Test not applicable for {reduction_func}") + + df = DataFrame( + np.random.default_rng(2).integers(0, 5, size=(100, 2)), columns=["a", "b"] + ) + expected = getattr(df.groupby("a"), reduction_func)() + if reduction_func == "size": + expected = expected.rename("size") + expected = expected.reset_index() + + if reduction_func != "size": + # 32 bit compat -> groupby preserves dtype whereas reset_index casts to int64 + expected["a"] = expected["a"].astype(df["a"].dtype) + + g = df.groupby("a", as_index=False) + + result = getattr(g, reduction_func)() + tm.assert_frame_equal(result, expected) + + result = g.agg(reduction_func) + tm.assert_frame_equal(result, expected) + + result = getattr(g["b"], reduction_func)() + tm.assert_frame_equal(result, expected) + + result = g["b"].agg(reduction_func) + tm.assert_frame_equal(result, expected) + + +def test_as_index_series_return_frame(df): + grouped = df.groupby("A", as_index=False) + grouped2 = df.groupby(["A", "B"], as_index=False) + + result = grouped["C"].agg("sum") + expected = grouped.agg("sum").loc[:, ["A", "C"]] + assert isinstance(result, DataFrame) + tm.assert_frame_equal(result, expected) + + result2 = grouped2["C"].agg("sum") + expected2 = grouped2.agg("sum").loc[:, ["A", "B", "C"]] + assert isinstance(result2, DataFrame) + tm.assert_frame_equal(result2, expected2) + + result = grouped["C"].sum() + expected = grouped.sum().loc[:, ["A", "C"]] + assert isinstance(result, DataFrame) + tm.assert_frame_equal(result, expected) + + result2 = grouped2["C"].sum() + expected2 = grouped2.sum().loc[:, ["A", "B", "C"]] + assert isinstance(result2, DataFrame) + tm.assert_frame_equal(result2, expected2) + + +def test_as_index_series_column_slice_raises(df): + # GH15072 + grouped = df.groupby("A", as_index=False) + msg = r"Column\(s\) C already selected" + + with pytest.raises(IndexError, match=msg): + grouped["C"].__getitem__("D") + + +def test_groupby_as_index_cython(df): + data = df + + # single-key + grouped = data.groupby("A", as_index=False) + result = grouped.mean(numeric_only=True) + expected = data.groupby(["A"]).mean(numeric_only=True) + expected.insert(0, "A", expected.index) + expected.index = RangeIndex(len(expected)) + tm.assert_frame_equal(result, expected) + + # multi-key + grouped = data.groupby(["A", "B"], as_index=False) + result = grouped.mean() + expected = data.groupby(["A", "B"]).mean() + + arrays = list(zip(*expected.index.values)) + expected.insert(0, "A", arrays[0]) + expected.insert(1, "B", arrays[1]) + expected.index = RangeIndex(len(expected)) + tm.assert_frame_equal(result, expected) + + +def test_groupby_as_index_series_scalar(df): + grouped = df.groupby(["A", "B"], as_index=False) + + # GH #421 + + result = grouped["C"].agg(len) + expected = grouped.agg(len).loc[:, ["A", "B", "C"]] + tm.assert_frame_equal(result, expected) + + +def test_groupby_as_index_corner(df, ts): + msg = "as_index=False only valid with DataFrame" + with pytest.raises(TypeError, match=msg): + ts.groupby(lambda x: x.weekday(), as_index=False) + + msg = "as_index=False only valid for axis=0" + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(lambda x: x.lower(), as_index=False, axis=1) + + +def test_groupby_multiple_key(): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) + agged = grouped.sum() + tm.assert_almost_equal(df.values, agged.values) + + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + grouped = df.T.groupby( + [lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1 + ) + + agged = grouped.agg(lambda x: x.sum()) + tm.assert_index_equal(agged.index, df.columns) + tm.assert_almost_equal(df.T.values, agged.values) + + agged = grouped.agg(lambda x: x.sum()) + tm.assert_almost_equal(df.T.values, agged.values) + + +def test_groupby_multi_corner(df): + # test that having an all-NA column doesn't mess you up + df = df.copy() + df["bad"] = np.nan + agged = df.groupby(["A", "B"]).mean() + + expected = df.groupby(["A", "B"]).mean() + expected["bad"] = np.nan + + tm.assert_frame_equal(agged, expected) + + +def test_raises_on_nuisance(df, using_infer_string): + grouped = df.groupby("A") + msg = re.escape("agg function failed [how->mean,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + with pytest.raises(TypeError, match=msg): + grouped.agg("mean") + with pytest.raises(TypeError, match=msg): + grouped.mean() + + df = df.loc[:, ["A", "C", "D"]] + df["E"] = datetime.now() + grouped = df.groupby("A") + msg = "datetime64 type does not support sum operations" + with pytest.raises(TypeError, match=msg): + grouped.agg("sum") + with pytest.raises(TypeError, match=msg): + grouped.sum() + + # won't work with axis = 1 + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1) + msg = "does not support reduction 'sum'|Cannot perform reduction 'sum'" + with pytest.raises(TypeError, match=msg): + grouped.agg(lambda x: x.sum(0, numeric_only=False)) + + +@pytest.mark.parametrize( + "agg_function", + ["max", "min"], +) +def test_keep_nuisance_agg(df, agg_function): + # GH 38815 + grouped = df.groupby("A") + result = getattr(grouped, agg_function)() + expected = result.copy() + expected.loc["bar", "B"] = getattr(df.loc[df["A"] == "bar", "B"], agg_function)() + expected.loc["foo", "B"] = getattr(df.loc[df["A"] == "foo", "B"], agg_function)() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "agg_function", + ["sum", "mean", "prod", "std", "var", "sem", "median"], +) +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_omit_nuisance_agg(df, agg_function, numeric_only, using_infer_string): + # GH 38774, GH 38815 + grouped = df.groupby("A") + + no_drop_nuisance = ("var", "std", "sem", "mean", "prod", "median") + if agg_function in no_drop_nuisance and not numeric_only: + # Added numeric_only as part of GH#46560; these do not drop nuisance + # columns when numeric_only is False + if using_infer_string: + msg = f"dtype 'str' does not support operation '{agg_function}'" + klass = TypeError + elif agg_function in ("std", "sem"): + klass = ValueError + msg = "could not convert string to float: 'one'" + else: + klass = TypeError + msg = re.escape(f"agg function failed [how->{agg_function},dtype->") + with pytest.raises(klass, match=msg): + getattr(grouped, agg_function)(numeric_only=numeric_only) + else: + result = getattr(grouped, agg_function)(numeric_only=numeric_only) + if not numeric_only and agg_function == "sum": + # sum is successful on column B + columns = ["A", "B", "C", "D"] + else: + columns = ["A", "C", "D"] + expected = getattr(df.loc[:, columns].groupby("A"), agg_function)( + numeric_only=numeric_only + ) + tm.assert_frame_equal(result, expected) + + +def test_raise_on_nuisance_python_single(df, using_infer_string): + # GH 38815 + grouped = df.groupby("A") + + err = ValueError + msg = "could not convert" + if using_infer_string: + err = TypeError + msg = "dtype 'str' does not support operation 'skew'" + with pytest.raises(err, match=msg): + grouped.skew() + + +def test_raise_on_nuisance_python_multiple(three_group, using_infer_string): + grouped = three_group.groupby(["A", "B"]) + msg = re.escape("agg function failed [how->mean,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + with pytest.raises(TypeError, match=msg): + grouped.agg("mean") + with pytest.raises(TypeError, match=msg): + grouped.mean() + + +def test_empty_groups_corner(multiindex_dataframe_random_data): + # handle empty groups + df = DataFrame( + { + "k1": np.array(["b", "b", "b", "a", "a", "a"]), + "k2": np.array(["1", "1", "1", "2", "2", "2"]), + "k3": ["foo", "bar"] * 3, + "v1": np.random.default_rng(2).standard_normal(6), + "v2": np.random.default_rng(2).standard_normal(6), + } + ) + + grouped = df.groupby(["k1", "k2"]) + result = grouped[["v1", "v2"]].agg("mean") + expected = grouped.mean(numeric_only=True) + tm.assert_frame_equal(result, expected) + + grouped = multiindex_dataframe_random_data[3:5].groupby(level=0) + agged = grouped.apply(lambda x: x.mean()) + agged_A = grouped["A"].apply("mean") + tm.assert_series_equal(agged["A"], agged_A) + assert agged.index.name == "first" + + +def test_nonsense_func(): + df = DataFrame([0]) + msg = r"unsupported operand type\(s\) for \+: 'int' and 'str'" + with pytest.raises(TypeError, match=msg): + df.groupby(lambda x: x + "foo") + + +def test_wrap_aggregated_output_multindex( + multiindex_dataframe_random_data, using_infer_string +): + df = multiindex_dataframe_random_data.T + df["baz", "two"] = "peekaboo" + + keys = [np.array([0, 0, 1]), np.array([0, 0, 1])] + msg = re.escape("agg function failed [how->mean,dtype->") + if using_infer_string: + msg = "dtype 'str' does not support operation 'mean'" + with pytest.raises(TypeError, match=msg): + df.groupby(keys).agg("mean") + agged = df.drop(columns=("baz", "two")).groupby(keys).agg("mean") + assert isinstance(agged.columns, MultiIndex) + + def aggfun(ser): + if ser.name == ("foo", "one"): + raise TypeError("Test error message") + return ser.sum() + + with pytest.raises(TypeError, match="Test error message"): + df.groupby(keys).aggregate(aggfun) + + +def test_groupby_level_apply(multiindex_dataframe_random_data): + result = multiindex_dataframe_random_data.groupby(level=0).count() + assert result.index.name == "first" + result = multiindex_dataframe_random_data.groupby(level=1).count() + assert result.index.name == "second" + + result = multiindex_dataframe_random_data["A"].groupby(level=0).count() + assert result.index.name == "first" + + +def test_groupby_level_mapper(multiindex_dataframe_random_data): + deleveled = multiindex_dataframe_random_data.reset_index() + + mapper0 = {"foo": 0, "bar": 0, "baz": 1, "qux": 1} + mapper1 = {"one": 0, "two": 0, "three": 1} + + result0 = multiindex_dataframe_random_data.groupby(mapper0, level=0).sum() + result1 = multiindex_dataframe_random_data.groupby(mapper1, level=1).sum() + + mapped_level0 = np.array( + [mapper0.get(x) for x in deleveled["first"]], dtype=np.int64 + ) + mapped_level1 = np.array( + [mapper1.get(x) for x in deleveled["second"]], dtype=np.int64 + ) + expected0 = multiindex_dataframe_random_data.groupby(mapped_level0).sum() + expected1 = multiindex_dataframe_random_data.groupby(mapped_level1).sum() + expected0.index.name, expected1.index.name = "first", "second" + + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) + + +def test_groupby_level_nonmulti(): + # GH 1313, GH 13901 + s = Series([1, 2, 3, 10, 4, 5, 20, 6], Index([1, 2, 3, 1, 4, 5, 2, 6], name="foo")) + expected = Series([11, 22, 3, 4, 5, 6], Index(range(1, 7), name="foo")) + + result = s.groupby(level=0).sum() + tm.assert_series_equal(result, expected) + result = s.groupby(level=[0]).sum() + tm.assert_series_equal(result, expected) + result = s.groupby(level=-1).sum() + tm.assert_series_equal(result, expected) + result = s.groupby(level=[-1]).sum() + tm.assert_series_equal(result, expected) + + msg = "level > 0 or level < -1 only valid with MultiIndex" + with pytest.raises(ValueError, match=msg): + s.groupby(level=1) + with pytest.raises(ValueError, match=msg): + s.groupby(level=-2) + msg = "No group keys passed!" + with pytest.raises(ValueError, match=msg): + s.groupby(level=[]) + msg = "multiple levels only valid with MultiIndex" + with pytest.raises(ValueError, match=msg): + s.groupby(level=[0, 0]) + with pytest.raises(ValueError, match=msg): + s.groupby(level=[0, 1]) + msg = "level > 0 or level < -1 only valid with MultiIndex" + with pytest.raises(ValueError, match=msg): + s.groupby(level=[1]) + + +def test_groupby_complex(): + # GH 12902 + a = Series(data=np.arange(4) * (1 + 2j), index=[0, 0, 1, 1]) + expected = Series((1 + 2j, 5 + 10j)) + + result = a.groupby(level=0).sum() + tm.assert_series_equal(result, expected) + + +def test_groupby_complex_mean(): + # GH 26475 + df = DataFrame( + [ + {"a": 2, "b": 1 + 2j}, + {"a": 1, "b": 1 + 1j}, + {"a": 1, "b": 1 + 2j}, + ] + ) + result = df.groupby("b").mean() + expected = DataFrame( + [[1.0], [1.5]], + index=Index([(1 + 1j), (1 + 2j)], name="b"), + columns=Index(["a"]), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_complex_numbers(): + # GH 17927 + df = DataFrame( + [ + {"a": 1, "b": 1 + 1j}, + {"a": 1, "b": 1 + 2j}, + {"a": 4, "b": 1}, + ] + ) + expected = DataFrame( + np.array([1, 1, 1], dtype=np.int64), + index=Index([(1 + 1j), (1 + 2j), (1 + 0j)], name="b"), + columns=Index(["a"]), + ) + result = df.groupby("b", sort=False).count() + tm.assert_frame_equal(result, expected) + + # Sorted by the magnitude of the complex numbers + expected.index = Index([(1 + 0j), (1 + 1j), (1 + 2j)], name="b") + result = df.groupby("b", sort=True).count() + tm.assert_frame_equal(result, expected) + + +def test_groupby_series_indexed_differently(): + s1 = Series( + [5.0, -9.0, 4.0, 100.0, -5.0, 55.0, 6.7], + index=Index(["a", "b", "c", "d", "e", "f", "g"]), + ) + s2 = Series( + [1.0, 1.0, 4.0, 5.0, 5.0, 7.0], index=Index(["a", "b", "d", "f", "g", "h"]) + ) + + grouped = s1.groupby(s2) + agged = grouped.mean() + exp = s1.groupby(s2.reindex(s1.index).get).mean() + tm.assert_series_equal(agged, exp) + + +def test_groupby_with_hier_columns(): + tuples = list( + zip( + *[ + ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + ) + ) + index = MultiIndex.from_tuples(tuples) + columns = MultiIndex.from_tuples( + [("A", "cat"), ("B", "dog"), ("B", "cat"), ("A", "dog")] + ) + df = DataFrame( + np.random.default_rng(2).standard_normal((8, 4)), index=index, columns=columns + ) + + result = df.groupby(level=0).mean() + tm.assert_index_equal(result.columns, columns) + + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(level=0, axis=1) + result = gb.mean() + tm.assert_index_equal(result.index, df.index) + + result = df.groupby(level=0).agg("mean") + tm.assert_index_equal(result.columns, columns) + + result = df.groupby(level=0).apply(lambda x: x.mean()) + tm.assert_index_equal(result.columns, columns) + + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(level=0, axis=1) + result = gb.agg(lambda x: x.mean(1)) + tm.assert_index_equal(result.columns, Index(["A", "B"])) + tm.assert_index_equal(result.index, df.index) + + # add a nuisance column + sorted_columns, _ = columns.sortlevel(0) + df["A", "foo"] = "bar" + result = df.groupby(level=0).mean(numeric_only=True) + tm.assert_index_equal(result.columns, df.columns[:-1]) + + +def test_grouping_ndarray(df): + grouped = df.groupby(df["A"].values) + grouped2 = df.groupby(df["A"].rename(None)) + + result = grouped.sum() + expected = grouped2.sum() + tm.assert_frame_equal(result, expected) + + +def test_groupby_wrong_multi_labels(): + index = Index([0, 1, 2, 3, 4], name="index") + data = DataFrame( + { + "foo": ["foo1", "foo1", "foo2", "foo1", "foo3"], + "bar": ["bar1", "bar2", "bar2", "bar1", "bar1"], + "baz": ["baz1", "baz1", "baz1", "baz2", "baz2"], + "spam": ["spam2", "spam3", "spam2", "spam1", "spam1"], + "data": [20, 30, 40, 50, 60], + }, + index=index, + ) + + grouped = data.groupby(["foo", "bar", "baz", "spam"]) + + result = grouped.agg("mean") + expected = grouped.mean() + tm.assert_frame_equal(result, expected) + + +def test_groupby_series_with_name(df): + result = df.groupby(df["A"]).mean(numeric_only=True) + result2 = df.groupby(df["A"], as_index=False).mean(numeric_only=True) + assert result.index.name == "A" + assert "A" in result2 + + result = df.groupby([df["A"], df["B"]]).mean() + result2 = df.groupby([df["A"], df["B"]], as_index=False).mean() + assert result.index.names == ("A", "B") + assert "A" in result2 + assert "B" in result2 + + +def test_seriesgroupby_name_attr(df): + # GH 6265 + result = df.groupby("A")["C"] + assert result.count().name == "C" + assert result.mean().name == "C" + + testFunc = lambda x: np.sum(x) * 2 + assert result.agg(testFunc).name == "C" + + +def test_consistency_name(): + # GH 12363 + + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "two", "two", "two", "one", "two"], + "C": np.random.default_rng(2).standard_normal(8) + 1.0, + "D": np.arange(8), + } + ) + + expected = df.groupby(["A"]).B.count() + result = df.B.groupby(df.A).count() + tm.assert_series_equal(result, expected) + + +def test_groupby_name_propagation(df): + # GH 6124 + def summarize(df, name=None): + return Series({"count": 1, "mean": 2, "omissions": 3}, name=name) + + def summarize_random_name(df): + # Provide a different name for each Series. In this case, groupby + # should not attempt to propagate the Series name since they are + # inconsistent. + return Series({"count": 1, "mean": 2, "omissions": 3}, name=df.iloc[0]["A"]) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + metrics = df.groupby("A").apply(summarize) + assert metrics.columns.name is None + with tm.assert_produces_warning(FutureWarning, match=msg): + metrics = df.groupby("A").apply(summarize, "metrics") + assert metrics.columns.name == "metrics" + with tm.assert_produces_warning(FutureWarning, match=msg): + metrics = df.groupby("A").apply(summarize_random_name) + assert metrics.columns.name is None + + +def test_groupby_nonstring_columns(): + df = DataFrame([np.arange(10) for x in range(10)]) + grouped = df.groupby(0) + result = grouped.mean() + expected = df.groupby(df[0]).mean() + tm.assert_frame_equal(result, expected) + + +def test_groupby_mixed_type_columns(): + # GH 13432, unorderable types in py3 + df = DataFrame([[0, 1, 2]], columns=["A", "B", 0]) + expected = DataFrame([[1, 2]], columns=["B", 0], index=Index([0], name="A")) + + result = df.groupby("A").first() + tm.assert_frame_equal(result, expected) + + result = df.groupby("A").sum() + tm.assert_frame_equal(result, expected) + + +def test_cython_grouper_series_bug_noncontig(): + arr = np.empty((100, 100)) + arr.fill(np.nan) + obj = Series(arr[:, 0]) + inds = np.tile(range(10), 10) + + result = obj.groupby(inds).agg(Series.median) + assert result.isna().all() + + +def test_series_grouper_noncontig_index(): + index = Index(["a" * 10] * 100) + + values = Series(np.random.default_rng(2).standard_normal(50), index=index[::2]) + labels = np.random.default_rng(2).integers(0, 5, 50) + + # it works! + grouped = values.groupby(labels) + + # accessing the index elements causes segfault + f = lambda x: len(set(map(id, x.index))) + grouped.agg(f) + + +def test_convert_objects_leave_decimal_alone(): + s = Series(range(5)) + labels = np.array(["a", "b", "c", "d", "e"], dtype="O") + + def convert_fast(x): + return Decimal(str(x.mean())) + + def convert_force_pure(x): + # base will be length 0 + assert len(x.values.base) > 0 + return Decimal(str(x.mean())) + + grouped = s.groupby(labels) + + result = grouped.agg(convert_fast) + assert result.dtype == np.object_ + assert isinstance(result.iloc[0], Decimal) + + result = grouped.agg(convert_force_pure) + assert result.dtype == np.object_ + assert isinstance(result.iloc[0], Decimal) + + +def test_groupby_dtype_inference_empty(): + # GH 6733 + df = DataFrame({"x": [], "range": np.arange(0, dtype="int64")}) + assert df["x"].dtype == np.float64 + + result = df.groupby("x").first() + exp_index = Index([], name="x", dtype=np.float64) + expected = DataFrame({"range": Series([], index=exp_index, dtype="int64")}) + tm.assert_frame_equal(result, expected, by_blocks=True) + + +def test_groupby_unit64_float_conversion(): + # GH: 30859 groupby converts unit64 to floats sometimes + df = DataFrame({"first": [1], "second": [1], "value": [16148277970000000000]}) + result = df.groupby(["first", "second"])["value"].max() + expected = Series( + [16148277970000000000], + MultiIndex.from_product([[1], [1]], names=["first", "second"]), + name="value", + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_list_infer_array_like(df): + result = df.groupby(list(df["A"])).mean(numeric_only=True) + expected = df.groupby(df["A"]).mean(numeric_only=True) + tm.assert_frame_equal(result, expected, check_names=False) + + with pytest.raises(KeyError, match=r"^'foo'$"): + df.groupby(list(df["A"][:-1])) + + # pathological case of ambiguity + df = DataFrame( + { + "foo": [0, 1], + "bar": [3, 4], + "val": np.random.default_rng(2).standard_normal(2), + } + ) + + result = df.groupby(["foo", "bar"]).mean() + expected = df.groupby([df["foo"], df["bar"]]).mean()[["val"]] + + +def test_groupby_keys_same_size_as_index(): + # GH 11185 + freq = "s" + index = date_range( + start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq + ) + df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index) + result = df.groupby([Grouper(level=0, freq=freq), "metric"]).mean() + expected = df.set_index([df.index, "metric"]).astype(float) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_one_row(): + # GH 11741 + msg = r"^'Z'$" + df1 = DataFrame( + np.random.default_rng(2).standard_normal((1, 4)), columns=list("ABCD") + ) + with pytest.raises(KeyError, match=msg): + df1.groupby("Z") + df2 = DataFrame( + np.random.default_rng(2).standard_normal((2, 4)), columns=list("ABCD") + ) + with pytest.raises(KeyError, match=msg): + df2.groupby("Z") + + +def test_groupby_nat_exclude(): + # GH 6992 + df = DataFrame( + { + "values": np.random.default_rng(2).standard_normal(8), + "dt": [ + np.nan, + Timestamp("2013-01-01"), + np.nan, + Timestamp("2013-02-01"), + np.nan, + Timestamp("2013-02-01"), + np.nan, + Timestamp("2013-01-01"), + ], + "str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"], + } + ) + grouped = df.groupby("dt") + + expected = [Index([1, 7]), Index([3, 5])] + keys = sorted(grouped.groups.keys()) + assert len(keys) == 2 + for k, e in zip(keys, expected): + # grouped.groups keys are np.datetime64 with system tz + # not to be affected by tz, only compare values + tm.assert_index_equal(grouped.groups[k], e) + + # confirm obj is not filtered + tm.assert_frame_equal(grouped._grouper.groupings[0].obj, df) + assert grouped.ngroups == 2 + + expected = { + Timestamp("2013-01-01 00:00:00"): np.array([1, 7], dtype=np.intp), + Timestamp("2013-02-01 00:00:00"): np.array([3, 5], dtype=np.intp), + } + + for k in grouped.indices: + tm.assert_numpy_array_equal(grouped.indices[k], expected[k]) + + tm.assert_frame_equal(grouped.get_group(Timestamp("2013-01-01")), df.iloc[[1, 7]]) + tm.assert_frame_equal(grouped.get_group(Timestamp("2013-02-01")), df.iloc[[3, 5]]) + + with pytest.raises(KeyError, match=r"^NaT$"): + grouped.get_group(pd.NaT) + + nan_df = DataFrame( + {"nan": [np.nan, np.nan, np.nan], "nat": [pd.NaT, pd.NaT, pd.NaT]} + ) + assert nan_df["nan"].dtype == "float64" + assert nan_df["nat"].dtype == "datetime64[ns]" + + for key in ["nan", "nat"]: + grouped = nan_df.groupby(key) + assert grouped.groups == {} + assert grouped.ngroups == 0 + assert grouped.indices == {} + with pytest.raises(KeyError, match=r"^nan$"): + grouped.get_group(np.nan) + with pytest.raises(KeyError, match=r"^NaT$"): + grouped.get_group(pd.NaT) + + +def test_groupby_two_group_keys_all_nan(): + # GH #36842: Grouping over two group keys shouldn't raise an error + df = DataFrame({"a": [np.nan, np.nan], "b": [np.nan, np.nan], "c": [1, 2]}) + result = df.groupby(["a", "b"]).indices + assert result == {} + + +def test_groupby_2d_malformed(): + d = DataFrame(index=range(2)) + d["group"] = ["g1", "g2"] + d["zeros"] = [0, 0] + d["ones"] = [1, 1] + d["label"] = ["l1", "l2"] + tmp = d.groupby(["group"]).mean(numeric_only=True) + res_values = np.array([[0.0, 1.0], [0.0, 1.0]]) + tm.assert_index_equal(tmp.columns, Index(["zeros", "ones"])) + tm.assert_numpy_array_equal(tmp.values, res_values) + + +def test_int32_overflow(): + B = np.concatenate((np.arange(10000), np.arange(10000), np.arange(5000))) + A = np.arange(25000) + df = DataFrame( + { + "A": A, + "B": B, + "C": A, + "D": B, + "E": np.random.default_rng(2).standard_normal(25000), + } + ) + + left = df.groupby(["A", "B", "C", "D"]).sum() + right = df.groupby(["D", "C", "B", "A"]).sum() + assert len(left) == len(right) + + +def test_groupby_sort_multi(): + df = DataFrame( + { + "a": ["foo", "bar", "baz"], + "b": [3, 2, 1], + "c": [0, 1, 2], + "d": np.random.default_rng(2).standard_normal(3), + } + ) + + tups = [tuple(row) for row in df[["a", "b", "c"]].values] + tups = com.asarray_tuplesafe(tups) + result = df.groupby(["a", "b", "c"], sort=True).sum() + tm.assert_numpy_array_equal(result.index.values, tups[[1, 2, 0]]) + + tups = [tuple(row) for row in df[["c", "a", "b"]].values] + tups = com.asarray_tuplesafe(tups) + result = df.groupby(["c", "a", "b"], sort=True).sum() + tm.assert_numpy_array_equal(result.index.values, tups) + + tups = [tuple(x) for x in df[["b", "c", "a"]].values] + tups = com.asarray_tuplesafe(tups) + result = df.groupby(["b", "c", "a"], sort=True).sum() + tm.assert_numpy_array_equal(result.index.values, tups[[2, 1, 0]]) + + df = DataFrame( + { + "a": [0, 1, 2, 0, 1, 2], + "b": [0, 0, 0, 1, 1, 1], + "d": np.random.default_rng(2).standard_normal(6), + } + ) + grouped = df.groupby(["a", "b"])["d"] + result = grouped.sum() + + def _check_groupby(df, result, keys, field, f=lambda x: x.sum()): + tups = [tuple(row) for row in df[keys].values] + tups = com.asarray_tuplesafe(tups) + expected = f(df.groupby(tups)[field]) + for k, v in expected.items(): + assert result[k] == v + + _check_groupby(df, result, ["a", "b"], "d") + + +def test_dont_clobber_name_column(): + df = DataFrame( + {"key": ["a", "a", "a", "b", "b", "b"], "name": ["foo", "bar", "baz"] * 2} + ) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("key", group_keys=False).apply(lambda x: x) + tm.assert_frame_equal(result, df) + + +def test_skip_group_keys(): + tsf = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + + grouped = tsf.groupby(lambda x: x.month, group_keys=False) + result = grouped.apply(lambda x: x.sort_values(by="A")[:3]) + + pieces = [group.sort_values(by="A")[:3] for key, group in grouped] + + expected = pd.concat(pieces) + tm.assert_frame_equal(result, expected) + + grouped = tsf["A"].groupby(lambda x: x.month, group_keys=False) + result = grouped.apply(lambda x: x.sort_values()[:3]) + + pieces = [group.sort_values()[:3] for key, group in grouped] + + expected = pd.concat(pieces) + tm.assert_series_equal(result, expected) + + +def test_no_nonsense_name(float_frame): + # GH #995 + s = float_frame["C"].copy() + s.name = None + + result = s.groupby(float_frame["A"]).agg("sum") + assert result.name is None + + +def test_multifunc_sum_bug(): + # GH #1065 + x = DataFrame(np.arange(9).reshape(3, 3)) + x["test"] = 0 + x["fl"] = [1.3, 1.5, 1.6] + + grouped = x.groupby("test") + result = grouped.agg({"fl": "sum", 2: "size"}) + assert result["fl"].dtype == np.float64 + + +def test_handle_dict_return_value(df): + def f(group): + return {"max": group.max(), "min": group.min()} + + def g(group): + return Series({"max": group.max(), "min": group.min()}) + + result = df.groupby("A")["C"].apply(f) + expected = df.groupby("A")["C"].apply(g) + + assert isinstance(result, Series) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("grouper", ["A", ["A", "B"]]) +def test_set_group_name(df, grouper): + def f(group): + assert group.name is not None + return group + + def freduce(group): + assert group.name is not None + return group.sum() + + def freducex(x): + return freduce(x) + + grouped = df.groupby(grouper, group_keys=False) + + # make sure all these work + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped.apply(f) + grouped.aggregate(freduce) + grouped.aggregate({"C": freduce, "D": freduce}) + grouped.transform(f) + + grouped["C"].apply(f) + grouped["C"].aggregate(freduce) + grouped["C"].aggregate([freduce, freducex]) + grouped["C"].transform(f) + + +def test_group_name_available_in_inference_pass(): + # gh-15062 + df = DataFrame({"a": [0, 0, 1, 1, 2, 2], "b": np.arange(6)}) + + names = [] + + def f(group): + names.append(group.name) + return group.copy() + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby("a", sort=False, group_keys=False).apply(f) + + expected_names = [0, 1, 2] + assert names == expected_names + + +def test_no_dummy_key_names(df): + # see gh-1291 + result = df.groupby(df["A"].values).sum() + assert result.index.name is None + + result2 = df.groupby([df["A"].values, df["B"].values]).sum() + assert result2.index.names == (None, None) + + +def test_groupby_sort_multiindex_series(): + # series multiindex groupby sort argument was not being passed through + # _compress_group_index + # GH 9444 + index = MultiIndex( + levels=[[1, 2], [1, 2]], + codes=[[0, 0, 0, 0, 1, 1], [1, 1, 0, 0, 0, 0]], + names=["a", "b"], + ) + mseries = Series([0, 1, 2, 3, 4, 5], index=index) + index = MultiIndex( + levels=[[1, 2], [1, 2]], codes=[[0, 0, 1], [1, 0, 0]], names=["a", "b"] + ) + mseries_result = Series([0, 2, 4], index=index) + + result = mseries.groupby(level=["a", "b"], sort=False).first() + tm.assert_series_equal(result, mseries_result) + result = mseries.groupby(level=["a", "b"], sort=True).first() + tm.assert_series_equal(result, mseries_result.sort_index()) + + +def test_groupby_reindex_inside_function(): + periods = 1000 + ind = date_range(start="2012/1/1", freq="5min", periods=periods) + df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind) + + def agg_before(func, fix=False): + """ + Run an aggregate func on the subset of data. + """ + + def _func(data): + d = data.loc[data.index.map(lambda x: x.hour < 11)].dropna() + if fix: + data[data.index[0]] + if len(d) == 0: + return None + return func(d) + + return _func + + grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day)) + closure_bad = grouped.agg({"high": agg_before(np.max)}) + closure_good = grouped.agg({"high": agg_before(np.max, True)}) + + tm.assert_frame_equal(closure_bad, closure_good) + + +def test_groupby_multiindex_missing_pair(): + # GH9049 + df = DataFrame( + { + "group1": ["a", "a", "a", "b"], + "group2": ["c", "c", "d", "c"], + "value": [1, 1, 1, 5], + } + ) + df = df.set_index(["group1", "group2"]) + df_grouped = df.groupby(level=["group1", "group2"], sort=True) + + res = df_grouped.agg("sum") + idx = MultiIndex.from_tuples( + [("a", "c"), ("a", "d"), ("b", "c")], names=["group1", "group2"] + ) + exp = DataFrame([[2], [1], [5]], index=idx, columns=["value"]) + + tm.assert_frame_equal(res, exp) + + +def test_groupby_multiindex_not_lexsorted(): + # GH 11640 + + # define the lexsorted version + lexsorted_mi = MultiIndex.from_tuples( + [("a", ""), ("b1", "c1"), ("b2", "c2")], names=["b", "c"] + ) + lexsorted_df = DataFrame([[1, 3, 4]], columns=lexsorted_mi) + assert lexsorted_df.columns._is_lexsorted() + + # define the non-lexsorted version + not_lexsorted_df = DataFrame( + columns=["a", "b", "c", "d"], data=[[1, "b1", "c1", 3], [1, "b2", "c2", 4]] + ) + not_lexsorted_df = not_lexsorted_df.pivot_table( + index="a", columns=["b", "c"], values="d" + ) + not_lexsorted_df = not_lexsorted_df.reset_index() + assert not not_lexsorted_df.columns._is_lexsorted() + + expected = lexsorted_df.groupby("a").mean() + with tm.assert_produces_warning(PerformanceWarning): + result = not_lexsorted_df.groupby("a").mean() + tm.assert_frame_equal(expected, result) + + # a transforming function should work regardless of sort + # GH 14776 + df = DataFrame( + {"x": ["a", "a", "b", "a"], "y": [1, 1, 2, 2], "z": [1, 2, 3, 4]} + ).set_index(["x", "y"]) + assert not df.index._is_lexsorted() + + for level in [0, 1, [0, 1]]: + for sort in [False, True]: + result = df.groupby(level=level, sort=sort, group_keys=False).apply( + DataFrame.drop_duplicates + ) + expected = df + tm.assert_frame_equal(expected, result) + + result = ( + df.sort_index() + .groupby(level=level, sort=sort, group_keys=False) + .apply(DataFrame.drop_duplicates) + ) + expected = df.sort_index() + tm.assert_frame_equal(expected, result) + + +def test_index_label_overlaps_location(): + # checking we don't have any label/location confusion in the + # wake of GH5375 + df = DataFrame(list("ABCDE"), index=[2, 0, 2, 1, 1]) + g = df.groupby(list("ababb")) + actual = g.filter(lambda x: len(x) > 2) + expected = df.iloc[[1, 3, 4]] + tm.assert_frame_equal(actual, expected) + + ser = df[0] + g = ser.groupby(list("ababb")) + actual = g.filter(lambda x: len(x) > 2) + expected = ser.take([1, 3, 4]) + tm.assert_series_equal(actual, expected) + + # and again, with a generic Index of floats + df.index = df.index.astype(float) + g = df.groupby(list("ababb")) + actual = g.filter(lambda x: len(x) > 2) + expected = df.iloc[[1, 3, 4]] + tm.assert_frame_equal(actual, expected) + + ser = df[0] + g = ser.groupby(list("ababb")) + actual = g.filter(lambda x: len(x) > 2) + expected = ser.take([1, 3, 4]) + tm.assert_series_equal(actual, expected) + + +def test_transform_doesnt_clobber_ints(): + # GH 7972 + n = 6 + x = np.arange(n) + df = DataFrame({"a": x // 2, "b": 2.0 * x, "c": 3.0 * x}) + df2 = DataFrame({"a": x // 2 * 1.0, "b": 2.0 * x, "c": 3.0 * x}) + + gb = df.groupby("a") + result = gb.transform("mean") + + gb2 = df2.groupby("a") + expected = gb2.transform("mean") + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "sort_column", + ["ints", "floats", "strings", ["ints", "floats"], ["ints", "strings"]], +) +@pytest.mark.parametrize( + "group_column", ["int_groups", "string_groups", ["int_groups", "string_groups"]] +) +def test_groupby_preserves_sort(sort_column, group_column): + # Test to ensure that groupby always preserves sort order of original + # object. Issue #8588 and #9651 + + df = DataFrame( + { + "int_groups": [3, 1, 0, 1, 0, 3, 3, 3], + "string_groups": ["z", "a", "z", "a", "a", "g", "g", "g"], + "ints": [8, 7, 4, 5, 2, 9, 1, 1], + "floats": [2.3, 5.3, 6.2, -2.4, 2.2, 1.1, 1.1, 5], + "strings": ["z", "d", "a", "e", "word", "word2", "42", "47"], + } + ) + + # Try sorting on different types and with different group types + + df = df.sort_values(by=sort_column) + g = df.groupby(group_column) + + def test_sort(x): + tm.assert_frame_equal(x, x.sort_values(by=sort_column)) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + g.apply(test_sort) + + +def test_pivot_table_values_key_error(): + # This test is designed to replicate the error in issue #14938 + df = DataFrame( + { + "eventDate": date_range(datetime.today(), periods=20, freq="ME").tolist(), + "thename": range(20), + } + ) + + df["year"] = df.set_index("eventDate").index.year + df["month"] = df.set_index("eventDate").index.month + + with pytest.raises(KeyError, match="'badname'"): + df.reset_index().pivot_table( + index="year", columns="month", values="badname", aggfunc="count" + ) + + +@pytest.mark.parametrize("columns", ["C", ["C"]]) +@pytest.mark.parametrize("keys", [["A"], ["A", "B"]]) +@pytest.mark.parametrize( + "values", + [ + [True], + [0], + [0.0], + ["a"], + Categorical([0]), + [to_datetime(0)], + date_range(0, 1, 1, tz="US/Eastern"), + pd.period_range("2016-01-01", periods=3, freq="D"), + pd.array([0], dtype="Int64"), + pd.array([0], dtype="Float64"), + pd.array([False], dtype="boolean"), + ], + ids=[ + "bool", + "int", + "float", + "str", + "cat", + "dt64", + "dt64tz", + "period", + "Int64", + "Float64", + "boolean", + ], +) +@pytest.mark.parametrize("method", ["attr", "agg", "apply"]) +@pytest.mark.parametrize( + "op", ["idxmax", "idxmin", "min", "max", "sum", "prod", "skew"] +) +def test_empty_groupby( + columns, keys, values, method, op, using_array_manager, dropna, using_infer_string +): + # GH8093 & GH26411 + override_dtype = None + + if isinstance(values, BooleanArray) and op in ["sum", "prod"]: + # We expect to get Int64 back for these + override_dtype = "Int64" + + if isinstance(values[0], bool) and op in ("prod", "sum"): + # sum/product of bools is an integer + override_dtype = "int64" + + df = DataFrame({"A": values, "B": values, "C": values}, columns=list("ABC")) + + if hasattr(values, "dtype"): + # check that we did the construction right + assert (df.dtypes == values.dtype).all() + + df = df.iloc[:0] + + gb = df.groupby(keys, group_keys=False, dropna=dropna, observed=False)[columns] + + def get_result(**kwargs): + if method == "attr": + return getattr(gb, op)(**kwargs) + else: + return getattr(gb, method)(op, **kwargs) + + def get_categorical_invalid_expected(): + # Categorical is special without 'observed=True', we get an NaN entry + # corresponding to the unobserved group. If we passed observed=True + # to groupby, expected would just be 'df.set_index(keys)[columns]' + # as below + lev = Categorical([0], dtype=values.dtype) + if len(keys) != 1: + idx = MultiIndex.from_product([lev, lev], names=keys) + else: + # all columns are dropped, but we end up with one row + # Categorical is special without 'observed=True' + idx = Index(lev, name=keys[0]) + + if using_infer_string: + columns = Index([], dtype="str") + else: + columns = [] + expected = DataFrame([], columns=columns, index=idx) + return expected + + is_per = isinstance(df.dtypes.iloc[0], pd.PeriodDtype) + is_dt64 = df.dtypes.iloc[0].kind == "M" + is_cat = isinstance(values, Categorical) + is_str = isinstance(df.dtypes.iloc[0], pd.StringDtype) + + if ( + isinstance(values, Categorical) + and not values.ordered + and op in ["min", "max", "idxmin", "idxmax"] + ): + if op in ["min", "max"]: + msg = f"Cannot perform {op} with non-ordered Categorical" + klass = TypeError + else: + msg = f"Can't get {op} of an empty group due to unobserved categories" + klass = ValueError + with pytest.raises(klass, match=msg): + get_result() + + if op in ["min", "max", "idxmin", "idxmax"] and isinstance(columns, list): + # i.e. DataframeGroupBy, not SeriesGroupBy + result = get_result(numeric_only=True) + expected = get_categorical_invalid_expected() + tm.assert_equal(result, expected) + return + + if op in ["prod", "sum", "skew"]: + # ops that require more than just ordered-ness + if is_dt64 or is_cat or is_per or (is_str and op != "sum"): + # GH#41291 + # datetime64 -> prod and sum are invalid + if is_dt64: + msg = "datetime64 type does not support" + elif is_per: + msg = "Period type does not support" + elif is_str: + msg = f"dtype 'str' does not support operation '{op}'" + else: + msg = "category type does not support" + if op == "skew": + msg = "|".join([msg, "does not support reduction 'skew'"]) + with pytest.raises(TypeError, match=msg): + get_result() + + if not isinstance(columns, list): + # i.e. SeriesGroupBy + return + elif op == "skew": + # TODO: test the numeric_only=True case + return + else: + # i.e. op in ["prod", "sum"]: + # i.e. DataFrameGroupBy + # ops that require more than just ordered-ness + # GH#41291 + result = get_result(numeric_only=True) + + # with numeric_only=True, these are dropped, and we get + # an empty DataFrame back + expected = df.set_index(keys)[[]] + if is_cat: + expected = get_categorical_invalid_expected() + tm.assert_equal(result, expected) + return + + result = get_result() + expected = df.set_index(keys)[columns] + if op in ["idxmax", "idxmin"]: + expected = expected.astype(df.index.dtype) + if override_dtype is not None: + expected = expected.astype(override_dtype) + if len(keys) == 1: + expected.index.name = keys[0] + tm.assert_equal(result, expected) + + +def test_empty_groupby_apply_nonunique_columns(): + # GH#44417 + df = DataFrame(np.random.default_rng(2).standard_normal((0, 4))) + df[3] = df[3].astype(np.int64) + df.columns = [0, 1, 2, 0] + gb = df.groupby(df[1], group_keys=False) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = gb.apply(lambda x: x) + assert (res.dtypes == df.dtypes).all() + + +def test_tuple_as_grouping(): + # https://github.com/pandas-dev/pandas/issues/18314 + df = DataFrame( + { + ("a", "b"): [1, 1, 1, 1], + "a": [2, 2, 2, 2], + "b": [2, 2, 2, 2], + "c": [1, 1, 1, 1], + } + ) + + with pytest.raises(KeyError, match=r"('a', 'b')"): + df[["a", "b", "c"]].groupby(("a", "b")) + + result = df.groupby(("a", "b"))["c"].sum() + expected = Series([4], name="c", index=Index([1], name=("a", "b"))) + tm.assert_series_equal(result, expected) + + +def test_tuple_correct_keyerror(): + # https://github.com/pandas-dev/pandas/issues/18798 + df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]])) + with pytest.raises(KeyError, match=r"^\(7, 8\)$"): + df.groupby((7, 8)).mean() + + +def test_groupby_agg_ohlc_non_first(): + # GH 21716 + df = DataFrame( + [[1], [1]], + columns=Index(["foo"], name="mycols"), + index=date_range("2018-01-01", periods=2, freq="D", name="dti"), + ) + + expected = DataFrame( + [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], + columns=MultiIndex.from_tuples( + ( + ("foo", "sum", "foo"), + ("foo", "ohlc", "open"), + ("foo", "ohlc", "high"), + ("foo", "ohlc", "low"), + ("foo", "ohlc", "close"), + ), + names=["mycols", None, None], + ), + index=date_range("2018-01-01", periods=2, freq="D", name="dti"), + ) + + result = df.groupby(Grouper(freq="D")).agg(["sum", "ohlc"]) + + tm.assert_frame_equal(result, expected) + + +def test_groupby_multiindex_nat(): + # GH 9236 + values = [ + (pd.NaT, "a"), + (datetime(2012, 1, 2), "a"), + (datetime(2012, 1, 2), "b"), + (datetime(2012, 1, 3), "a"), + ] + mi = MultiIndex.from_tuples(values, names=["date", None]) + ser = Series([3, 2, 2.5, 4], index=mi) + + result = ser.groupby(level=1).mean() + expected = Series([3.0, 2.5], index=["a", "b"]) + tm.assert_series_equal(result, expected) + + +def test_groupby_empty_list_raises(): + # GH 5289 + values = zip(range(10), range(10)) + df = DataFrame(values, columns=["apple", "b"]) + msg = "Grouper and axis must be same length" + with pytest.raises(ValueError, match=msg): + df.groupby([[]]) + + +def test_groupby_multiindex_series_keys_len_equal_group_axis(): + # GH 25704 + index_array = [["x", "x"], ["a", "b"], ["k", "k"]] + index_names = ["first", "second", "third"] + ri = MultiIndex.from_arrays(index_array, names=index_names) + s = Series(data=[1, 2], index=ri) + result = s.groupby(["first", "third"]).sum() + + index_array = [["x"], ["k"]] + index_names = ["first", "third"] + ei = MultiIndex.from_arrays(index_array, names=index_names) + expected = Series([3], index=ei) + + tm.assert_series_equal(result, expected) + + +def test_groupby_groups_in_BaseGrouper(): + # GH 26326 + # Test if DataFrame grouped with a pandas.Grouper has correct groups + mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"]) + df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi) + result = df.groupby([Grouper(level="alpha"), "beta"]) + expected = df.groupby(["alpha", "beta"]) + assert result.groups == expected.groups + + result = df.groupby(["beta", Grouper(level="alpha")]) + expected = df.groupby(["beta", "alpha"]) + assert result.groups == expected.groups + + +@pytest.mark.parametrize("group_name", ["x", ["x"]]) +def test_groupby_axis_1(group_name): + # GH 27614 + df = DataFrame( + np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20] + ) + df.index.name = "y" + df.columns.name = "x" + + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(group_name, axis=1) + + results = gb.sum() + expected = df.T.groupby(group_name).sum().T + tm.assert_frame_equal(results, expected) + + # test on MI column + iterables = [["bar", "baz", "foo"], ["one", "two"]] + mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"]) + df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(group_name, axis=1) + results = gb.sum() + expected = df.T.groupby(group_name).sum().T + tm.assert_frame_equal(results, expected) + + +@pytest.mark.parametrize( + "op, expected", + [ + ( + "shift", + { + "time": [ + None, + None, + Timestamp("2019-01-01 12:00:00"), + Timestamp("2019-01-01 12:30:00"), + None, + None, + ] + }, + ), + ( + "bfill", + { + "time": [ + Timestamp("2019-01-01 12:00:00"), + Timestamp("2019-01-01 12:30:00"), + Timestamp("2019-01-01 14:00:00"), + Timestamp("2019-01-01 14:30:00"), + Timestamp("2019-01-01 14:00:00"), + Timestamp("2019-01-01 14:30:00"), + ] + }, + ), + ( + "ffill", + { + "time": [ + Timestamp("2019-01-01 12:00:00"), + Timestamp("2019-01-01 12:30:00"), + Timestamp("2019-01-01 12:00:00"), + Timestamp("2019-01-01 12:30:00"), + Timestamp("2019-01-01 14:00:00"), + Timestamp("2019-01-01 14:30:00"), + ] + }, + ), + ], +) +def test_shift_bfill_ffill_tz(tz_naive_fixture, op, expected): + # GH19995, GH27992: Check that timezone does not drop in shift, bfill, and ffill + tz = tz_naive_fixture + data = { + "id": ["A", "B", "A", "B", "A", "B"], + "time": [ + Timestamp("2019-01-01 12:00:00"), + Timestamp("2019-01-01 12:30:00"), + None, + None, + Timestamp("2019-01-01 14:00:00"), + Timestamp("2019-01-01 14:30:00"), + ], + } + df = DataFrame(data).assign(time=lambda x: x.time.dt.tz_localize(tz)) + + grouped = df.groupby("id") + result = getattr(grouped, op)() + expected = DataFrame(expected).assign(time=lambda x: x.time.dt.tz_localize(tz)) + tm.assert_frame_equal(result, expected) + + +def test_groupby_only_none_group(): + # see GH21624 + # this was crashing with "ValueError: Length of passed values is 1, index implies 0" + df = DataFrame({"g": [None], "x": 1}) + actual = df.groupby("g")["x"].transform("sum") + expected = Series([np.nan], name="x") + + tm.assert_series_equal(actual, expected) + + +def test_groupby_duplicate_index(): + # GH#29189 the groupby call here used to raise + ser = Series([2, 5, 6, 8], index=[2.0, 4.0, 4.0, 5.0]) + gb = ser.groupby(level=0) + + result = gb.mean() + expected = Series([2, 5.5, 8], index=[2.0, 4.0, 5.0]) + tm.assert_series_equal(result, expected) + + +def test_group_on_empty_multiindex(transformation_func, request): + # GH 47787 + # With one row, those are transforms so the schema should be the same + df = DataFrame( + data=[[1, Timestamp("today"), 3, 4]], + columns=["col_1", "col_2", "col_3", "col_4"], + ) + df["col_3"] = df["col_3"].astype(int) + df["col_4"] = df["col_4"].astype(int) + df = df.set_index(["col_1", "col_2"]) + if transformation_func == "fillna": + args = ("ffill",) + else: + args = () + warn = FutureWarning if transformation_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = df.iloc[:0].groupby(["col_1"]).transform(transformation_func, *args) + with tm.assert_produces_warning(warn, match=warn_msg): + expected = df.groupby(["col_1"]).transform(transformation_func, *args).iloc[:0] + if transformation_func in ("diff", "shift"): + expected = expected.astype(int) + tm.assert_equal(result, expected) + + warn_msg = "SeriesGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = ( + df["col_3"] + .iloc[:0] + .groupby(["col_1"]) + .transform(transformation_func, *args) + ) + warn_msg = "SeriesGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + expected = ( + df["col_3"] + .groupby(["col_1"]) + .transform(transformation_func, *args) + .iloc[:0] + ) + if transformation_func in ("diff", "shift"): + expected = expected.astype(int) + tm.assert_equal(result, expected) + + +def test_groupby_crash_on_nunique(axis): + # Fix following 30253 + dti = date_range("2016-01-01", periods=2, name="foo") + df = DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]}) + df.columns.names = ("bar", "baz") + df.index = dti + + axis_number = df._get_axis_number(axis) + if not axis_number: + df = df.T + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + else: + msg = "DataFrame.groupby with axis=1 is deprecated" + + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(axis=axis_number, level=0) + result = gb.nunique() + + expected = DataFrame({"A": [1, 2], "D": [1, 1]}, index=dti) + expected.columns.name = "bar" + if not axis_number: + expected = expected.T + + tm.assert_frame_equal(result, expected) + + if axis_number == 0: + # same thing, but empty columns + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df[[]].groupby(axis=axis_number, level=0) + exp = expected[[]] + else: + # same thing, but empty rows + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df.loc[[]].groupby(axis=axis_number, level=0) + # default for empty when we can't infer a dtype is float64 + exp = expected.loc[[]].astype(np.float64) + + res = gb2.nunique() + tm.assert_frame_equal(res, exp) + + +def test_groupby_list_level(): + # GH 9790 + expected = DataFrame(np.arange(0, 9).reshape(3, 3), dtype=float) + result = expected.groupby(level=[0]).mean() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "max_seq_items, expected", + [ + (5, "{0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}"), + (4, "{0: [0], 1: [1], 2: [2], 3: [3], ...}"), + (1, "{0: [0], ...}"), + ], +) +def test_groups_repr_truncates(max_seq_items, expected): + # GH 1135 + df = DataFrame(np.random.default_rng(2).standard_normal((5, 1))) + df["a"] = df.index + + with pd.option_context("display.max_seq_items", max_seq_items): + result = df.groupby("a").groups.__repr__() + assert result == expected + + result = df.groupby(np.array(df.a)).groups.__repr__() + assert result == expected + + +def test_group_on_two_row_multiindex_returns_one_tuple_key(): + # GH 18451 + df = DataFrame([{"a": 1, "b": 2, "c": 99}, {"a": 1, "b": 2, "c": 88}]) + df = df.set_index(["a", "b"]) + + grp = df.groupby(["a", "b"]) + result = grp.indices + expected = {(1, 2): np.array([0, 1], dtype=np.int64)} + + assert len(result) == 1 + key = (1, 2) + assert (result[key] == expected[key]).all() + + +@pytest.mark.parametrize( + "klass, attr, value", + [ + (DataFrame, "level", "a"), + (DataFrame, "as_index", False), + (DataFrame, "sort", False), + (DataFrame, "group_keys", False), + (DataFrame, "observed", True), + (DataFrame, "dropna", False), + (Series, "level", "a"), + (Series, "as_index", False), + (Series, "sort", False), + (Series, "group_keys", False), + (Series, "observed", True), + (Series, "dropna", False), + ], +) +def test_subsetting_columns_keeps_attrs(klass, attr, value): + # GH 9959 - When subsetting columns, don't drop attributes + df = DataFrame({"a": [1], "b": [2], "c": [3]}) + if attr != "axis": + df = df.set_index("a") + + expected = df.groupby("a", **{attr: value}) + result = expected[["b"]] if klass is DataFrame else expected["b"] + assert getattr(result, attr) == getattr(expected, attr) + + +def test_subsetting_columns_axis_1(): + # GH 37725 + df = DataFrame({"A": [1], "B": [2], "C": [3]}) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + g = df.groupby([0, 0, 1], axis=1) + match = "Cannot subset columns when using axis=1" + with pytest.raises(ValueError, match=match): + g[["A", "B"]].sum() + + +@pytest.mark.parametrize("func", ["sum", "any", "shift"]) +def test_groupby_column_index_name_lost(func): + # GH: 29764 groupby loses index sometimes + expected = Index(["a"], name="idx") + df = DataFrame([[1]], columns=expected) + df_grouped = df.groupby([1]) + result = getattr(df_grouped, func)().columns + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize( + "infer_string", + [ + False, + pytest.param(True, marks=td.skip_if_no("pyarrow")), + ], +) +def test_groupby_duplicate_columns(infer_string): + # GH: 31735 + if infer_string: + pytest.importorskip("pyarrow") + df = DataFrame( + {"A": ["f", "e", "g", "h"], "B": ["a", "b", "c", "d"], "C": [1, 2, 3, 4]} + ).astype(object) + df.columns = ["A", "B", "B"] + with pd.option_context("future.infer_string", infer_string): + result = df.groupby([0, 0, 0, 0]).min() + expected = DataFrame( + [["e", "a", 1]], index=np.array([0]), columns=["A", "B", "B"], dtype=object + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_series_with_tuple_name(): + # GH 37755 + ser = Series([1, 2, 3, 4], index=[1, 1, 2, 2], name=("a", "a")) + ser.index.name = ("b", "b") + result = ser.groupby(level=0).last() + expected = Series([2, 4], index=[1, 2], name=("a", "a")) + expected.index.name = ("b", "b") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func, values", [("sum", [97.0, 98.0]), ("mean", [24.25, 24.5])] +) +def test_groupby_numerical_stability_sum_mean(func, values): + # GH#38778 + data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] + df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) + result = getattr(df.groupby("group"), func)() + expected = DataFrame({"a": values, "b": values}, index=Index([1, 2], name="group")) + tm.assert_frame_equal(result, expected) + + +def test_groupby_numerical_stability_cumsum(): + # GH#38934 + data = [1e16, 1e16, 97, 98, -5e15, -5e15, -5e15, -5e15] + df = DataFrame({"group": [1, 2] * 4, "a": data, "b": data}) + result = df.groupby("group").cumsum() + exp_data = ( + [1e16] * 2 + [1e16 + 96, 1e16 + 98] + [5e15 + 97, 5e15 + 98] + [97.0, 98.0] + ) + expected = DataFrame({"a": exp_data, "b": exp_data}) + tm.assert_frame_equal(result, expected, check_exact=True) + + +def test_groupby_cumsum_skipna_false(): + # GH#46216 don't propagate np.nan above the diagonal + arr = np.random.default_rng(2).standard_normal((5, 5)) + df = DataFrame(arr) + for i in range(5): + df.iloc[i, i] = np.nan + + df["A"] = 1 + gb = df.groupby("A") + + res = gb.cumsum(skipna=False) + + expected = df[[0, 1, 2, 3, 4]].cumsum(skipna=False) + tm.assert_frame_equal(res, expected) + + +def test_groupby_cumsum_timedelta64(): + # GH#46216 don't ignore is_datetimelike in libgroupby.group_cumsum + dti = date_range("2016-01-01", periods=5) + ser = Series(dti) - dti[0] + ser[2] = pd.NaT + + df = DataFrame({"A": 1, "B": ser}) + gb = df.groupby("A") + + res = gb.cumsum(numeric_only=False, skipna=True) + exp = DataFrame({"B": [ser[0], ser[1], pd.NaT, ser[4], ser[4] * 2]}) + tm.assert_frame_equal(res, exp) + + res = gb.cumsum(numeric_only=False, skipna=False) + exp = DataFrame({"B": [ser[0], ser[1], pd.NaT, pd.NaT, pd.NaT]}) + tm.assert_frame_equal(res, exp) + + +def test_groupby_mean_duplicate_index(rand_series_with_duplicate_datetimeindex): + dups = rand_series_with_duplicate_datetimeindex + result = dups.groupby(level=0).mean() + expected = dups.groupby(dups.index).mean() + tm.assert_series_equal(result, expected) + + +def test_groupby_all_nan_groups_drop(): + # GH 15036 + s = Series([1, 2, 3], [np.nan, np.nan, np.nan]) + result = s.groupby(s.index).sum() + expected = Series([], index=Index([], dtype=np.float64), dtype=np.int64) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_groupby_empty_multi_column(as_index, numeric_only): + # GH 15106 & GH 41998 + df = DataFrame(data=[], columns=["A", "B", "C"]) + gb = df.groupby(["A", "B"], as_index=as_index) + result = gb.sum(numeric_only=numeric_only) + if as_index: + index = MultiIndex([[], []], [[], []], names=["A", "B"]) + columns = ["C"] if not numeric_only else Index([], dtype="str") + else: + index = RangeIndex(0) + columns = ["A", "B", "C"] if not numeric_only else ["A", "B"] + expected = DataFrame([], columns=columns, index=index) + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_non_numeric_dtype(): + # GH #43108 + df = DataFrame( + [["M", [1]], ["M", [1]], ["W", [10]], ["W", [20]]], columns=["MW", "v"] + ) + + expected = DataFrame( + { + "v": [[1, 1], [10, 20]], + }, + index=Index(["M", "W"], name="MW"), + ) + + gb = df.groupby(by=["MW"]) + result = gb.sum() + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_multi_non_numeric_dtype(): + # GH #42395 + df = DataFrame( + { + "x": [1, 0, 1, 1, 0], + "y": [Timedelta(i, "days") for i in range(1, 6)], + "z": [Timedelta(i * 10, "days") for i in range(1, 6)], + } + ) + + expected = DataFrame( + { + "y": [Timedelta(i, "days") for i in range(7, 9)], + "z": [Timedelta(i * 10, "days") for i in range(7, 9)], + }, + index=Index([0, 1], dtype="int64", name="x"), + ) + + gb = df.groupby(by=["x"]) + result = gb.sum() + tm.assert_frame_equal(result, expected) + + +def test_groupby_aggregation_numeric_with_non_numeric_dtype(): + # GH #43108 + df = DataFrame( + { + "x": [1, 0, 1, 1, 0], + "y": [Timedelta(i, "days") for i in range(1, 6)], + "z": list(range(1, 6)), + } + ) + + expected = DataFrame( + {"y": [Timedelta(7, "days"), Timedelta(8, "days")], "z": [7, 8]}, + index=Index([0, 1], dtype="int64", name="x"), + ) + + gb = df.groupby(by=["x"]) + result = gb.sum() + tm.assert_frame_equal(result, expected) + + +def test_groupby_filtered_df_std(): + # GH 16174 + dicts = [ + {"filter_col": False, "groupby_col": True, "bool_col": True, "float_col": 10.5}, + {"filter_col": True, "groupby_col": True, "bool_col": True, "float_col": 20.5}, + {"filter_col": True, "groupby_col": True, "bool_col": True, "float_col": 30.5}, + ] + df = DataFrame(dicts) + + df_filter = df[df["filter_col"] == True] # noqa: E712 + dfgb = df_filter.groupby("groupby_col") + result = dfgb.std() + expected = DataFrame( + [[0.0, 0.0, 7.071068]], + columns=["filter_col", "bool_col", "float_col"], + index=Index([True], name="groupby_col"), + ) + tm.assert_frame_equal(result, expected) + + +def test_datetime_categorical_multikey_groupby_indices(): + # GH 26859 + df = DataFrame( + { + "a": Series(list("abc")), + "b": Series( + to_datetime(["2018-01-01", "2018-02-01", "2018-03-01"]), + dtype="category", + ), + "c": Categorical.from_codes([-1, 0, 1], categories=[0, 1]), + } + ) + result = df.groupby(["a", "b"], observed=False).indices + expected = { + ("a", Timestamp("2018-01-01 00:00:00")): np.array([0]), + ("b", Timestamp("2018-02-01 00:00:00")): np.array([1]), + ("c", Timestamp("2018-03-01 00:00:00")): np.array([2]), + } + assert result == expected + + +def test_rolling_wrong_param_min_period(): + # GH34037 + name_l = ["Alice"] * 5 + ["Bob"] * 5 + val_l = [np.nan, np.nan, 1, 2, 3] + [np.nan, 1, 2, 3, 4] + test_df = DataFrame([name_l, val_l]).T + test_df.columns = ["name", "val"] + + result_error_msg = ( + r"^[a-zA-Z._]*\(\) got an unexpected keyword argument 'min_period'" + ) + with pytest.raises(TypeError, match=result_error_msg): + test_df.groupby("name")["val"].rolling(window=2, min_period=1).sum() + + +def test_by_column_values_with_same_starting_value(any_string_dtype): + # GH29635 + df = DataFrame( + { + "Name": ["Thomas", "Thomas", "Thomas John"], + "Credit": [1200, 1300, 900], + "Mood": Series(["sad", "happy", "happy"], dtype=any_string_dtype), + } + ) + aggregate_details = {"Mood": Series.mode, "Credit": "sum"} + + result = df.groupby(["Name"]).agg(aggregate_details) + expected_result = DataFrame( + { + "Mood": [["happy", "sad"], "happy"], + "Credit": [2500, 900], + "Name": ["Thomas", "Thomas John"], + } + ).set_index("Name") + + tm.assert_frame_equal(result, expected_result) + + +def test_groupby_none_in_first_mi_level(): + # GH#47348 + arr = [[None, 1, 0, 1], [2, 3, 2, 3]] + ser = Series(1, index=MultiIndex.from_arrays(arr, names=["a", "b"])) + result = ser.groupby(level=[0, 1]).sum() + expected = Series( + [1, 2], MultiIndex.from_tuples([(0.0, 2), (1.0, 3)], names=["a", "b"]) + ) + tm.assert_series_equal(result, expected) + + +def test_groupby_none_column_name(using_infer_string): + # GH#47348 + df = DataFrame({None: [1, 1, 2, 2], "b": [1, 1, 2, 3], "c": [4, 5, 6, 7]}) + by = [np.nan] if using_infer_string else [None] + gb = df.groupby(by=by) + result = gb.sum() + expected = DataFrame({"b": [2, 5], "c": [9, 13]}, index=Index([1, 2], name=by[0])) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("selection", [None, "a", ["a"]]) +def test_single_element_list_grouping(selection): + # GH#42795, GH#53500 + df = DataFrame({"a": [1, 2], "b": [np.nan, 5], "c": [np.nan, 2]}, index=["x", "y"]) + grouped = df.groupby(["a"]) if selection is None else df.groupby(["a"])[selection] + result = [key for key, _ in grouped] + + expected = [(1,), (2,)] + assert result == expected + + +def test_groupby_string_dtype(): + # GH 40148 + df = DataFrame({"str_col": ["a", "b", "c", "a"], "num_col": [1, 2, 3, 2]}) + df["str_col"] = df["str_col"].astype("string") + expected = DataFrame( + { + "str_col": [ + "a", + "b", + "c", + ], + "num_col": [1.5, 2.0, 3.0], + } + ) + expected["str_col"] = expected["str_col"].astype("string") + grouped = df.groupby("str_col", as_index=False) + result = grouped.mean() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "level_arg, multiindex", [([0], False), ((0,), False), ([0], True), ((0,), True)] +) +def test_single_element_listlike_level_grouping_deprecation(level_arg, multiindex): + # GH 51583 + df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"]) + if multiindex: + df = df.set_index(["a", "b"]) + depr_msg = ( + "Creating a Groupby object with a length-1 list-like " + "level parameter will yield indexes as tuples in a future version. " + "To keep indexes as scalars, create Groupby objects with " + "a scalar level parameter instead." + ) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + [key for key, _ in df.groupby(level=level_arg)] + + +@pytest.mark.parametrize("func", ["sum", "cumsum", "cumprod", "prod"]) +def test_groupby_avoid_casting_to_float(func): + # GH#37493 + val = 922337203685477580 + df = DataFrame({"a": 1, "b": [val]}) + result = getattr(df.groupby("a"), func)() - val + expected = DataFrame({"b": [0]}, index=Index([1], name="a")) + if func in ["cumsum", "cumprod"]: + expected = expected.reset_index(drop=True) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func, val", [("sum", 3), ("prod", 2)]) +def test_groupby_sum_support_mask(any_numeric_ea_dtype, func, val): + # GH#37493 + df = DataFrame({"a": 1, "b": [1, 2, pd.NA]}, dtype=any_numeric_ea_dtype) + result = getattr(df.groupby("a"), func)() + expected = DataFrame( + {"b": [val]}, + index=Index([1], name="a", dtype=any_numeric_ea_dtype), + dtype=any_numeric_ea_dtype, + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("val, dtype", [(111, "int"), (222, "uint")]) +def test_groupby_overflow(val, dtype): + # GH#37493 + df = DataFrame({"a": 1, "b": [val, val]}, dtype=f"{dtype}8") + result = df.groupby("a").sum() + expected = DataFrame( + {"b": [val * 2]}, + index=Index([1], name="a", dtype=f"{dtype}8"), + dtype=f"{dtype}64", + ) + tm.assert_frame_equal(result, expected) + + result = df.groupby("a").cumsum() + expected = DataFrame({"b": [val, val * 2]}, dtype=f"{dtype}64") + tm.assert_frame_equal(result, expected) + + result = df.groupby("a").prod() + expected = DataFrame( + {"b": [val * val]}, + index=Index([1], name="a", dtype=f"{dtype}8"), + dtype=f"{dtype}64", + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("skipna, val", [(True, 3), (False, pd.NA)]) +def test_groupby_cumsum_mask(any_numeric_ea_dtype, skipna, val): + # GH#37493 + df = DataFrame({"a": 1, "b": [1, pd.NA, 2]}, dtype=any_numeric_ea_dtype) + result = df.groupby("a").cumsum(skipna=skipna) + expected = DataFrame( + {"b": [1, pd.NA, val]}, + dtype=any_numeric_ea_dtype, + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "val_in, index, val_out", + [ + ( + [1.0, 2.0, 3.0, 4.0, 5.0], + ["foo", "foo", "bar", "baz", "blah"], + [3.0, 4.0, 5.0, 3.0], + ), + ( + [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + ["foo", "foo", "bar", "baz", "blah", "blah"], + [3.0, 4.0, 11.0, 3.0], + ), + ], +) +def test_groupby_index_name_in_index_content(val_in, index, val_out): + # GH 48567 + series = Series(data=val_in, name="values", index=Index(index, name="blah")) + result = series.groupby("blah").sum() + expected = Series( + data=val_out, + name="values", + index=Index(["bar", "baz", "blah", "foo"], name="blah"), + ) + tm.assert_series_equal(result, expected) + + result = series.to_frame().groupby("blah").sum() + expected = expected.to_frame() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("n", [1, 10, 32, 100, 1000]) +def test_sum_of_booleans(n): + # GH 50347 + df = DataFrame({"groupby_col": 1, "bool": [True] * n}) + df["bool"] = df["bool"].eq(True) + result = df.groupby("groupby_col").sum() + expected = DataFrame({"bool": [n]}, index=Index([1], name="groupby_col")) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.filterwarnings( + "ignore:invalid value encountered in remainder:RuntimeWarning" +) +@pytest.mark.parametrize("method", ["head", "tail", "nth", "first", "last"]) +def test_groupby_method_drop_na(method): + # GH 21755 + df = DataFrame({"A": ["a", np.nan, "b", np.nan, "c"], "B": range(5)}) + + if method == "nth": + result = getattr(df.groupby("A"), method)(n=0) + else: + result = getattr(df.groupby("A"), method)() + + if method in ["first", "last"]: + expected = DataFrame({"B": [0, 2, 4]}).set_index( + Series(["a", "b", "c"], name="A") + ) + else: + expected = DataFrame({"A": ["a", "b", "c"], "B": [0, 2, 4]}, index=[0, 2, 4]) + tm.assert_frame_equal(result, expected) + + +def test_groupby_reduce_period(): + # GH#51040 + pi = pd.period_range("2016-01-01", periods=100, freq="D") + grps = list(range(10)) * 10 + ser = pi.to_series() + gb = ser.groupby(grps) + + with pytest.raises(TypeError, match="Period type does not support sum operations"): + gb.sum() + with pytest.raises( + TypeError, match="Period type does not support cumsum operations" + ): + gb.cumsum() + with pytest.raises(TypeError, match="Period type does not support prod operations"): + gb.prod() + with pytest.raises( + TypeError, match="Period type does not support cumprod operations" + ): + gb.cumprod() + + res = gb.max() + expected = ser[-10:] + expected.index = Index(range(10), dtype=int) + tm.assert_series_equal(res, expected) + + res = gb.min() + expected = ser[:10] + expected.index = Index(range(10), dtype=int) + tm.assert_series_equal(res, expected) + + +def test_obj_with_exclusions_duplicate_columns(): + # GH#50806 + df = DataFrame([[0, 1, 2, 3]]) + df.columns = [0, 1, 2, 0] + gb = df.groupby(df[1]) + result = gb._obj_with_exclusions + expected = df.take([0, 2, 3], axis=1) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_groupby_numeric_only_std_no_result(numeric_only): + # GH 51080 + dicts_non_numeric = [{"a": "foo", "b": "bar"}, {"a": "car", "b": "dar"}] + df = DataFrame(dicts_non_numeric, dtype=object) + dfgb = df.groupby("a", as_index=False, sort=False) + + if numeric_only: + result = dfgb.std(numeric_only=True) + expected_df = DataFrame(["foo", "car"], columns=["a"]) + tm.assert_frame_equal(result, expected_df) + else: + with pytest.raises( + ValueError, match="could not convert string to float: 'bar'" + ): + dfgb.std(numeric_only=numeric_only) + + +@pytest.mark.filterwarnings("ignore:invalid value encountered in cast:RuntimeWarning") +def test_grouping_with_categorical_interval_columns(): + # GH#34164 + df = DataFrame({"x": [0.1, 0.2, 0.3, -0.4, 0.5], "w": ["a", "b", "a", "c", "a"]}) + qq = pd.qcut(df["x"], q=np.linspace(0, 1, 5)) + result = df.groupby([qq, "w"], observed=False)["x"].agg("mean") + categorical_index_level_1 = Categorical( + [ + Interval(-0.401, 0.1, closed="right"), + Interval(0.1, 0.2, closed="right"), + Interval(0.2, 0.3, closed="right"), + Interval(0.3, 0.5, closed="right"), + ], + ordered=True, + ) + index_level_2 = ["a", "b", "c"] + mi = MultiIndex.from_product( + [categorical_index_level_1, index_level_2], names=["x", "w"] + ) + expected = Series( + np.array( + [ + 0.1, + np.nan, + -0.4, + np.nan, + 0.2, + np.nan, + 0.3, + np.nan, + np.nan, + 0.5, + np.nan, + np.nan, + ] + ), + index=mi, + name="x", + ) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("bug_var", [1, "a"]) +def test_groupby_sum_on_nan_should_return_nan(bug_var): + # GH 24196 + df = DataFrame({"A": [bug_var, bug_var, bug_var, np.nan]}) + if isinstance(bug_var, str): + df = df.astype(object) + dfgb = df.groupby(lambda x: x) + result = dfgb.sum(min_count=1) + + expected_df = DataFrame( + [bug_var, bug_var, bug_var, None], columns=["A"], dtype=df["A"].dtype + ) + tm.assert_frame_equal(result, expected_df) + + +@pytest.mark.parametrize( + "method", + [ + "count", + "corr", + "cummax", + "cummin", + "cumprod", + "describe", + "rank", + "quantile", + "diff", + "shift", + "all", + "any", + "idxmin", + "idxmax", + "ffill", + "bfill", + "pct_change", + ], +) +def test_groupby_selection_with_methods(df, method): + # some methods which require DatetimeIndex + rng = date_range("2014", periods=len(df)) + df.index = rng + + g = df.groupby(["A"])[["C"]] + g_exp = df[["C"]].groupby(df["A"]) + # TODO check groupby with > 1 col ? + + res = getattr(g, method)() + exp = getattr(g_exp, method)() + + # should always be frames! + tm.assert_frame_equal(res, exp) + + +def test_groupby_selection_other_methods(df): + # some methods which require DatetimeIndex + rng = date_range("2014", periods=len(df)) + df.columns.name = "foo" + df.index = rng + + g = df.groupby(["A"])[["C"]] + g_exp = df[["C"]].groupby(df["A"]) + + # methods which aren't just .foo() + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + tm.assert_frame_equal(g.fillna(0), g_exp.fillna(0)) + msg = "DataFrameGroupBy.dtypes is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + tm.assert_frame_equal(g.dtypes, g_exp.dtypes) + tm.assert_frame_equal(g.apply(lambda x: x.sum()), g_exp.apply(lambda x: x.sum())) + + tm.assert_frame_equal(g.resample("D").mean(), g_exp.resample("D").mean()) + tm.assert_frame_equal(g.resample("D").ohlc(), g_exp.resample("D").ohlc()) + + tm.assert_frame_equal( + g.filter(lambda x: len(x) == 3), g_exp.filter(lambda x: len(x) == 3) + ) + + +def test_groupby_with_Time_Grouper(unit): + idx2 = to_datetime( + [ + "2016-08-31 22:08:12.000", + "2016-08-31 22:09:12.200", + "2016-08-31 22:20:12.400", + ] + ).as_unit(unit) + + test_data = DataFrame( + {"quant": [1.0, 1.0, 3.0], "quant2": [1.0, 1.0, 3.0], "time2": idx2} + ) + + time2 = date_range("2016-08-31 22:08:00", periods=13, freq="1min", unit=unit) + expected_output = DataFrame( + { + "time2": time2, + "quant": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + "quant2": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + } + ) + + gb = test_data.groupby(Grouper(key="time2", freq="1min")) + result = gb.count().reset_index() + + tm.assert_frame_equal(result, expected_output) + + +def test_groupby_series_with_datetimeindex_month_name(): + # GH 48509 + s = Series([0, 1, 0], index=date_range("2022-01-01", periods=3), name="jan") + result = s.groupby(s).count() + expected = Series([2, 1], name="jan") + expected.index.name = "jan" + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("test_series", [True, False]) +@pytest.mark.parametrize( + "kwarg, value, name, warn", + [ + ("by", "a", 1, None), + ("by", ["a"], 1, FutureWarning), + ("by", ["a"], (1,), None), + ("level", 0, 1, None), + ("level", [0], 1, FutureWarning), + ("level", [0], (1,), None), + ], +) +def test_depr_get_group_len_1_list_likes(test_series, kwarg, value, name, warn): + # GH#25971 + obj = DataFrame({"b": [3, 4, 5]}, index=Index([1, 1, 2], name="a")) + if test_series: + obj = obj["b"] + gb = obj.groupby(**{kwarg: value}) + msg = "you will need to pass a length-1 tuple" + with tm.assert_produces_warning(warn, match=msg): + result = gb.get_group(name) + if test_series: + expected = Series([3, 4], index=Index([1, 1], name="a"), name="b") + else: + expected = DataFrame({"b": [3, 4]}, index=Index([1, 1], name="a")) + tm.assert_equal(result, expected) + + +def test_groupby_ngroup_with_nan(): + # GH#50100 + df = DataFrame({"a": Categorical([np.nan]), "b": [1]}) + result = df.groupby(["a", "b"], dropna=False, observed=False).ngroup() + expected = Series([0]) + tm.assert_series_equal(result, expected) + + +def test_get_group_axis_1(): + # GH#54858 + df = DataFrame( + { + "col1": [0, 3, 2, 3], + "col2": [4, 1, 6, 7], + "col3": [3, 8, 2, 10], + "col4": [1, 13, 6, 15], + "col5": [-4, 5, 6, -7], + } + ) + with tm.assert_produces_warning(FutureWarning, match="deprecated"): + grouped = df.groupby(axis=1, by=[1, 2, 3, 2, 1]) + result = grouped.get_group(1) + expected = DataFrame( + { + "col1": [0, 3, 2, 3], + "col5": [-4, 5, 6, -7], + } + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_ffill_with_duplicated_index(): + # GH#43412 + df = DataFrame({"a": [1, 2, 3, 4, np.nan, np.nan]}, index=[0, 1, 2, 0, 1, 2]) + + result = df.groupby(level=0).ffill() + expected = DataFrame({"a": [1, 2, 3, 4, 2, 3]}, index=[0, 1, 2, 0, 1, 2]) + tm.assert_frame_equal(result, expected, check_dtype=False) + + +@pytest.mark.parametrize("test_series", [True, False]) +def test_decimal_na_sort(test_series): + # GH#54847 + # We catch both TypeError and decimal.InvalidOperation exceptions in safe_sort. + # If this next assert raises, we can just catch TypeError + assert not isinstance(decimal.InvalidOperation, TypeError) + df = DataFrame( + { + "key": [Decimal(1), Decimal(1), None, None], + "value": [Decimal(2), Decimal(3), Decimal(4), Decimal(5)], + } + ) + gb = df.groupby("key", dropna=False) + if test_series: + gb = gb["value"] + result = gb._grouper.result_index + expected = Index([Decimal(1), None], name="key") + tm.assert_index_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_dropna.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_dropna.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9b61aa7ebf5cb27890536a5105a79fb6cae096 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_dropna.py @@ -0,0 +1,696 @@ +import numpy as np +import pytest + +from pandas.compat.pyarrow import pa_version_under10p1 + +from pandas.core.dtypes.missing import na_value_for_dtype + +import pandas as pd +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +@pytest.mark.parametrize( + "dropna, tuples, outputs", + [ + ( + True, + [["A", "B"], ["B", "A"]], + {"c": [13.0, 123.23], "d": [13.0, 123.0], "e": [13.0, 1.0]}, + ), + ( + False, + [["A", "B"], ["A", np.nan], ["B", "A"]], + { + "c": [13.0, 12.3, 123.23], + "d": [13.0, 233.0, 123.0], + "e": [13.0, 12.0, 1.0], + }, + ), + ], +) +def test_groupby_dropna_multi_index_dataframe_nan_in_one_group( + dropna, tuples, outputs, nulls_fixture +): + # GH 3729 this is to test that NA is in one group + df_list = [ + ["A", "B", 12, 12, 12], + ["A", nulls_fixture, 12.3, 233.0, 12], + ["B", "A", 123.23, 123, 1], + ["A", "B", 1, 1, 1.0], + ] + df = pd.DataFrame(df_list, columns=["a", "b", "c", "d", "e"]) + grouped = df.groupby(["a", "b"], dropna=dropna).sum() + + mi = pd.MultiIndex.from_tuples(tuples, names=list("ab")) + + # Since right now, by default MI will drop NA from levels when we create MI + # via `from_*`, so we need to add NA for level manually afterwards. + if not dropna: + mi = mi.set_levels(["A", "B", np.nan], level="b") + expected = pd.DataFrame(outputs, index=mi) + + tm.assert_frame_equal(grouped, expected) + + +@pytest.mark.parametrize( + "dropna, tuples, outputs", + [ + ( + True, + [["A", "B"], ["B", "A"]], + {"c": [12.0, 123.23], "d": [12.0, 123.0], "e": [12.0, 1.0]}, + ), + ( + False, + [["A", "B"], ["A", np.nan], ["B", "A"], [np.nan, "B"]], + { + "c": [12.0, 13.3, 123.23, 1.0], + "d": [12.0, 234.0, 123.0, 1.0], + "e": [12.0, 13.0, 1.0, 1.0], + }, + ), + ], +) +def test_groupby_dropna_multi_index_dataframe_nan_in_two_groups( + dropna, tuples, outputs, nulls_fixture, nulls_fixture2 +): + # GH 3729 this is to test that NA in different groups with different representations + df_list = [ + ["A", "B", 12, 12, 12], + ["A", nulls_fixture, 12.3, 233.0, 12], + ["B", "A", 123.23, 123, 1], + [nulls_fixture2, "B", 1, 1, 1.0], + ["A", nulls_fixture2, 1, 1, 1.0], + ] + df = pd.DataFrame(df_list, columns=["a", "b", "c", "d", "e"]) + grouped = df.groupby(["a", "b"], dropna=dropna).sum() + + mi = pd.MultiIndex.from_tuples(tuples, names=list("ab")) + + # Since right now, by default MI will drop NA from levels when we create MI + # via `from_*`, so we need to add NA for level manually afterwards. + if not dropna: + mi = mi.set_levels([["A", "B", np.nan], ["A", "B", np.nan]]) + expected = pd.DataFrame(outputs, index=mi) + + tm.assert_frame_equal(grouped, expected) + + +@pytest.mark.parametrize( + "dropna, idx, outputs", + [ + (True, ["A", "B"], {"b": [123.23, 13.0], "c": [123.0, 13.0], "d": [1.0, 13.0]}), + ( + False, + ["A", "B", np.nan], + { + "b": [123.23, 13.0, 12.3], + "c": [123.0, 13.0, 233.0], + "d": [1.0, 13.0, 12.0], + }, + ), + ], +) +def test_groupby_dropna_normal_index_dataframe(dropna, idx, outputs): + # GH 3729 + df_list = [ + ["B", 12, 12, 12], + [None, 12.3, 233.0, 12], + ["A", 123.23, 123, 1], + ["B", 1, 1, 1.0], + ] + df = pd.DataFrame(df_list, columns=["a", "b", "c", "d"]) + grouped = df.groupby("a", dropna=dropna).sum() + + expected = pd.DataFrame(outputs, index=pd.Index(idx, name="a")) + + tm.assert_frame_equal(grouped, expected) + + +@pytest.mark.parametrize( + "dropna, idx, expected", + [ + (True, ["a", "a", "b", np.nan], pd.Series([3, 3], index=["a", "b"])), + ( + False, + ["a", "a", "b", np.nan], + pd.Series([3, 3, 3], index=["a", "b", np.nan]), + ), + ], +) +def test_groupby_dropna_series_level(dropna, idx, expected): + ser = pd.Series([1, 2, 3, 3], index=idx) + + result = ser.groupby(level=0, dropna=dropna).sum() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "dropna, expected", + [ + (True, pd.Series([210.0, 350.0], index=["a", "b"], name="Max Speed")), + ( + False, + pd.Series([210.0, 350.0, 20.0], index=["a", "b", np.nan], name="Max Speed"), + ), + ], +) +def test_groupby_dropna_series_by(dropna, expected): + ser = pd.Series( + [390.0, 350.0, 30.0, 20.0], + index=["Falcon", "Falcon", "Parrot", "Parrot"], + name="Max Speed", + ) + + result = ser.groupby(["a", "b", "a", np.nan], dropna=dropna).mean() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("dropna", (False, True)) +def test_grouper_dropna_propagation(dropna): + # GH 36604 + df = pd.DataFrame({"A": [0, 0, 1, None], "B": [1, 2, 3, None]}) + gb = df.groupby("A", dropna=dropna) + assert gb._grouper.dropna == dropna + + +@pytest.mark.parametrize( + "index", + [ + pd.RangeIndex(0, 4), + list("abcd"), + pd.MultiIndex.from_product([(1, 2), ("R", "B")], names=["num", "col"]), + ], +) +def test_groupby_dataframe_slice_then_transform(dropna, index): + # GH35014 & GH35612 + expected_data = {"B": [2, 2, 1, np.nan if dropna else 1]} + + df = pd.DataFrame({"A": [0, 0, 1, None], "B": [1, 2, 3, None]}, index=index) + gb = df.groupby("A", dropna=dropna) + + result = gb.transform(len) + expected = pd.DataFrame(expected_data, index=index) + tm.assert_frame_equal(result, expected) + + result = gb[["B"]].transform(len) + expected = pd.DataFrame(expected_data, index=index) + tm.assert_frame_equal(result, expected) + + result = gb["B"].transform(len) + expected = pd.Series(expected_data["B"], index=index, name="B") + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "dropna, tuples, outputs", + [ + ( + True, + [["A", "B"], ["B", "A"]], + {"c": [13.0, 123.23], "d": [12.0, 123.0], "e": [1.0, 1.0]}, + ), + ( + False, + [["A", "B"], ["A", np.nan], ["B", "A"]], + { + "c": [13.0, 12.3, 123.23], + "d": [12.0, 233.0, 123.0], + "e": [1.0, 12.0, 1.0], + }, + ), + ], +) +def test_groupby_dropna_multi_index_dataframe_agg(dropna, tuples, outputs): + # GH 3729 + df_list = [ + ["A", "B", 12, 12, 12], + ["A", None, 12.3, 233.0, 12], + ["B", "A", 123.23, 123, 1], + ["A", "B", 1, 1, 1.0], + ] + df = pd.DataFrame(df_list, columns=["a", "b", "c", "d", "e"]) + agg_dict = {"c": "sum", "d": "max", "e": "min"} + grouped = df.groupby(["a", "b"], dropna=dropna).agg(agg_dict) + + mi = pd.MultiIndex.from_tuples(tuples, names=list("ab")) + + # Since right now, by default MI will drop NA from levels when we create MI + # via `from_*`, so we need to add NA for level manually afterwards. + if not dropna: + mi = mi.set_levels(["A", "B", np.nan], level="b") + expected = pd.DataFrame(outputs, index=mi) + + tm.assert_frame_equal(grouped, expected) + + +@pytest.mark.arm_slow +@pytest.mark.parametrize( + "datetime1, datetime2", + [ + (pd.Timestamp("2020-01-01"), pd.Timestamp("2020-02-01")), + (pd.Timedelta("-2 days"), pd.Timedelta("-1 days")), + (pd.Period("2020-01-01"), pd.Period("2020-02-01")), + ], +) +@pytest.mark.parametrize("dropna, values", [(True, [12, 3]), (False, [12, 3, 6])]) +def test_groupby_dropna_datetime_like_data( + dropna, values, datetime1, datetime2, unique_nulls_fixture, unique_nulls_fixture2 +): + # 3729 + df = pd.DataFrame( + { + "values": [1, 2, 3, 4, 5, 6], + "dt": [ + datetime1, + unique_nulls_fixture, + datetime2, + unique_nulls_fixture2, + datetime1, + datetime1, + ], + } + ) + + if dropna: + indexes = [datetime1, datetime2] + else: + indexes = [datetime1, datetime2, np.nan] + + grouped = df.groupby("dt", dropna=dropna).agg({"values": "sum"}) + expected = pd.DataFrame({"values": values}, index=pd.Index(indexes, name="dt")) + + tm.assert_frame_equal(grouped, expected) + + +@pytest.mark.parametrize( + "dropna, data, selected_data, levels", + [ + pytest.param( + False, + {"groups": ["a", "a", "b", np.nan], "values": [10, 10, 20, 30]}, + {"values": [0, 1, 0, 0]}, + ["a", "b", np.nan], + id="dropna_false_has_nan", + ), + pytest.param( + True, + {"groups": ["a", "a", "b", np.nan], "values": [10, 10, 20, 30]}, + {"values": [0, 1, 0]}, + None, + id="dropna_true_has_nan", + ), + pytest.param( + # no nan in "groups"; dropna=True|False should be same. + False, + {"groups": ["a", "a", "b", "c"], "values": [10, 10, 20, 30]}, + {"values": [0, 1, 0, 0]}, + None, + id="dropna_false_no_nan", + ), + pytest.param( + # no nan in "groups"; dropna=True|False should be same. + True, + {"groups": ["a", "a", "b", "c"], "values": [10, 10, 20, 30]}, + {"values": [0, 1, 0, 0]}, + None, + id="dropna_true_no_nan", + ), + ], +) +def test_groupby_apply_with_dropna_for_multi_index(dropna, data, selected_data, levels): + # GH 35889 + + df = pd.DataFrame(data) + gb = df.groupby("groups", dropna=dropna) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = gb.apply(lambda grp: pd.DataFrame({"values": range(len(grp))})) + + mi_tuples = tuple(zip(data["groups"], selected_data["values"])) + mi = pd.MultiIndex.from_tuples(mi_tuples, names=["groups", None]) + # Since right now, by default MI will drop NA from levels when we create MI + # via `from_*`, so we need to add NA for level manually afterwards. + if not dropna and levels: + mi = mi.set_levels(levels, level="groups") + + expected = pd.DataFrame(selected_data, index=mi) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("input_index", [None, ["a"], ["a", "b"]]) +@pytest.mark.parametrize("keys", [["a"], ["a", "b"]]) +@pytest.mark.parametrize("series", [True, False]) +def test_groupby_dropna_with_multiindex_input(input_index, keys, series): + # GH#46783 + obj = pd.DataFrame( + { + "a": [1, np.nan], + "b": [1, 1], + "c": [2, 3], + } + ) + + expected = obj.set_index(keys) + if series: + expected = expected["c"] + elif input_index == ["a", "b"] and keys == ["a"]: + # Column b should not be aggregated + expected = expected[["c"]] + + if input_index is not None: + obj = obj.set_index(input_index) + gb = obj.groupby(keys, dropna=False) + if series: + gb = gb["c"] + result = gb.sum() + + tm.assert_equal(result, expected) + + +def test_groupby_nan_included(): + # GH 35646 + data = {"group": ["g1", np.nan, "g1", "g2", np.nan], "B": [0, 1, 2, 3, 4]} + df = pd.DataFrame(data) + grouped = df.groupby("group", dropna=False) + result = grouped.indices + dtype = np.intp + expected = { + "g1": np.array([0, 2], dtype=dtype), + "g2": np.array([3], dtype=dtype), + np.nan: np.array([1, 4], dtype=dtype), + } + for result_values, expected_values in zip(result.values(), expected.values()): + tm.assert_numpy_array_equal(result_values, expected_values) + assert np.isnan(list(result.keys())[2]) + assert list(result.keys())[0:2] == ["g1", "g2"] + + +def test_groupby_drop_nan_with_multi_index(): + # GH 39895 + df = pd.DataFrame([[np.nan, 0, 1]], columns=["a", "b", "c"]) + df = df.set_index(["a", "b"]) + result = df.groupby(["a", "b"], dropna=False).first() + expected = df + tm.assert_frame_equal(result, expected) + + +# sequence_index enumerates all strings made up of x, y, z of length 4 +@pytest.mark.parametrize("sequence_index", range(3**4)) +@pytest.mark.parametrize( + "dtype", + [ + None, + "UInt8", + "Int8", + "UInt16", + "Int16", + "UInt32", + "Int32", + "UInt64", + "Int64", + "Float32", + "Int64", + "Float64", + "category", + "string", + pytest.param( + "string[pyarrow]", + marks=pytest.mark.skipif( + pa_version_under10p1, reason="pyarrow is not installed" + ), + ), + "datetime64[ns]", + "period[d]", + "Sparse[float]", + ], +) +@pytest.mark.parametrize("test_series", [True, False]) +def test_no_sort_keep_na(sequence_index, dtype, test_series, as_index): + # GH#46584, GH#48794 + + # Convert sequence_index into a string sequence, e.g. 5 becomes "xxyz" + # This sequence is used for the grouper. + sequence = "".join( + [{0: "x", 1: "y", 2: "z"}[sequence_index // (3**k) % 3] for k in range(4)] + ) + + # Unique values to use for grouper, depends on dtype + if dtype in ("string", "string[pyarrow]"): + uniques = {"x": "x", "y": "y", "z": pd.NA} + elif dtype in ("datetime64[ns]", "period[d]"): + uniques = {"x": "2016-01-01", "y": "2017-01-01", "z": pd.NA} + else: + uniques = {"x": 1, "y": 2, "z": np.nan} + + df = pd.DataFrame( + { + "key": pd.Series([uniques[label] for label in sequence], dtype=dtype), + "a": [0, 1, 2, 3], + } + ) + gb = df.groupby("key", dropna=False, sort=False, as_index=as_index, observed=False) + if test_series: + gb = gb["a"] + result = gb.sum() + + # Manually compute the groupby sum, use the labels "x", "y", and "z" to avoid + # issues with hashing np.nan + summed = {} + for idx, label in enumerate(sequence): + summed[label] = summed.get(label, 0) + idx + if dtype == "category": + index = pd.CategoricalIndex( + [uniques[e] for e in summed], + df["key"].cat.categories, + name="key", + ) + elif isinstance(dtype, str) and dtype.startswith("Sparse"): + index = pd.Index( + pd.array([uniques[label] for label in summed], dtype=dtype), name="key" + ) + else: + index = pd.Index([uniques[label] for label in summed], dtype=dtype, name="key") + expected = pd.Series(summed.values(), index=index, name="a", dtype=None) + if not test_series: + expected = expected.to_frame() + if not as_index: + expected = expected.reset_index() + if dtype is not None and dtype.startswith("Sparse"): + expected["key"] = expected["key"].astype(dtype) + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("test_series", [True, False]) +@pytest.mark.parametrize("dtype", [object, None]) +def test_null_is_null_for_dtype( + sort, dtype, nulls_fixture, nulls_fixture2, test_series +): + # GH#48506 - groups should always result in using the null for the dtype + df = pd.DataFrame({"a": [1, 2]}) + groups = pd.Series([nulls_fixture, nulls_fixture2], dtype=dtype) + obj = df["a"] if test_series else df + gb = obj.groupby(groups, dropna=False, sort=sort) + result = gb.sum() + index = pd.Index([na_value_for_dtype(groups.dtype)]) + expected = pd.DataFrame({"a": [3]}, index=index) + if test_series: + tm.assert_series_equal(result, expected["a"]) + else: + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("index_kind", ["range", "single", "multi"]) +def test_categorical_reducers(reduction_func, observed, sort, as_index, index_kind): + # Ensure there is at least one null value by appending to the end + values = np.append(np.random.default_rng(2).choice([1, 2, None], size=19), None) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(20)} + ) + + # Strategy: Compare to dropna=True by filling null values with a new code + df_filled = df.copy() + df_filled["x"] = pd.Categorical(values, categories=[1, 2, 3, 4]).fillna(4) + + if index_kind == "range": + keys = ["x"] + elif index_kind == "single": + keys = ["x"] + df = df.set_index("x") + df_filled = df_filled.set_index("x") + else: + keys = ["x", "x2"] + df["x2"] = df["x"] + df = df.set_index(["x", "x2"]) + df_filled["x2"] = df_filled["x"] + df_filled = df_filled.set_index(["x", "x2"]) + args = get_groupby_method_args(reduction_func, df) + args_filled = get_groupby_method_args(reduction_func, df_filled) + if reduction_func == "corrwith" and index_kind == "range": + # Don't include the grouping columns so we can call reset_index + args = (args[0].drop(columns=keys),) + args_filled = (args_filled[0].drop(columns=keys),) + + gb_keepna = df.groupby( + keys, dropna=False, observed=observed, sort=sort, as_index=as_index + ) + + if not observed and reduction_func in ["idxmin", "idxmax"]: + with pytest.raises( + ValueError, match="empty group due to unobserved categories" + ): + getattr(gb_keepna, reduction_func)(*args) + return + + gb_filled = df_filled.groupby(keys, observed=observed, sort=sort, as_index=True) + expected = getattr(gb_filled, reduction_func)(*args_filled).reset_index() + expected["x"] = expected["x"].cat.remove_categories([4]) + if index_kind == "multi": + expected["x2"] = expected["x2"].cat.remove_categories([4]) + if as_index: + if index_kind == "multi": + expected = expected.set_index(["x", "x2"]) + else: + expected = expected.set_index("x") + elif index_kind != "range" and reduction_func != "size": + # size, unlike other methods, has the desired behavior in GH#49519 + expected = expected.drop(columns="x") + if index_kind == "multi": + expected = expected.drop(columns="x2") + if reduction_func in ("idxmax", "idxmin") and index_kind != "range": + # expected was computed with a RangeIndex; need to translate to index values + values = expected["y"].values.tolist() + if index_kind == "single": + values = [np.nan if e == 4 else e for e in values] + expected["y"] = pd.Categorical(values, categories=[1, 2, 3]) + else: + values = [(np.nan, np.nan) if e == (4, 4) else e for e in values] + expected["y"] = values + if reduction_func == "size": + # size, unlike other methods, has the desired behavior in GH#49519 + expected = expected.rename(columns={0: "size"}) + if as_index: + expected = expected["size"].rename(None) + + if as_index or index_kind == "range" or reduction_func == "size": + warn = None + else: + warn = FutureWarning + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(warn, match=msg): + result = getattr(gb_keepna, reduction_func)(*args) + + # size will return a Series, others are DataFrame + tm.assert_equal(result, expected) + + +def test_categorical_transformers( + request, transformation_func, observed, sort, as_index +): + # GH#36327 + if transformation_func == "fillna": + msg = "GH#49651 fillna may incorrectly reorders results when dropna=False" + request.applymarker(pytest.mark.xfail(reason=msg, strict=False)) + + values = np.append(np.random.default_rng(2).choice([1, 2, None], size=19), None) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(20)} + ) + args = get_groupby_method_args(transformation_func, df) + + # Compute result for null group + null_group_values = df[df["x"].isnull()]["y"] + if transformation_func == "cumcount": + null_group_data = list(range(len(null_group_values))) + elif transformation_func == "ngroup": + if sort: + if observed: + na_group = df["x"].nunique(dropna=False) - 1 + else: + # TODO: Should this be 3? + na_group = df["x"].nunique(dropna=False) - 1 + else: + na_group = df.iloc[: null_group_values.index[0]]["x"].nunique() + null_group_data = len(null_group_values) * [na_group] + else: + null_group_data = getattr(null_group_values, transformation_func)(*args) + null_group_result = pd.DataFrame({"y": null_group_data}) + + gb_keepna = df.groupby( + "x", dropna=False, observed=observed, sort=sort, as_index=as_index + ) + gb_dropna = df.groupby("x", dropna=True, observed=observed, sort=sort) + + msg = "The default fill_method='ffill' in DataFrameGroupBy.pct_change is deprecated" + if transformation_func == "pct_change": + with tm.assert_produces_warning(FutureWarning, match=msg): + result = getattr(gb_keepna, "pct_change")(*args) + else: + result = getattr(gb_keepna, transformation_func)(*args) + expected = getattr(gb_dropna, transformation_func)(*args) + + for iloc, value in zip( + df[df["x"].isnull()].index.tolist(), null_group_result.values.ravel() + ): + if expected.ndim == 1: + expected.iloc[iloc] = value + else: + expected.iloc[iloc, 0] = value + if transformation_func == "ngroup": + expected[df["x"].notnull() & expected.ge(na_group)] += 1 + if transformation_func not in ("rank", "diff", "pct_change", "shift"): + expected = expected.astype("int64") + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("method", ["head", "tail"]) +def test_categorical_head_tail(method, observed, sort, as_index): + # GH#36327 + values = np.random.default_rng(2).choice([1, 2, None], 30) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))} + ) + gb = df.groupby("x", dropna=False, observed=observed, sort=sort, as_index=as_index) + result = getattr(gb, method)() + + if method == "tail": + values = values[::-1] + # Take the top 5 values from each group + mask = ( + ((values == 1) & ((values == 1).cumsum() <= 5)) + | ((values == 2) & ((values == 2).cumsum() <= 5)) + # flake8 doesn't like the vectorized check for None, thinks we should use `is` + | ((values == None) & ((values == None).cumsum() <= 5)) # noqa: E711 + ) + if method == "tail": + mask = mask[::-1] + expected = df[mask] + + tm.assert_frame_equal(result, expected) + + +def test_categorical_agg(): + # GH#36327 + values = np.random.default_rng(2).choice([1, 2, None], 30) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))} + ) + gb = df.groupby("x", dropna=False, observed=False) + result = gb.agg(lambda x: x.sum()) + expected = gb.sum() + tm.assert_frame_equal(result, expected) + + +def test_categorical_transform(): + # GH#36327 + values = np.random.default_rng(2).choice([1, 2, None], 30) + df = pd.DataFrame( + {"x": pd.Categorical(values, categories=[1, 2, 3]), "y": range(len(values))} + ) + gb = df.groupby("x", dropna=False, observed=False) + result = gb.transform(lambda x: x.sum()) + expected = gb.transform("sum") + tm.assert_frame_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_subclass.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_subclass.py new file mode 100644 index 0000000000000000000000000000000000000000..b5523592c3c5c33772083de8970b1223ff482ea6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_groupby_subclass.py @@ -0,0 +1,135 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Index, + Series, +) +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + +pytestmark = pytest.mark.filterwarnings( + "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning" +) + + +@pytest.mark.parametrize( + "obj", + [ + tm.SubclassedDataFrame({"A": np.arange(0, 10)}), + tm.SubclassedSeries(np.arange(0, 10), name="A"), + ], +) +def test_groupby_preserves_subclass(obj, groupby_func): + # GH28330 -- preserve subclass through groupby operations + + if isinstance(obj, Series) and groupby_func in {"corrwith"}: + pytest.skip(f"Not applicable for Series and {groupby_func}") + + grouped = obj.groupby(np.arange(0, 10)) + + # Groups should preserve subclass type + assert isinstance(grouped.get_group(0), type(obj)) + + args = get_groupby_method_args(groupby_func, obj) + + warn = FutureWarning if groupby_func == "fillna" else None + msg = f"{type(grouped).__name__}.fillna is deprecated" + with tm.assert_produces_warning(warn, match=msg, raise_on_extra_warnings=False): + result1 = getattr(grouped, groupby_func)(*args) + with tm.assert_produces_warning(warn, match=msg, raise_on_extra_warnings=False): + result2 = grouped.agg(groupby_func, *args) + + # Reduction or transformation kernels should preserve type + slices = {"ngroup", "cumcount", "size"} + if isinstance(obj, DataFrame) and groupby_func in slices: + assert isinstance(result1, tm.SubclassedSeries) + else: + assert isinstance(result1, type(obj)) + + # Confirm .agg() groupby operations return same results + if isinstance(result1, DataFrame): + tm.assert_frame_equal(result1, result2) + else: + tm.assert_series_equal(result1, result2) + + +def test_groupby_preserves_metadata(): + # GH-37343 + custom_df = tm.SubclassedDataFrame({"a": [1, 2, 3], "b": [1, 1, 2], "c": [7, 8, 9]}) + assert "testattr" in custom_df._metadata + custom_df.testattr = "hello" + for _, group_df in custom_df.groupby("c"): + assert group_df.testattr == "hello" + + # GH-45314 + def func(group): + assert isinstance(group, tm.SubclassedDataFrame) + assert hasattr(group, "testattr") + assert group.testattr == "hello" + return group.testattr + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning( + FutureWarning, + match=msg, + raise_on_extra_warnings=False, + check_stacklevel=False, + ): + result = custom_df.groupby("c").apply(func) + expected = tm.SubclassedSeries(["hello"] * 3, index=Index([7, 8, 9], name="c")) + tm.assert_series_equal(result, expected) + + result = custom_df.groupby("c").apply(func, include_groups=False) + tm.assert_series_equal(result, expected) + + # https://github.com/pandas-dev/pandas/pull/56761 + result = custom_df.groupby("c")[["a", "b"]].apply(func) + tm.assert_series_equal(result, expected) + + def func2(group): + assert isinstance(group, tm.SubclassedSeries) + assert hasattr(group, "testattr") + return group.testattr + + custom_series = tm.SubclassedSeries([1, 2, 3]) + custom_series.testattr = "hello" + result = custom_series.groupby(custom_df["c"]).apply(func2) + tm.assert_series_equal(result, expected) + result = custom_series.groupby(custom_df["c"]).agg(func2) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("obj", [DataFrame, tm.SubclassedDataFrame]) +def test_groupby_resample_preserves_subclass(obj): + # GH28330 -- preserve subclass through groupby.resample() + + df = obj( + { + "Buyer": Series("Carl Carl Carl Carl Joe Carl".split(), dtype=object), + "Quantity": [18, 3, 5, 1, 9, 3], + "Date": [ + datetime(2013, 9, 1, 13, 0), + datetime(2013, 9, 1, 13, 5), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 3, 10, 0), + datetime(2013, 12, 2, 12, 0), + datetime(2013, 9, 2, 14, 0), + ], + } + ) + df = df.set_index("Date") + + # Confirm groupby.resample() preserves dataframe type + msg = "DataFrameGroupBy.resample operated on the grouping columns" + with tm.assert_produces_warning( + FutureWarning, + match=msg, + raise_on_extra_warnings=False, + check_stacklevel=False, + ): + result = df.groupby("Buyer").resample("5D").sum() + assert isinstance(result, obj) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_grouping.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0e67dea532bedac3a920f3c9bfa88e9d657f88 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_grouping.py @@ -0,0 +1,1238 @@ +""" +test where we are determining what we are grouping, or getting groups +""" +from datetime import ( + date, + timedelta, +) + +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + CategoricalIndex, + DataFrame, + Grouper, + Index, + MultiIndex, + Series, + Timestamp, + date_range, + period_range, +) +import pandas._testing as tm +from pandas.core.groupby.grouper import Grouping + +# selection +# -------------------------------- + + +class TestSelection: + def test_select_bad_cols(self): + df = DataFrame([[1, 2]], columns=["A", "B"]) + g = df.groupby("A") + with pytest.raises(KeyError, match="\"Columns not found: 'C'\""): + g[["C"]] + + with pytest.raises(KeyError, match="^[^A]+$"): + # A should not be referenced as a bad column... + # will have to rethink regex if you change message! + g[["A", "C"]] + + def test_groupby_duplicated_column_errormsg(self): + # GH7511 + df = DataFrame( + columns=["A", "B", "A", "C"], data=[range(4), range(2, 6), range(0, 8, 2)] + ) + + msg = "Grouper for 'A' not 1-dimensional" + with pytest.raises(ValueError, match=msg): + df.groupby("A") + with pytest.raises(ValueError, match=msg): + df.groupby(["A", "B"]) + + grouped = df.groupby("B") + c = grouped.count() + assert c.columns.nlevels == 1 + assert c.columns.size == 3 + + def test_column_select_via_attr(self, df): + result = df.groupby("A").C.sum() + expected = df.groupby("A")["C"].sum() + tm.assert_series_equal(result, expected) + + df["mean"] = 1.5 + result = df.groupby("A").mean(numeric_only=True) + expected = df.groupby("A")[["C", "D", "mean"]].agg("mean") + tm.assert_frame_equal(result, expected) + + def test_getitem_list_of_columns(self): + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.default_rng(2).standard_normal(8), + "D": np.random.default_rng(2).standard_normal(8), + "E": np.random.default_rng(2).standard_normal(8), + } + ) + + result = df.groupby("A")[["C", "D"]].mean() + result2 = df.groupby("A")[df.columns[2:4]].mean() + + expected = df.loc[:, ["A", "C", "D"]].groupby("A").mean() + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + + def test_getitem_numeric_column_names(self): + # GH #13731 + df = DataFrame( + { + 0: list("abcd") * 2, + 2: np.random.default_rng(2).standard_normal(8), + 4: np.random.default_rng(2).standard_normal(8), + 6: np.random.default_rng(2).standard_normal(8), + } + ) + result = df.groupby(0)[df.columns[1:3]].mean() + result2 = df.groupby(0)[[2, 4]].mean() + + expected = df.loc[:, [0, 2, 4]].groupby(0).mean() + + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result2, expected) + + # per GH 23566 enforced deprecation raises a ValueError + with pytest.raises(ValueError, match="Cannot subset columns with a tuple"): + df.groupby(0)[2, 4].mean() + + def test_getitem_single_tuple_of_columns_raises(self, df): + # per GH 23566 enforced deprecation raises a ValueError + with pytest.raises(ValueError, match="Cannot subset columns with a tuple"): + df.groupby("A")["C", "D"].mean() + + def test_getitem_single_column(self): + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": ["one", "one", "two", "three", "two", "two", "one", "three"], + "C": np.random.default_rng(2).standard_normal(8), + "D": np.random.default_rng(2).standard_normal(8), + "E": np.random.default_rng(2).standard_normal(8), + } + ) + + result = df.groupby("A")["C"].mean() + + as_frame = df.loc[:, ["A", "C"]].groupby("A").mean() + as_series = as_frame.iloc[:, 0] + expected = as_series + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "func", [lambda x: x.sum(), lambda x: x.agg(lambda y: y.sum())] + ) + def test_getitem_from_grouper(self, func): + # GH 50383 + df = DataFrame({"a": [1, 1, 2], "b": 3, "c": 4, "d": 5}) + gb = df.groupby(["a", "b"])[["a", "c"]] + + idx = MultiIndex.from_tuples([(1, 3), (2, 3)], names=["a", "b"]) + expected = DataFrame({"a": [2, 2], "c": [8, 4]}, index=idx) + result = func(gb) + + tm.assert_frame_equal(result, expected) + + def test_indices_grouped_by_tuple_with_lambda(self): + # GH 36158 + df = DataFrame( + { + "Tuples": ( + (x, y) + for x in [0, 1] + for y in np.random.default_rng(2).integers(3, 5, 5) + ) + } + ) + + gb = df.groupby("Tuples") + gb_lambda = df.groupby(lambda x: df.iloc[x, 0]) + + expected = gb.indices + result = gb_lambda.indices + + tm.assert_dict_equal(result, expected) + + +# grouping +# -------------------------------- + + +class TestGrouping: + @pytest.mark.parametrize( + "index", + [ + Index(list("abcde")), + Index(np.arange(5)), + Index(np.arange(5, dtype=float)), + date_range("2020-01-01", periods=5), + period_range("2020-01-01", periods=5), + ], + ) + def test_grouper_index_types(self, index): + # related GH5375 + # groupby misbehaving when using a Floatlike index + df = DataFrame(np.arange(10).reshape(5, 2), columns=list("AB"), index=index) + + df.groupby(list("abcde"), group_keys=False).apply(lambda x: x) + + df.index = df.index[::-1] + df.groupby(list("abcde"), group_keys=False).apply(lambda x: x) + + def test_grouper_multilevel_freq(self): + # GH 7885 + # with level and freq specified in a Grouper + d0 = date.today() - timedelta(days=14) + dates = date_range(d0, date.today()) + date_index = MultiIndex.from_product([dates, dates], names=["foo", "bar"]) + df = DataFrame(np.random.default_rng(2).integers(0, 100, 225), index=date_index) + + # Check string level + expected = ( + df.reset_index() + .groupby([Grouper(key="foo", freq="W"), Grouper(key="bar", freq="W")]) + .sum() + ) + # reset index changes columns dtype to object + expected.columns = Index([0], dtype="int64") + + result = df.groupby( + [Grouper(level="foo", freq="W"), Grouper(level="bar", freq="W")] + ).sum() + tm.assert_frame_equal(result, expected) + + # Check integer level + result = df.groupby( + [Grouper(level=0, freq="W"), Grouper(level=1, freq="W")] + ).sum() + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug(self): + # GH 8795 + df = DataFrame({"A": [0, 0, 1, 1, 2, 2], "B": [1, 2, 3, 4, 5, 6]}) + g = df.groupby("A") + expected = g.sum() + + g = df.groupby(Grouper(key="A")) + result = g.sum() + tm.assert_frame_equal(result, expected) + + msg = "Grouper axis keyword is deprecated and will be removed" + with tm.assert_produces_warning(FutureWarning, match=msg): + gpr = Grouper(key="A", axis=0) + g = df.groupby(gpr) + result = g.sum() + tm.assert_frame_equal(result, expected) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = g.apply(lambda x: x.sum()) + expected["A"] = [0, 2, 4] + expected = expected.loc[:, ["A", "B"]] + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug2(self): + # GH14334 + # Grouper(key=...) may be passed in a list + df = DataFrame( + {"A": [0, 0, 0, 1, 1, 1], "B": [1, 1, 2, 2, 3, 3], "C": [1, 2, 3, 4, 5, 6]} + ) + # Group by single column + expected = df.groupby("A").sum() + g = df.groupby([Grouper(key="A")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group by two columns + # using a combination of strings and Grouper objects + expected = df.groupby(["A", "B"]).sum() + + # Group with two Grouper objects + g = df.groupby([Grouper(key="A"), Grouper(key="B")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group with a string and a Grouper object + g = df.groupby(["A", Grouper(key="B")]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + # Group with a Grouper object and a string + g = df.groupby([Grouper(key="A"), "B"]) + result = g.sum() + tm.assert_frame_equal(result, expected) + + def test_grouper_creation_bug3(self, unit): + # GH8866 + dti = date_range("20130101", periods=2, unit=unit) + mi = MultiIndex.from_product( + [list("ab"), range(2), dti], + names=["one", "two", "three"], + ) + ser = Series( + np.arange(8, dtype="int64"), + index=mi, + ) + result = ser.groupby(Grouper(level="three", freq="ME")).sum() + exp_dti = pd.DatetimeIndex( + [Timestamp("2013-01-31")], freq="ME", name="three" + ).as_unit(unit) + expected = Series( + [28], + index=exp_dti, + ) + tm.assert_series_equal(result, expected) + + # just specifying a level breaks + result = ser.groupby(Grouper(level="one")).sum() + expected = ser.groupby(level="one").sum() + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("func", [False, True]) + def test_grouper_returning_tuples(self, func): + # GH 22257 , both with dict and with callable + df = DataFrame({"X": ["A", "B", "A", "B"], "Y": [1, 4, 3, 2]}) + mapping = dict(zip(range(4), [("C", 5), ("D", 6)] * 2)) + + if func: + gb = df.groupby(by=lambda idx: mapping[idx], sort=False) + else: + gb = df.groupby(by=mapping, sort=False) + + name, expected = next(iter(gb)) + assert name == ("C", 5) + result = gb.get_group(name) + + tm.assert_frame_equal(result, expected) + + def test_grouper_column_and_index(self): + # GH 14327 + + # Grouping a multi-index frame by a column and an index level should + # be equivalent to resetting the index and grouping by two columns + idx = MultiIndex.from_tuples( + [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)] + ) + idx.names = ["outer", "inner"] + df_multi = DataFrame( + {"A": np.arange(6), "B": ["one", "one", "two", "two", "one", "one"]}, + index=idx, + ) + result = df_multi.groupby(["B", Grouper(level="inner")]).mean(numeric_only=True) + expected = ( + df_multi.reset_index().groupby(["B", "inner"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + # Test the reverse grouping order + result = df_multi.groupby([Grouper(level="inner"), "B"]).mean(numeric_only=True) + expected = ( + df_multi.reset_index().groupby(["inner", "B"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + # Grouping a single-index frame by a column and the index should + # be equivalent to resetting the index and grouping by two columns + df_single = df_multi.reset_index("outer") + result = df_single.groupby(["B", Grouper(level="inner")]).mean( + numeric_only=True + ) + expected = ( + df_single.reset_index().groupby(["B", "inner"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + # Test the reverse grouping order + result = df_single.groupby([Grouper(level="inner"), "B"]).mean( + numeric_only=True + ) + expected = ( + df_single.reset_index().groupby(["inner", "B"]).mean(numeric_only=True) + ) + tm.assert_frame_equal(result, expected) + + def test_groupby_levels_and_columns(self): + # GH9344, GH9049 + idx_names = ["x", "y"] + idx = MultiIndex.from_tuples([(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names) + df = DataFrame(np.arange(12).reshape(-1, 3), index=idx) + + by_levels = df.groupby(level=idx_names).mean() + # reset_index changes columns dtype to object + by_columns = df.reset_index().groupby(idx_names).mean() + + # without casting, by_columns.columns is object-dtype + by_columns.columns = by_columns.columns.astype(np.int64) + tm.assert_frame_equal(by_levels, by_columns) + + def test_groupby_categorical_index_and_columns(self, observed): + # GH18432, adapted for GH25871 + columns = ["A", "B", "A", "B"] + categories = ["B", "A"] + data = np.array( + [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]], int + ) + cat_columns = CategoricalIndex(columns, categories=categories, ordered=True) + df = DataFrame(data=data, columns=cat_columns) + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = df.groupby(axis=1, level=0, observed=observed).sum() + expected_data = np.array([[4, 2], [4, 2], [4, 2], [4, 2], [4, 2]], int) + expected_columns = CategoricalIndex( + categories, categories=categories, ordered=True + ) + expected = DataFrame(data=expected_data, columns=expected_columns) + tm.assert_frame_equal(result, expected) + + # test transposed version + df = DataFrame(data.T, index=cat_columns) + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(axis=0, level=0, observed=observed).sum() + expected = DataFrame(data=expected_data.T, index=expected_columns) + tm.assert_frame_equal(result, expected) + + def test_grouper_getting_correct_binner(self): + # GH 10063 + # using a non-time-based grouper and a time-based grouper + # and specifying levels + df = DataFrame( + {"A": 1}, + index=MultiIndex.from_product( + [list("ab"), date_range("20130101", periods=80)], names=["one", "two"] + ), + ) + result = df.groupby( + [Grouper(level="one"), Grouper(level="two", freq="ME")] + ).sum() + expected = DataFrame( + {"A": [31, 28, 21, 31, 28, 21]}, + index=MultiIndex.from_product( + [list("ab"), date_range("20130101", freq="ME", periods=3)], + names=["one", "two"], + ), + ) + tm.assert_frame_equal(result, expected) + + def test_grouper_iter(self, df): + gb = df.groupby("A") + msg = "DataFrameGroupBy.grouper is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouper = gb.grouper + result = sorted(grouper) + expected = ["bar", "foo"] + assert result == expected + + def test_empty_groups(self, df): + # see gh-1048 + with pytest.raises(ValueError, match="No group keys passed!"): + df.groupby([]) + + def test_groupby_grouper(self, df): + grouped = df.groupby("A") + msg = "DataFrameGroupBy.grouper is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouper = grouped.grouper + result = df.groupby(grouper).mean(numeric_only=True) + expected = grouped.mean(numeric_only=True) + tm.assert_frame_equal(result, expected) + + def test_groupby_dict_mapping(self): + # GH #679 + s = Series({"T1": 5}) + result = s.groupby({"T1": "T2"}).agg("sum") + expected = s.groupby(["T2"]).agg("sum") + tm.assert_series_equal(result, expected) + + s = Series([1.0, 2.0, 3.0, 4.0], index=list("abcd")) + mapping = {"a": 0, "b": 0, "c": 1, "d": 1} + + result = s.groupby(mapping).mean() + result2 = s.groupby(mapping).agg("mean") + exp_key = np.array([0, 0, 1, 1], dtype=np.int64) + expected = s.groupby(exp_key).mean() + expected2 = s.groupby(exp_key).mean() + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result, result2) + tm.assert_series_equal(result, expected2) + + @pytest.mark.parametrize( + "index", + [ + [0, 1, 2, 3], + ["a", "b", "c", "d"], + [Timestamp(2021, 7, 28 + i) for i in range(4)], + ], + ) + def test_groupby_series_named_with_tuple(self, frame_or_series, index): + # GH 42731 + obj = frame_or_series([1, 2, 3, 4], index=index) + groups = Series([1, 0, 1, 0], index=index, name=("a", "a")) + result = obj.groupby(groups).last() + expected = frame_or_series([4, 3]) + expected.index.name = ("a", "a") + tm.assert_equal(result, expected) + + def test_groupby_grouper_f_sanity_checked(self): + dates = date_range("01-Jan-2013", periods=12, freq="MS") + ts = Series(np.random.default_rng(2).standard_normal(12), index=dates) + + # GH51979 + # simple check that the passed function doesn't operates on the whole index + msg = "'Timestamp' object is not subscriptable" + with pytest.raises(TypeError, match=msg): + ts.groupby(lambda key: key[0:6]) + + result = ts.groupby(lambda x: x).sum() + expected = ts.groupby(ts.index).sum() + expected.index.freq = None + tm.assert_series_equal(result, expected) + + def test_groupby_with_datetime_key(self): + # GH 51158 + df = DataFrame( + { + "id": ["a", "b"] * 3, + "b": date_range("2000-01-01", "2000-01-03", freq="9h"), + } + ) + grouper = Grouper(key="b", freq="D") + gb = df.groupby([grouper, "id"]) + + # test number of groups + expected = { + (Timestamp("2000-01-01"), "a"): [0, 2], + (Timestamp("2000-01-01"), "b"): [1], + (Timestamp("2000-01-02"), "a"): [4], + (Timestamp("2000-01-02"), "b"): [3, 5], + } + tm.assert_dict_equal(gb.groups, expected) + + # test number of group keys + assert len(gb.groups.keys()) == 4 + + def test_grouping_error_on_multidim_input(self, df): + msg = "Grouper for '' not 1-dimensional" + with pytest.raises(ValueError, match=msg): + Grouping(df.index, df[["A", "A"]]) + + def test_multiindex_passthru(self): + # GH 7997 + # regression from 0.14.1 + df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + df.columns = MultiIndex.from_tuples([(0, 1), (1, 1), (2, 1)]) + + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(axis=1, level=[0, 1]) + result = gb.first() + tm.assert_frame_equal(result, df) + + def test_multiindex_negative_level(self, multiindex_dataframe_random_data): + # GH 13901 + result = multiindex_dataframe_random_data.groupby(level=-1).sum() + expected = multiindex_dataframe_random_data.groupby(level="second").sum() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=-2).sum() + expected = multiindex_dataframe_random_data.groupby(level="first").sum() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=[-2, -1]).sum() + expected = multiindex_dataframe_random_data.sort_index() + tm.assert_frame_equal(result, expected) + + result = multiindex_dataframe_random_data.groupby(level=[-1, "first"]).sum() + expected = multiindex_dataframe_random_data.groupby( + level=["second", "first"] + ).sum() + tm.assert_frame_equal(result, expected) + + def test_multifunc_select_col_integer_cols(self, df): + df.columns = np.arange(len(df.columns)) + + # it works! + msg = "Passing a dictionary to SeriesGroupBy.agg is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby(1, as_index=False)[2].agg({"Q": np.mean}) + + def test_multiindex_columns_empty_level(self): + lst = [["count", "values"], ["to filter", ""]] + midx = MultiIndex.from_tuples(lst) + + df = DataFrame([[1, "A"]], columns=midx) + + grouped = df.groupby("to filter").groups + assert grouped["A"] == [0] + + grouped = df.groupby([("to filter", "")]).groups + assert grouped["A"] == [0] + + df = DataFrame([[1, "A"], [2, "B"]], columns=midx) + + expected = df.groupby("to filter").groups + result = df.groupby([("to filter", "")]).groups + assert result == expected + + df = DataFrame([[1, "A"], [2, "A"]], columns=midx) + + expected = df.groupby("to filter").groups + result = df.groupby([("to filter", "")]).groups + tm.assert_dict_equal(result, expected) + + def test_groupby_multiindex_tuple(self): + # GH 17979 + df = DataFrame( + [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]], + columns=MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]), + ) + expected = df.groupby([("b", 1)]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + df2 = DataFrame( + df.values, + columns=MultiIndex.from_arrays( + [["a", "b", "b", "c"], ["d", "d", "e", "e"]] + ), + ) + expected = df2.groupby([("b", "d")]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + df3 = DataFrame(df.values, columns=[("a", "d"), ("b", "d"), ("b", "e"), "c"]) + expected = df3.groupby([("b", "d")]).groups + result = df.groupby(("b", 1)).groups + tm.assert_dict_equal(expected, result) + + def test_groupby_multiindex_partial_indexing_equivalence(self): + # GH 17977 + df = DataFrame( + [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]], + columns=MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]), + ) + + expected_mean = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].mean() + result_mean = df.groupby([("a", 1)])["b"].mean() + tm.assert_frame_equal(expected_mean, result_mean) + + expected_sum = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].sum() + result_sum = df.groupby([("a", 1)])["b"].sum() + tm.assert_frame_equal(expected_sum, result_sum) + + expected_count = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].count() + result_count = df.groupby([("a", 1)])["b"].count() + tm.assert_frame_equal(expected_count, result_count) + + expected_min = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].min() + result_min = df.groupby([("a", 1)])["b"].min() + tm.assert_frame_equal(expected_min, result_min) + + expected_max = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].max() + result_max = df.groupby([("a", 1)])["b"].max() + tm.assert_frame_equal(expected_max, result_max) + + expected_groups = df.groupby([("a", 1)])[[("b", 1), ("b", 2)]].groups + result_groups = df.groupby([("a", 1)])["b"].groups + tm.assert_dict_equal(expected_groups, result_groups) + + @pytest.mark.parametrize("sort", [True, False]) + def test_groupby_level(self, sort, multiindex_dataframe_random_data, df): + # GH 17537 + frame = multiindex_dataframe_random_data + deleveled = frame.reset_index() + + result0 = frame.groupby(level=0, sort=sort).sum() + result1 = frame.groupby(level=1, sort=sort).sum() + + expected0 = frame.groupby(deleveled["first"].values, sort=sort).sum() + expected1 = frame.groupby(deleveled["second"].values, sort=sort).sum() + + expected0.index.name = "first" + expected1.index.name = "second" + + assert result0.index.name == "first" + assert result1.index.name == "second" + + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) + assert result0.index.name == frame.index.names[0] + assert result1.index.name == frame.index.names[1] + + # groupby level name + result0 = frame.groupby(level="first", sort=sort).sum() + result1 = frame.groupby(level="second", sort=sort).sum() + tm.assert_frame_equal(result0, expected0) + tm.assert_frame_equal(result1, expected1) + + # axis=1 + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result0 = frame.T.groupby(level=0, axis=1, sort=sort).sum() + result1 = frame.T.groupby(level=1, axis=1, sort=sort).sum() + tm.assert_frame_equal(result0, expected0.T) + tm.assert_frame_equal(result1, expected1.T) + + # raise exception for non-MultiIndex + msg = "level > 0 or level < -1 only valid with MultiIndex" + with pytest.raises(ValueError, match=msg): + df.groupby(level=1) + + def test_groupby_level_index_names(self, axis): + # GH4014 this used to raise ValueError since 'exp'>1 (in py2) + df = DataFrame({"exp": ["A"] * 3 + ["B"] * 3, "var1": range(6)}).set_index( + "exp" + ) + if axis in (1, "columns"): + df = df.T + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + else: + depr_msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(level="exp", axis=axis) + msg = f"level name foo is not the name of the {df._get_axis_name(axis)}" + with pytest.raises(ValueError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(level="foo", axis=axis) + + @pytest.mark.parametrize("sort", [True, False]) + def test_groupby_level_with_nas(self, sort): + # GH 17537 + index = MultiIndex( + levels=[[1, 0], [0, 1, 2, 3]], + codes=[[1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]], + ) + + # factorizing doesn't confuse things + s = Series(np.arange(8.0), index=index) + result = s.groupby(level=0, sort=sort).sum() + expected = Series([6.0, 22.0], index=[0, 1]) + tm.assert_series_equal(result, expected) + + index = MultiIndex( + levels=[[1, 0], [0, 1, 2, 3]], + codes=[[1, 1, 1, 1, -1, 0, 0, 0], [0, 1, 2, 3, 0, 1, 2, 3]], + ) + + # factorizing doesn't confuse things + s = Series(np.arange(8.0), index=index) + result = s.groupby(level=0, sort=sort).sum() + expected = Series([6.0, 18.0], index=[0.0, 1.0]) + tm.assert_series_equal(result, expected) + + def test_groupby_args(self, multiindex_dataframe_random_data): + # PR8618 and issue 8015 + frame = multiindex_dataframe_random_data + + msg = "You have to supply one of 'by' and 'level'" + with pytest.raises(TypeError, match=msg): + frame.groupby() + + msg = "You have to supply one of 'by' and 'level'" + with pytest.raises(TypeError, match=msg): + frame.groupby(by=None, level=None) + + @pytest.mark.parametrize( + "sort,labels", + [ + [True, [2, 2, 2, 0, 0, 1, 1, 3, 3, 3]], + [False, [0, 0, 0, 1, 1, 2, 2, 3, 3, 3]], + ], + ) + def test_level_preserve_order(self, sort, labels, multiindex_dataframe_random_data): + # GH 17537 + grouped = multiindex_dataframe_random_data.groupby(level=0, sort=sort) + exp_labels = np.array(labels, np.intp) + tm.assert_almost_equal(grouped._grouper.codes[0], exp_labels) + + def test_grouping_labels(self, multiindex_dataframe_random_data): + grouped = multiindex_dataframe_random_data.groupby( + multiindex_dataframe_random_data.index.get_level_values(0) + ) + exp_labels = np.array([2, 2, 2, 0, 0, 1, 1, 3, 3, 3], dtype=np.intp) + tm.assert_almost_equal(grouped._grouper.codes[0], exp_labels) + + def test_list_grouper_with_nat(self): + # GH 14715 + df = DataFrame({"date": date_range("1/1/2011", periods=365, freq="D")}) + df.iloc[-1] = pd.NaT + grouper = Grouper(key="date", freq="YS") + + # Grouper in a list grouping + result = df.groupby([grouper]) + expected = {Timestamp("2011-01-01"): Index(list(range(364)))} + tm.assert_dict_equal(result.groups, expected) + + # Test case without a list + result = df.groupby(grouper) + expected = {Timestamp("2011-01-01"): 365} + tm.assert_dict_equal(result.groups, expected) + + @pytest.mark.parametrize( + "func,expected", + [ + ( + "transform", + Series(name=2, dtype=np.float64), + ), + ( + "agg", + Series( + name=2, dtype=np.float64, index=Index([], dtype=np.float64, name=1) + ), + ), + ( + "apply", + Series( + name=2, dtype=np.float64, index=Index([], dtype=np.float64, name=1) + ), + ), + ], + ) + def test_evaluate_with_empty_groups(self, func, expected): + # 26208 + # test transform'ing empty groups + # (not testing other agg fns, because they return + # different index objects. + df = DataFrame({1: [], 2: []}) + g = df.groupby(1, group_keys=False) + result = getattr(g[2], func)(lambda x: x) + tm.assert_series_equal(result, expected) + + def test_groupby_empty(self): + # https://github.com/pandas-dev/pandas/issues/27190 + s = Series([], name="name", dtype="float64") + gr = s.groupby([]) + + result = gr.mean() + expected = s.set_axis(Index([], dtype=np.intp)) + tm.assert_series_equal(result, expected) + + # check group properties + assert len(gr._grouper.groupings) == 1 + tm.assert_numpy_array_equal( + gr._grouper.group_info[0], np.array([], dtype=np.dtype(np.intp)) + ) + + tm.assert_numpy_array_equal( + gr._grouper.group_info[1], np.array([], dtype=np.dtype(np.intp)) + ) + + assert gr._grouper.group_info[2] == 0 + + # check name + gb = s.groupby(s) + msg = "SeriesGroupBy.grouper is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouper = gb.grouper + result = grouper.names + expected = ["name"] + assert result == expected + + def test_groupby_level_index_value_all_na(self): + # issue 20519 + df = DataFrame( + [["x", np.nan, 10], [None, np.nan, 20]], columns=["A", "B", "C"] + ).set_index(["A", "B"]) + result = df.groupby(level=["A", "B"]).sum() + expected = DataFrame( + data=[], + index=MultiIndex( + levels=[Index(["x"], dtype="str"), Index([], dtype="float64")], + codes=[[], []], + names=["A", "B"], + ), + columns=["C"], + dtype="int64", + ) + tm.assert_frame_equal(result, expected) + + def test_groupby_multiindex_level_empty(self): + # https://github.com/pandas-dev/pandas/issues/31670 + df = DataFrame( + [[123, "a", 1.0], [123, "b", 2.0]], columns=["id", "category", "value"] + ) + df = df.set_index(["id", "category"]) + empty = df[df.value < 0] + result = empty.groupby("id").sum() + expected = DataFrame( + dtype="float64", + columns=["value"], + index=Index([], dtype=np.int64, name="id"), + ) + tm.assert_frame_equal(result, expected) + + +# get_group +# -------------------------------- + + +class TestGetGroup: + def test_get_group(self): + # GH 5267 + # be datelike friendly + df = DataFrame( + { + "DATE": pd.to_datetime( + [ + "10-Oct-2013", + "10-Oct-2013", + "10-Oct-2013", + "11-Oct-2013", + "11-Oct-2013", + "11-Oct-2013", + ] + ), + "label": ["foo", "foo", "bar", "foo", "foo", "bar"], + "VAL": [1, 2, 3, 4, 5, 6], + } + ) + + g = df.groupby("DATE") + key = next(iter(g.groups)) + result1 = g.get_group(key) + result2 = g.get_group(Timestamp(key).to_pydatetime()) + result3 = g.get_group(str(Timestamp(key))) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) + + g = df.groupby(["DATE", "label"]) + + key = next(iter(g.groups)) + result1 = g.get_group(key) + result2 = g.get_group((Timestamp(key[0]).to_pydatetime(), key[1])) + result3 = g.get_group((str(Timestamp(key[0])), key[1])) + tm.assert_frame_equal(result1, result2) + tm.assert_frame_equal(result1, result3) + + # must pass a same-length tuple with multiple keys + msg = "must supply a tuple to get_group with multiple grouping keys" + with pytest.raises(ValueError, match=msg): + g.get_group("foo") + with pytest.raises(ValueError, match=msg): + g.get_group("foo") + msg = "must supply a same-length tuple to get_group with multiple grouping keys" + with pytest.raises(ValueError, match=msg): + g.get_group(("foo", "bar", "baz")) + + def test_get_group_empty_bins(self, observed): + d = DataFrame([3, 1, 7, 6]) + bins = [0, 5, 10, 15] + g = d.groupby(pd.cut(d[0], bins), observed=observed) + + # TODO: should prob allow a str of Interval work as well + # IOW '(0, 5]' + result = g.get_group(pd.Interval(0, 5)) + expected = DataFrame([3, 1], index=[0, 1]) + tm.assert_frame_equal(result, expected) + + msg = r"Interval\(10, 15, closed='right'\)" + with pytest.raises(KeyError, match=msg): + g.get_group(pd.Interval(10, 15)) + + def test_get_group_grouped_by_tuple(self): + # GH 8121 + df = DataFrame([[(1,), (1, 2), (1,), (1, 2)]], index=["ids"]).T + gr = df.groupby("ids") + expected = DataFrame({"ids": [(1,), (1,)]}, index=[0, 2]) + result = gr.get_group((1,)) + tm.assert_frame_equal(result, expected) + + dt = pd.to_datetime(["2010-01-01", "2010-01-02", "2010-01-01", "2010-01-02"]) + df = DataFrame({"ids": [(x,) for x in dt]}) + gr = df.groupby("ids") + result = gr.get_group(("2010-01-01",)) + expected = DataFrame({"ids": [(dt[0],), (dt[0],)]}, index=[0, 2]) + tm.assert_frame_equal(result, expected) + + def test_get_group_grouped_by_tuple_with_lambda(self): + # GH 36158 + df = DataFrame( + { + "Tuples": ( + (x, y) + for x in [0, 1] + for y in np.random.default_rng(2).integers(3, 5, 5) + ) + } + ) + + gb = df.groupby("Tuples") + gb_lambda = df.groupby(lambda x: df.iloc[x, 0]) + + expected = gb.get_group(next(iter(gb.groups.keys()))) + result = gb_lambda.get_group(next(iter(gb_lambda.groups.keys()))) + + tm.assert_frame_equal(result, expected) + + def test_groupby_with_empty(self): + index = pd.DatetimeIndex(()) + data = () + series = Series(data, index, dtype=object) + grouper = Grouper(freq="D") + grouped = series.groupby(grouper) + assert next(iter(grouped), None) is None + + def test_groupby_with_single_column(self): + df = DataFrame({"a": list("abssbab")}) + tm.assert_frame_equal(df.groupby("a").get_group("a"), df.iloc[[0, 5]]) + # GH 13530 + exp = DataFrame( + index=Index(["a", "b", "s"], name="a"), columns=Index([], dtype="str") + ) + tm.assert_frame_equal(df.groupby("a").count(), exp) + tm.assert_frame_equal(df.groupby("a").sum(), exp) + + exp = df.iloc[[3, 4, 5]] + tm.assert_frame_equal(df.groupby("a").nth(1), exp) + + def test_gb_key_len_equal_axis_len(self): + # GH16843 + # test ensures that index and column keys are recognized correctly + # when number of keys equals axis length of groupby + df = DataFrame( + [["foo", "bar", "B", 1], ["foo", "bar", "B", 2], ["foo", "baz", "C", 3]], + columns=["first", "second", "third", "one"], + ) + df = df.set_index(["first", "second"]) + df = df.groupby(["first", "second", "third"]).size() + assert df.loc[("foo", "bar", "B")] == 2 + assert df.loc[("foo", "baz", "C")] == 1 + + +# groups & iteration +# -------------------------------- + + +class TestIteration: + def test_groups(self, df): + grouped = df.groupby(["A"]) + groups = grouped.groups + assert groups is grouped.groups # caching works + + for k, v in grouped.groups.items(): + assert (df.loc[v]["A"] == k).all() + + grouped = df.groupby(["A", "B"]) + groups = grouped.groups + assert groups is grouped.groups # caching works + + for k, v in grouped.groups.items(): + assert (df.loc[v]["A"] == k[0]).all() + assert (df.loc[v]["B"] == k[1]).all() + + def test_grouping_is_iterable(self, tsframe): + # this code path isn't used anywhere else + # not sure it's useful + grouped = tsframe.groupby([lambda x: x.weekday(), lambda x: x.year]) + + # test it works + for g in grouped._grouper.groupings[0]: + pass + + def test_multi_iter(self): + s = Series(np.arange(6)) + k1 = np.array(["a", "a", "a", "b", "b", "b"]) + k2 = np.array(["1", "2", "1", "2", "1", "2"]) + + grouped = s.groupby([k1, k2]) + + iterated = list(grouped) + expected = [ + ("a", "1", s[[0, 2]]), + ("a", "2", s[[1]]), + ("b", "1", s[[4]]), + ("b", "2", s[[3, 5]]), + ] + for i, ((one, two), three) in enumerate(iterated): + e1, e2, e3 = expected[i] + assert e1 == one + assert e2 == two + tm.assert_series_equal(three, e3) + + def test_multi_iter_frame(self, three_group): + k1 = np.array(["b", "b", "b", "a", "a", "a"]) + k2 = np.array(["1", "2", "1", "2", "1", "2"]) + df = DataFrame( + { + "v1": np.random.default_rng(2).standard_normal(6), + "v2": np.random.default_rng(2).standard_normal(6), + "k1": k1, + "k2": k2, + }, + index=["one", "two", "three", "four", "five", "six"], + ) + + grouped = df.groupby(["k1", "k2"]) + + # things get sorted! + iterated = list(grouped) + idx = df.index + expected = [ + ("a", "1", df.loc[idx[[4]]]), + ("a", "2", df.loc[idx[[3, 5]]]), + ("b", "1", df.loc[idx[[0, 2]]]), + ("b", "2", df.loc[idx[[1]]]), + ] + for i, ((one, two), three) in enumerate(iterated): + e1, e2, e3 = expected[i] + assert e1 == one + assert e2 == two + tm.assert_frame_equal(three, e3) + + # don't iterate through groups with no data + df["k1"] = np.array(["b", "b", "b", "a", "a", "a"]) + df["k2"] = np.array(["1", "1", "1", "2", "2", "2"]) + grouped = df.groupby(["k1", "k2"]) + # calling `dict` on a DataFrameGroupBy leads to a TypeError, + # we need to use a dictionary comprehension here + # pylint: disable-next=unnecessary-comprehension + groups = {key: gp for key, gp in grouped} # noqa: C416 + assert len(groups) == 2 + + # axis = 1 + three_levels = three_group.groupby(["A", "B", "C"]).mean() + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + grouped = three_levels.T.groupby(axis=1, level=(1, 2)) + for key, group in grouped: + pass + + def test_dictify(self, df): + dict(iter(df.groupby("A"))) + dict(iter(df.groupby(["A", "B"]))) + dict(iter(df["C"].groupby(df["A"]))) + dict(iter(df["C"].groupby([df["A"], df["B"]]))) + dict(iter(df.groupby("A")["C"])) + dict(iter(df.groupby(["A", "B"])["C"])) + + def test_groupby_with_small_elem(self): + # GH 8542 + # length=2 + df = DataFrame( + {"event": ["start", "start"], "change": [1234, 5678]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10"]), + ) + grouped = df.groupby([Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (Timestamp("2014-09-30"), "start") in grouped.groups + assert (Timestamp("2013-10-31"), "start") in grouped.groups + + res = grouped.get_group((Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0], :]) + res = grouped.get_group((Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + + df = DataFrame( + {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-09-15"]), + ) + grouped = df.groupby([Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 2 + assert grouped.ngroups == 2 + assert (Timestamp("2014-09-30"), "start") in grouped.groups + assert (Timestamp("2013-10-31"), "start") in grouped.groups + + res = grouped.get_group((Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0, 2], :]) + res = grouped.get_group((Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + + # length=3 + df = DataFrame( + {"event": ["start", "start", "start"], "change": [1234, 5678, 9123]}, + index=pd.DatetimeIndex(["2014-09-10", "2013-10-10", "2014-08-05"]), + ) + grouped = df.groupby([Grouper(freq="ME"), "event"]) + assert len(grouped.groups) == 3 + assert grouped.ngroups == 3 + assert (Timestamp("2014-09-30"), "start") in grouped.groups + assert (Timestamp("2013-10-31"), "start") in grouped.groups + assert (Timestamp("2014-08-31"), "start") in grouped.groups + + res = grouped.get_group((Timestamp("2014-09-30"), "start")) + tm.assert_frame_equal(res, df.iloc[[0], :]) + res = grouped.get_group((Timestamp("2013-10-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[1], :]) + res = grouped.get_group((Timestamp("2014-08-31"), "start")) + tm.assert_frame_equal(res, df.iloc[[2], :]) + + def test_grouping_string_repr(self): + # GH 13394 + mi = MultiIndex.from_arrays([list("AAB"), list("aba")]) + df = DataFrame([[1, 2, 3]], columns=mi) + gr = df.groupby(df[("A", "a")]) + + result = gr._grouper.groupings[0].__repr__() + expected = "Grouping(('A', 'a'))" + assert result == expected + + +def test_grouping_by_key_is_in_axis(): + # GH#50413 - Groupers specified by key are in-axis + df = DataFrame({"a": [1, 1, 2], "b": [1, 1, 2], "c": [3, 4, 5]}).set_index("a") + gb = df.groupby([Grouper(level="a"), Grouper(key="b")], as_index=False) + assert not gb._grouper.groupings[0].in_axis + assert gb._grouper.groupings[1].in_axis + + # Currently only in-axis groupings are including in the result when as_index=False; + # This is likely to change in the future. + msg = "A grouping .* was excluded from the result" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = gb.sum() + expected = DataFrame({"b": [1, 2], "c": [7, 5]}) + tm.assert_frame_equal(result, expected) + + +def test_grouper_groups(): + # GH#51182 check Grouper.groups does not raise AttributeError + df = DataFrame({"a": [1, 2, 3], "b": 1}) + grper = Grouper(key="a") + gb = df.groupby(grper) + + msg = "Use GroupBy.groups instead" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = grper.groups + assert res is gb.groups + + msg = "Use GroupBy.grouper instead" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = grper.grouper + assert res is gb._grouper + + msg = "Grouper.obj is deprecated and will be removed" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = grper.obj + assert res is gb.obj + + msg = "Use Resampler.ax instead" + with tm.assert_produces_warning(FutureWarning, match=msg): + grper.ax + + msg = "Grouper.indexer is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grper.indexer + + +@pytest.mark.parametrize("attr", ["group_index", "result_index", "group_arraylike"]) +def test_depr_grouping_attrs(attr): + # GH#56148 + df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5]}) + gb = df.groupby("a") + msg = f"{attr} is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + getattr(gb._grouper.groupings[0], attr) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_index_as_string.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_index_as_string.py new file mode 100644 index 0000000000000000000000000000000000000000..4aaf3de9a23b2416603947db312bb49eea343ba8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_index_as_string.py @@ -0,0 +1,85 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.fixture(params=[["inner"], ["inner", "outer"]]) +def frame(request): + levels = request.param + df = pd.DataFrame( + { + "outer": ["a", "a", "a", "b", "b", "b"], + "inner": [1, 2, 3, 1, 2, 3], + "A": np.arange(6), + "B": ["one", "one", "two", "two", "one", "one"], + } + ) + if levels: + df = df.set_index(levels) + + return df + + +@pytest.fixture() +def series(): + df = pd.DataFrame( + { + "outer": ["a", "a", "a", "b", "b", "b"], + "inner": [1, 2, 3, 1, 2, 3], + "A": np.arange(6), + "B": ["one", "one", "two", "two", "one", "one"], + } + ) + s = df.set_index(["outer", "inner", "B"])["A"] + + return s + + +@pytest.mark.parametrize( + "key_strs,groupers", + [ + ("inner", pd.Grouper(level="inner")), # Index name + (["inner"], [pd.Grouper(level="inner")]), # List of index name + (["B", "inner"], ["B", pd.Grouper(level="inner")]), # Column and index + (["inner", "B"], [pd.Grouper(level="inner"), "B"]), # Index and column + ], +) +def test_grouper_index_level_as_string(frame, key_strs, groupers): + if "B" not in key_strs or "outer" in frame.columns: + result = frame.groupby(key_strs).mean(numeric_only=True) + expected = frame.groupby(groupers).mean(numeric_only=True) + else: + result = frame.groupby(key_strs).mean() + expected = frame.groupby(groupers).mean() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "levels", + [ + "inner", + "outer", + "B", + ["inner"], + ["outer"], + ["B"], + ["inner", "outer"], + ["outer", "inner"], + ["inner", "outer", "B"], + ["B", "outer", "inner"], + ], +) +def test_grouper_index_level_as_string_series(series, levels): + # Compute expected result + if isinstance(levels, list): + groupers = [pd.Grouper(level=lv) for lv in levels] + else: + groupers = pd.Grouper(level=levels) + + expected = series.groupby(groupers).mean() + + # Compute and check result + result = series.groupby(levels).mean() + tm.assert_series_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_indexing.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..664c52babac1381f77f2e2ee7266a9d41031f15e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_indexing.py @@ -0,0 +1,333 @@ +# Test GroupBy._positional_selector positional grouped indexing GH#42864 + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +@pytest.mark.parametrize( + "arg, expected_rows", + [ + [0, [0, 1, 4]], + [2, [5]], + [5, []], + [-1, [3, 4, 7]], + [-2, [1, 6]], + [-6, []], + ], +) +def test_int(slice_test_df, slice_test_grouped, arg, expected_rows): + # Test single integer + result = slice_test_grouped._positional_selector[arg] + expected = slice_test_df.iloc[expected_rows] + + tm.assert_frame_equal(result, expected) + + +def test_slice(slice_test_df, slice_test_grouped): + # Test single slice + result = slice_test_grouped._positional_selector[0:3:2] + expected = slice_test_df.iloc[[0, 1, 4, 5]] + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "arg, expected_rows", + [ + [[0, 2], [0, 1, 4, 5]], + [[0, 2, -1], [0, 1, 3, 4, 5, 7]], + [range(0, 3, 2), [0, 1, 4, 5]], + [{0, 2}, [0, 1, 4, 5]], + ], + ids=[ + "list", + "negative", + "range", + "set", + ], +) +def test_list(slice_test_df, slice_test_grouped, arg, expected_rows): + # Test lists of integers and integer valued iterables + result = slice_test_grouped._positional_selector[arg] + expected = slice_test_df.iloc[expected_rows] + + tm.assert_frame_equal(result, expected) + + +def test_ints(slice_test_df, slice_test_grouped): + # Test tuple of ints + result = slice_test_grouped._positional_selector[0, 2, -1] + expected = slice_test_df.iloc[[0, 1, 3, 4, 5, 7]] + + tm.assert_frame_equal(result, expected) + + +def test_slices(slice_test_df, slice_test_grouped): + # Test tuple of slices + result = slice_test_grouped._positional_selector[:2, -2:] + expected = slice_test_df.iloc[[0, 1, 2, 3, 4, 6, 7]] + + tm.assert_frame_equal(result, expected) + + +def test_mix(slice_test_df, slice_test_grouped): + # Test mixed tuple of ints and slices + result = slice_test_grouped._positional_selector[0, 1, -2:] + expected = slice_test_df.iloc[[0, 1, 2, 3, 4, 6, 7]] + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "arg, expected_rows", + [ + [0, [0, 1, 4]], + [[0, 2, -1], [0, 1, 3, 4, 5, 7]], + [(slice(None, 2), slice(-2, None)), [0, 1, 2, 3, 4, 6, 7]], + ], +) +def test_as_index(slice_test_df, arg, expected_rows): + # Test the default as_index behaviour + result = slice_test_df.groupby("Group", sort=False)._positional_selector[arg] + expected = slice_test_df.iloc[expected_rows] + + tm.assert_frame_equal(result, expected) + + +def test_doc_examples(): + # Test the examples in the documentation + df = pd.DataFrame( + [["a", 1], ["a", 2], ["a", 3], ["b", 4], ["b", 5]], columns=["A", "B"] + ) + + grouped = df.groupby("A", as_index=False) + + result = grouped._positional_selector[1:2] + expected = pd.DataFrame([["a", 2], ["b", 5]], columns=["A", "B"], index=[1, 4]) + + tm.assert_frame_equal(result, expected) + + result = grouped._positional_selector[1, -1] + expected = pd.DataFrame( + [["a", 2], ["a", 3], ["b", 5]], columns=["A", "B"], index=[1, 2, 4] + ) + + tm.assert_frame_equal(result, expected) + + +@pytest.fixture() +def multiindex_data(): + rng = np.random.default_rng(2) + ndates = 100 + nitems = 20 + dates = pd.date_range("20130101", periods=ndates, freq="D") + items = [f"item {i}" for i in range(nitems)] + + data = {} + for date in dates: + nitems_for_date = nitems - rng.integers(0, 12) + levels = [ + (item, rng.integers(0, 10000) / 100, rng.integers(0, 10000) / 100) + for item in items[:nitems_for_date] + ] + levels.sort(key=lambda x: x[1]) + data[date] = levels + + return data + + +def _make_df_from_data(data): + rows = {} + for date in data: + for level in data[date]: + rows[(date, level[0])] = {"A": level[1], "B": level[2]} + + df = pd.DataFrame.from_dict(rows, orient="index") + df.index.names = ("Date", "Item") + return df + + +def test_multiindex(multiindex_data): + # Test the multiindex mentioned as the use-case in the documentation + df = _make_df_from_data(multiindex_data) + result = df.groupby("Date", as_index=False).nth(slice(3, -3)) + + sliced = {date: multiindex_data[date][3:-3] for date in multiindex_data} + expected = _make_df_from_data(sliced) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("arg", [1, 5, 30, 1000, -1, -5, -30, -1000]) +@pytest.mark.parametrize("method", ["head", "tail"]) +@pytest.mark.parametrize("simulated", [True, False]) +def test_against_head_and_tail(arg, method, simulated): + # Test gives the same results as grouped head and tail + n_groups = 100 + n_rows_per_group = 30 + + data = { + "group": [ + f"group {g}" for j in range(n_rows_per_group) for g in range(n_groups) + ], + "value": [ + f"group {g} row {j}" + for j in range(n_rows_per_group) + for g in range(n_groups) + ], + } + df = pd.DataFrame(data) + grouped = df.groupby("group", as_index=False) + size = arg if arg >= 0 else n_rows_per_group + arg + + if method == "head": + result = grouped._positional_selector[:arg] + + if simulated: + indices = [ + j * n_groups + i + for j in range(size) + for i in range(n_groups) + if j * n_groups + i < n_groups * n_rows_per_group + ] + expected = df.iloc[indices] + + else: + expected = grouped.head(arg) + + else: + result = grouped._positional_selector[-arg:] + + if simulated: + indices = [ + (n_rows_per_group + j - size) * n_groups + i + for j in range(size) + for i in range(n_groups) + if (n_rows_per_group + j - size) * n_groups + i >= 0 + ] + expected = df.iloc[indices] + + else: + expected = grouped.tail(arg) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("start", [None, 0, 1, 10, -1, -10]) +@pytest.mark.parametrize("stop", [None, 0, 1, 10, -1, -10]) +@pytest.mark.parametrize("step", [None, 1, 5]) +def test_against_df_iloc(start, stop, step): + # Test that a single group gives the same results as DataFrame.iloc + n_rows = 30 + + data = { + "group": ["group 0"] * n_rows, + "value": list(range(n_rows)), + } + df = pd.DataFrame(data) + grouped = df.groupby("group", as_index=False) + + result = grouped._positional_selector[start:stop:step] + expected = df.iloc[start:stop:step] + + tm.assert_frame_equal(result, expected) + + +def test_series(): + # Test grouped Series + ser = pd.Series([1, 2, 3, 4, 5], index=["a", "a", "a", "b", "b"]) + grouped = ser.groupby(level=0) + result = grouped._positional_selector[1:2] + expected = pd.Series([2, 5], index=["a", "b"]) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("step", [1, 2, 3, 4, 5]) +def test_step(step): + # Test slice with various step values + data = [["x", f"x{i}"] for i in range(5)] + data += [["y", f"y{i}"] for i in range(4)] + data += [["z", f"z{i}"] for i in range(3)] + df = pd.DataFrame(data, columns=["A", "B"]) + + grouped = df.groupby("A", as_index=False) + + result = grouped._positional_selector[::step] + + data = [["x", f"x{i}"] for i in range(0, 5, step)] + data += [["y", f"y{i}"] for i in range(0, 4, step)] + data += [["z", f"z{i}"] for i in range(0, 3, step)] + + index = [0 + i for i in range(0, 5, step)] + index += [5 + i for i in range(0, 4, step)] + index += [9 + i for i in range(0, 3, step)] + + expected = pd.DataFrame(data, columns=["A", "B"], index=index) + + tm.assert_frame_equal(result, expected) + + +@pytest.fixture() +def column_group_df(): + return pd.DataFrame( + [[0, 1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 0, 2]], + columns=["A", "B", "C", "D", "E", "F", "G"], + ) + + +def test_column_axis(column_group_df): + msg = "DataFrame.groupby with axis=1" + with tm.assert_produces_warning(FutureWarning, match=msg): + g = column_group_df.groupby(column_group_df.iloc[1], axis=1) + result = g._positional_selector[1:-1] + expected = column_group_df.iloc[:, [1, 3]] + + tm.assert_frame_equal(result, expected) + + +def test_columns_on_iter(): + # GitHub issue #44821 + df = pd.DataFrame({k: range(10) for k in "ABC"}) + + # Group-by and select columns + cols = ["A", "B"] + for _, dg in df.groupby(df.A < 4)[cols]: + tm.assert_index_equal(dg.columns, pd.Index(cols)) + assert "C" not in dg.columns + + +@pytest.mark.parametrize("func", [list, pd.Index, pd.Series, np.array]) +def test_groupby_duplicated_columns(func): + # GH#44924 + df = pd.DataFrame( + { + "A": [1, 2], + "B": [3, 3], + "C": ["G", "G"], + } + ) + result = df.groupby("C")[func(["A", "B", "A"])].mean() + expected = pd.DataFrame( + [[1.5, 3.0, 1.5]], columns=["A", "B", "A"], index=pd.Index(["G"], name="C") + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_get_nonexisting_groups(): + # GH#32492 + df = pd.DataFrame( + data={ + "A": ["a1", "a2", None], + "B": ["b1", "b2", "b1"], + "val": [1, 2, 3], + } + ) + grps = df.groupby(by=["A", "B"]) + + msg = "('a2', 'b1')" + with pytest.raises(KeyError, match=msg): + grps.get_group(("a2", "b1")) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_libgroupby.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_libgroupby.py new file mode 100644 index 0000000000000000000000000000000000000000..35b8fa93b8e033b8dd9287bc7de8e1ca18ade439 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_libgroupby.py @@ -0,0 +1,331 @@ +import numpy as np +import pytest + +from pandas._libs import groupby as libgroupby +from pandas._libs.groupby import ( + group_cumprod, + group_cumsum, + group_mean, + group_sum, + group_var, +) + +from pandas.core.dtypes.common import ensure_platform_int + +from pandas import isna +import pandas._testing as tm + + +class GroupVarTestMixin: + def test_group_var_generic_1d(self): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((5, 1))).astype(self.dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.random((15, 1)).astype(self.dtype) + labels = np.tile(np.arange(5), (3,)).astype("intp") + + expected_out = ( + np.squeeze(values).reshape((5, 3), order="F").std(axis=1, ddof=1) ** 2 + )[:, np.newaxis] + expected_counts = counts + 3 + + self.algo(out, counts, values, labels) + assert np.allclose(out, expected_out, self.rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_1d_flat_labels(self): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((1, 1))).astype(self.dtype) + counts = np.zeros(1, dtype="int64") + values = 10 * prng.random((5, 1)).astype(self.dtype) + labels = np.zeros(5, dtype="intp") + + expected_out = np.array([[values.std(ddof=1) ** 2]]) + expected_counts = counts + 5 + + self.algo(out, counts, values, labels) + + assert np.allclose(out, expected_out, self.rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_2d_all_finite(self): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((5, 2))).astype(self.dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.random((10, 2)).astype(self.dtype) + labels = np.tile(np.arange(5), (2,)).astype("intp") + + expected_out = np.std(values.reshape(2, 5, 2), ddof=1, axis=0) ** 2 + expected_counts = counts + 2 + + self.algo(out, counts, values, labels) + assert np.allclose(out, expected_out, self.rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_2d_some_nan(self): + prng = np.random.default_rng(2) + + out = (np.nan * np.ones((5, 2))).astype(self.dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.random((10, 2)).astype(self.dtype) + values[:, 1] = np.nan + labels = np.tile(np.arange(5), (2,)).astype("intp") + + expected_out = np.vstack( + [ + values[:, 0].reshape(5, 2, order="F").std(ddof=1, axis=1) ** 2, + np.nan * np.ones(5), + ] + ).T.astype(self.dtype) + expected_counts = counts + 2 + + self.algo(out, counts, values, labels) + tm.assert_almost_equal(out, expected_out, rtol=0.5e-06) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_constant(self): + # Regression test from GH 10448. + + out = np.array([[np.nan]], dtype=self.dtype) + counts = np.array([0], dtype="int64") + values = 0.832845131556193 * np.ones((3, 1), dtype=self.dtype) + labels = np.zeros(3, dtype="intp") + + self.algo(out, counts, values, labels) + + assert counts[0] == 3 + assert out[0, 0] >= 0 + tm.assert_almost_equal(out[0, 0], 0.0) + + +class TestGroupVarFloat64(GroupVarTestMixin): + __test__ = True + + algo = staticmethod(group_var) + dtype = np.float64 + rtol = 1e-5 + + def test_group_var_large_inputs(self): + prng = np.random.default_rng(2) + + out = np.array([[np.nan]], dtype=self.dtype) + counts = np.array([0], dtype="int64") + values = (prng.random(10**6) + 10**12).astype(self.dtype) + values.shape = (10**6, 1) + labels = np.zeros(10**6, dtype="intp") + + self.algo(out, counts, values, labels) + + assert counts[0] == 10**6 + tm.assert_almost_equal(out[0, 0], 1.0 / 12, rtol=0.5e-3) + + +class TestGroupVarFloat32(GroupVarTestMixin): + __test__ = True + + algo = staticmethod(group_var) + dtype = np.float32 + rtol = 1e-2 + + +@pytest.mark.parametrize("dtype", ["float32", "float64"]) +def test_group_ohlc(dtype): + obj = np.array(np.random.default_rng(2).standard_normal(20), dtype=dtype) + + bins = np.array([6, 12, 20]) + out = np.zeros((3, 4), dtype) + counts = np.zeros(len(out), dtype=np.int64) + labels = ensure_platform_int(np.repeat(np.arange(3), np.diff(np.r_[0, bins]))) + + func = libgroupby.group_ohlc + func(out, counts, obj[:, None], labels) + + def _ohlc(group): + if isna(group).all(): + return np.repeat(np.nan, 4) + return [group[0], group.max(), group.min(), group[-1]] + + expected = np.array([_ohlc(obj[:6]), _ohlc(obj[6:12]), _ohlc(obj[12:])]) + + tm.assert_almost_equal(out, expected) + tm.assert_numpy_array_equal(counts, np.array([6, 6, 8], dtype=np.int64)) + + obj[:6] = np.nan + func(out, counts, obj[:, None], labels) + expected[0] = np.nan + tm.assert_almost_equal(out, expected) + + +def _check_cython_group_transform_cumulative(pd_op, np_op, dtype): + """ + Check a group transform that executes a cumulative function. + + Parameters + ---------- + pd_op : callable + The pandas cumulative function. + np_op : callable + The analogous one in NumPy. + dtype : type + The specified dtype of the data. + """ + is_datetimelike = False + + data = np.array([[1], [2], [3], [4]], dtype=dtype) + answer = np.zeros_like(data) + + labels = np.array([0, 0, 0, 0], dtype=np.intp) + ngroups = 1 + pd_op(answer, data, labels, ngroups, is_datetimelike) + + tm.assert_numpy_array_equal(np_op(data), answer[:, 0], check_dtype=False) + + +@pytest.mark.parametrize("np_dtype", ["int64", "uint64", "float32", "float64"]) +def test_cython_group_transform_cumsum(np_dtype): + # see gh-4095 + dtype = np.dtype(np_dtype).type + pd_op, np_op = group_cumsum, np.cumsum + _check_cython_group_transform_cumulative(pd_op, np_op, dtype) + + +def test_cython_group_transform_cumprod(): + # see gh-4095 + dtype = np.float64 + pd_op, np_op = group_cumprod, np.cumprod + _check_cython_group_transform_cumulative(pd_op, np_op, dtype) + + +def test_cython_group_transform_algos(): + # see gh-4095 + is_datetimelike = False + + # with nans + labels = np.array([0, 0, 0, 0, 0], dtype=np.intp) + ngroups = 1 + + data = np.array([[1], [2], [3], [np.nan], [4]], dtype="float64") + actual = np.zeros_like(data) + actual.fill(np.nan) + group_cumprod(actual, data, labels, ngroups, is_datetimelike) + expected = np.array([1, 2, 6, np.nan, 24], dtype="float64") + tm.assert_numpy_array_equal(actual[:, 0], expected) + + actual = np.zeros_like(data) + actual.fill(np.nan) + group_cumsum(actual, data, labels, ngroups, is_datetimelike) + expected = np.array([1, 3, 6, np.nan, 10], dtype="float64") + tm.assert_numpy_array_equal(actual[:, 0], expected) + + # timedelta + is_datetimelike = True + data = np.array([np.timedelta64(1, "ns")] * 5, dtype="m8[ns]")[:, None] + actual = np.zeros_like(data, dtype="int64") + group_cumsum(actual, data.view("int64"), labels, ngroups, is_datetimelike) + expected = np.array( + [ + np.timedelta64(1, "ns"), + np.timedelta64(2, "ns"), + np.timedelta64(3, "ns"), + np.timedelta64(4, "ns"), + np.timedelta64(5, "ns"), + ] + ) + tm.assert_numpy_array_equal(actual[:, 0].view("m8[ns]"), expected) + + +def test_cython_group_mean_datetimelike(): + actual = np.zeros(shape=(1, 1), dtype="float64") + counts = np.array([0], dtype="int64") + data = ( + np.array( + [np.timedelta64(2, "ns"), np.timedelta64(4, "ns"), np.timedelta64("NaT")], + dtype="m8[ns]", + )[:, None] + .view("int64") + .astype("float64") + ) + labels = np.zeros(len(data), dtype=np.intp) + + group_mean(actual, counts, data, labels, is_datetimelike=True) + + tm.assert_numpy_array_equal(actual[:, 0], np.array([3], dtype="float64")) + + +def test_cython_group_mean_wrong_min_count(): + actual = np.zeros(shape=(1, 1), dtype="float64") + counts = np.zeros(1, dtype="int64") + data = np.zeros(1, dtype="float64")[:, None] + labels = np.zeros(1, dtype=np.intp) + + with pytest.raises(AssertionError, match="min_count"): + group_mean(actual, counts, data, labels, is_datetimelike=True, min_count=0) + + +def test_cython_group_mean_not_datetimelike_but_has_NaT_values(): + actual = np.zeros(shape=(1, 1), dtype="float64") + counts = np.array([0], dtype="int64") + data = ( + np.array( + [np.timedelta64("NaT"), np.timedelta64("NaT")], + dtype="m8[ns]", + )[:, None] + .view("int64") + .astype("float64") + ) + labels = np.zeros(len(data), dtype=np.intp) + + group_mean(actual, counts, data, labels, is_datetimelike=False) + + tm.assert_numpy_array_equal( + actual[:, 0], np.array(np.divide(np.add(data[0], data[1]), 2), dtype="float64") + ) + + +def test_cython_group_mean_Inf_at_begining_and_end(): + # GH 50367 + actual = np.array([[np.nan, np.nan], [np.nan, np.nan]], dtype="float64") + counts = np.array([0, 0], dtype="int64") + data = np.array( + [[np.inf, 1.0], [1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0], [5, np.inf]], + dtype="float64", + ) + labels = np.array([0, 1, 0, 1, 0, 1], dtype=np.intp) + + group_mean(actual, counts, data, labels, is_datetimelike=False) + + expected = np.array([[np.inf, 3], [3, np.inf]], dtype="float64") + + tm.assert_numpy_array_equal( + actual, + expected, + ) + + +@pytest.mark.parametrize( + "values, out", + [ + ([[np.inf], [np.inf], [np.inf]], [[np.inf], [np.inf]]), + ([[np.inf], [np.inf], [-np.inf]], [[np.inf], [np.nan]]), + ([[np.inf], [-np.inf], [np.inf]], [[np.inf], [np.nan]]), + ([[np.inf], [-np.inf], [-np.inf]], [[np.inf], [-np.inf]]), + ], +) +def test_cython_group_sum_Inf_at_begining_and_end(values, out): + # GH #53606 + actual = np.array([[np.nan], [np.nan]], dtype="float64") + counts = np.array([0, 0], dtype="int64") + data = np.array(values, dtype="float64") + labels = np.array([0, 1, 1], dtype=np.intp) + + group_sum(actual, counts, data, labels, None, is_datetimelike=False) + + expected = np.array(out, dtype="float64") + + tm.assert_numpy_array_equal( + actual, + expected, + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_missing.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_missing.py new file mode 100644 index 0000000000000000000000000000000000000000..3180a92be1236688e044758bf2334a0985e7aee1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_missing.py @@ -0,0 +1,163 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + Index, + date_range, +) +import pandas._testing as tm + + +@pytest.mark.parametrize("func", ["ffill", "bfill"]) +def test_groupby_column_index_name_lost_fill_funcs(func): + # GH: 29764 groupby loses index sometimes + df = DataFrame( + [[1, 1.0, -1.0], [1, np.nan, np.nan], [1, 2.0, -2.0]], + columns=Index(["type", "a", "b"], name="idx"), + ) + df_grouped = df.groupby(["type"])[["a", "b"]] + result = getattr(df_grouped, func)().columns + expected = Index(["a", "b"], name="idx") + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("func", ["ffill", "bfill"]) +def test_groupby_fill_duplicate_column_names(func): + # GH: 25610 ValueError with duplicate column names + df1 = DataFrame({"field1": [1, 3, 4], "field2": [1, 3, 4]}) + df2 = DataFrame({"field1": [1, np.nan, 4]}) + df_grouped = pd.concat([df1, df2], axis=1).groupby(by=["field2"]) + expected = DataFrame( + [[1, 1.0], [3, np.nan], [4, 4.0]], columns=["field1", "field1"] + ) + result = getattr(df_grouped, func)() + tm.assert_frame_equal(result, expected) + + +def test_ffill_missing_arguments(): + # GH 14955 + df = DataFrame({"a": [1, 2], "b": [1, 1]}) + msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + with pytest.raises(ValueError, match="Must specify a fill"): + df.groupby("b").fillna() + + +@pytest.mark.parametrize( + "method, expected", [("ffill", [None, "a", "a"]), ("bfill", ["a", "a", None])] +) +def test_fillna_with_string_dtype(method, expected): + # GH 40250 + df = DataFrame({"a": pd.array([None, "a", None], dtype="string"), "b": [0, 0, 0]}) + grp = df.groupby("b") + msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = grp.fillna(method=method) + expected = DataFrame({"a": pd.array(expected, dtype="string")}) + tm.assert_frame_equal(result, expected) + + +def test_fill_consistency(): + # GH9221 + # pass thru keyword arguments to the generated wrapper + # are set if the passed kw is None (only) + df = DataFrame( + index=pd.MultiIndex.from_product( + [["value1", "value2"], date_range("2014-01-01", "2014-01-06")] + ), + columns=Index(["1", "2"], name="id"), + ) + df["1"] = [ + np.nan, + 1, + np.nan, + np.nan, + 11, + np.nan, + np.nan, + 2, + np.nan, + np.nan, + 22, + np.nan, + ] + df["2"] = [ + np.nan, + 3, + np.nan, + np.nan, + 33, + np.nan, + np.nan, + 4, + np.nan, + np.nan, + 44, + np.nan, + ] + + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.groupby(level=0, axis=0).fillna(method="ffill") + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.T.groupby(level=0, axis=1).fillna(method="ffill").T + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("method", ["ffill", "bfill"]) +@pytest.mark.parametrize("dropna", [True, False]) +@pytest.mark.parametrize("has_nan_group", [True, False]) +def test_ffill_handles_nan_groups(dropna, method, has_nan_group): + # GH 34725 + + df_without_nan_rows = DataFrame([(1, 0.1), (2, 0.2)]) + + ridx = [-1, 0, -1, -1, 1, -1] + df = df_without_nan_rows.reindex(ridx).reset_index(drop=True) + + group_b = np.nan if has_nan_group else "b" + df["group_col"] = pd.Series(["a"] * 3 + [group_b] * 3) + + grouped = df.groupby(by="group_col", dropna=dropna) + result = getattr(grouped, method)(limit=None) + + expected_rows = { + ("ffill", True, True): [-1, 0, 0, -1, -1, -1], + ("ffill", True, False): [-1, 0, 0, -1, 1, 1], + ("ffill", False, True): [-1, 0, 0, -1, 1, 1], + ("ffill", False, False): [-1, 0, 0, -1, 1, 1], + ("bfill", True, True): [0, 0, -1, -1, -1, -1], + ("bfill", True, False): [0, 0, -1, 1, 1, -1], + ("bfill", False, True): [0, 0, -1, 1, 1, -1], + ("bfill", False, False): [0, 0, -1, 1, 1, -1], + } + + ridx = expected_rows.get((method, dropna, has_nan_group)) + expected = df_without_nan_rows.reindex(ridx).reset_index(drop=True) + # columns are a 'take' on df.columns, which are object dtype + expected.columns = expected.columns.astype(object) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("min_count, value", [(2, np.nan), (-1, 1.0)]) +@pytest.mark.parametrize("func", ["first", "last", "max", "min"]) +def test_min_count(func, min_count, value): + # GH#37821 + df = DataFrame({"a": [1] * 3, "b": [1, np.nan, np.nan], "c": [np.nan] * 3}) + result = getattr(df.groupby("a"), func)(min_count=min_count) + expected = DataFrame({"b": [value], "c": [np.nan]}, index=Index([1], name="a")) + tm.assert_frame_equal(result, expected) + + +def test_indices_with_missing(): + # GH 9304 + df = DataFrame({"a": [1, 1, np.nan], "b": [2, 3, 4], "c": [5, 6, 7]}) + g = df.groupby(["a", "b"]) + result = g.indices + expected = {(1.0, 2): np.array([0]), (1.0, 3): np.array([1])} + assert result == expected diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_numba.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_numba.py new file mode 100644 index 0000000000000000000000000000000000000000..f2c138c86a046a27c93e402d4864d1351275c317 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_numba.py @@ -0,0 +1,89 @@ +import pytest + +from pandas.compat import is_platform_arm + +from pandas import ( + DataFrame, + Series, + option_context, +) +import pandas._testing as tm +from pandas.util.version import Version + +pytestmark = [pytest.mark.single_cpu] + +numba = pytest.importorskip("numba") +pytestmark.append( + pytest.mark.skipif( + Version(numba.__version__) == Version("0.61") and is_platform_arm(), + reason=f"Segfaults on ARM platforms with numba {numba.__version__}", + ) +) + + +@pytest.mark.filterwarnings("ignore") +# Filter warnings when parallel=True and the function can't be parallelized by Numba +class TestEngine: + def test_cython_vs_numba_frame( + self, sort, nogil, parallel, nopython, numba_supported_reductions + ): + func, kwargs = numba_supported_reductions + df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)}) + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + gb = df.groupby("a", sort=sort) + result = getattr(gb, func)( + engine="numba", engine_kwargs=engine_kwargs, **kwargs + ) + expected = getattr(gb, func)(**kwargs) + tm.assert_frame_equal(result, expected) + + def test_cython_vs_numba_getitem( + self, sort, nogil, parallel, nopython, numba_supported_reductions + ): + func, kwargs = numba_supported_reductions + df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)}) + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + gb = df.groupby("a", sort=sort)["c"] + result = getattr(gb, func)( + engine="numba", engine_kwargs=engine_kwargs, **kwargs + ) + expected = getattr(gb, func)(**kwargs) + tm.assert_series_equal(result, expected) + + def test_cython_vs_numba_series( + self, sort, nogil, parallel, nopython, numba_supported_reductions + ): + func, kwargs = numba_supported_reductions + ser = Series(range(3), index=[1, 2, 1], name="foo") + engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} + gb = ser.groupby(level=0, sort=sort) + result = getattr(gb, func)( + engine="numba", engine_kwargs=engine_kwargs, **kwargs + ) + expected = getattr(gb, func)(**kwargs) + tm.assert_series_equal(result, expected) + + def test_as_index_false_unsupported(self, numba_supported_reductions): + func, kwargs = numba_supported_reductions + df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)}) + gb = df.groupby("a", as_index=False) + with pytest.raises(NotImplementedError, match="as_index=False"): + getattr(gb, func)(engine="numba", **kwargs) + + def test_axis_1_unsupported(self, numba_supported_reductions): + func, kwargs = numba_supported_reductions + df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)}) + gb = df.groupby("a", axis=1) + with pytest.raises(NotImplementedError, match="axis=1"): + getattr(gb, func)(engine="numba", **kwargs) + + def test_no_engine_doesnt_raise(self): + # GH55520 + df = DataFrame({"a": [3, 2, 3, 2], "b": range(4), "c": range(1, 5)}) + gb = df.groupby("a") + # Make sure behavior of functions w/out engine argument don't raise + # when the global use_numba option is set + with option_context("compute.use_numba", True): + res = gb.agg({"b": "first"}) + expected = gb.agg({"b": "first"}) + tm.assert_frame_equal(res, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_numeric_only.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_numeric_only.py new file mode 100644 index 0000000000000000000000000000000000000000..3c1ed20ddcb165db2444146c3e13ce7d7a8f874a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_numeric_only.py @@ -0,0 +1,532 @@ +import re + +import numpy as np +import pytest + +from pandas._libs import lib + +import pandas as pd +from pandas import ( + DataFrame, + Index, + Series, + Timestamp, + date_range, +) +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +class TestNumericOnly: + # make sure that we are passing thru kwargs to our agg functions + + @pytest.fixture + def df(self): + # GH3668 + # GH5724 + df = DataFrame( + { + "group": [1, 1, 2], + "int": [1, 2, 3], + "float": [4.0, 5.0, 6.0], + "string": Series(["a", "b", "c"], dtype="str"), + "object": Series(["a", "b", "c"], dtype=object), + "category_string": Series(list("abc")).astype("category"), + "category_int": [7, 8, 9], + "datetime": date_range("20130101", periods=3), + "datetimetz": date_range("20130101", periods=3, tz="US/Eastern"), + "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"), + }, + columns=[ + "group", + "int", + "float", + "string", + "object", + "category_string", + "category_int", + "datetime", + "datetimetz", + "timedelta", + ], + ) + return df + + @pytest.mark.parametrize("method", ["mean", "median"]) + def test_averages(self, df, method): + # mean / median + expected_columns_numeric = Index(["int", "float", "category_int"]) + + gb = df.groupby("group") + expected = DataFrame( + { + "category_int": [7.5, 9], + "float": [4.5, 6.0], + "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")], + "int": [1.5, 3], + "datetime": [ + Timestamp("2013-01-01 12:00:00"), + Timestamp("2013-01-03 00:00:00"), + ], + "datetimetz": [ + Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), + Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), + ], + }, + index=Index([1, 2], name="group"), + columns=[ + "int", + "float", + "category_int", + ], + ) + + result = getattr(gb, method)(numeric_only=True) + tm.assert_frame_equal(result.reindex_like(expected), expected) + + expected_columns = expected.columns + + self._check(df, method, expected_columns, expected_columns_numeric) + + @pytest.mark.parametrize("method", ["min", "max"]) + def test_extrema(self, df, method): + # TODO: min, max *should* handle + # categorical (ordered) dtype + + expected_columns = Index( + [ + "int", + "float", + "string", + "category_int", + "datetime", + "datetimetz", + "timedelta", + ] + ) + expected_columns_numeric = expected_columns + + self._check(df, method, expected_columns, expected_columns_numeric) + + @pytest.mark.parametrize("method", ["first", "last"]) + def test_first_last(self, df, method): + expected_columns = Index( + [ + "int", + "float", + "string", + "object", + "category_string", + "category_int", + "datetime", + "datetimetz", + "timedelta", + ] + ) + expected_columns_numeric = expected_columns + + self._check(df, method, expected_columns, expected_columns_numeric) + + @pytest.mark.parametrize("method", ["sum", "cumsum"]) + def test_sum_cumsum(self, df, method): + expected_columns_numeric = Index(["int", "float", "category_int"]) + expected_columns = Index( + ["int", "float", "string", "category_int", "timedelta"] + ) + if method == "cumsum": + # cumsum loses string + expected_columns = Index(["int", "float", "category_int", "timedelta"]) + + self._check(df, method, expected_columns, expected_columns_numeric) + + @pytest.mark.parametrize("method", ["prod", "cumprod"]) + def test_prod_cumprod(self, df, method): + expected_columns = Index(["int", "float", "category_int"]) + expected_columns_numeric = expected_columns + + self._check(df, method, expected_columns, expected_columns_numeric) + + @pytest.mark.parametrize("method", ["cummin", "cummax"]) + def test_cummin_cummax(self, df, method): + # like min, max, but don't include strings + expected_columns = Index( + ["int", "float", "category_int", "datetime", "datetimetz", "timedelta"] + ) + + # GH#15561: numeric_only=False set by default like min/max + expected_columns_numeric = expected_columns + + self._check(df, method, expected_columns, expected_columns_numeric) + + def _check(self, df, method, expected_columns, expected_columns_numeric): + gb = df.groupby("group") + + # object dtypes for transformations are not implemented in Cython and + # have no Python fallback + exception = ( + (NotImplementedError, TypeError) if method.startswith("cum") else TypeError + ) + + if method in ("min", "max", "cummin", "cummax", "cumsum", "cumprod"): + # The methods default to numeric_only=False and raise TypeError + msg = "|".join( + [ + "Categorical is not ordered", + f"Cannot perform {method} with non-ordered Categorical", + re.escape(f"agg function failed [how->{method},dtype->object]"), + # cumsum/cummin/cummax/cumprod + "function is not implemented for this dtype", + f"dtype 'str' does not support operation '{method}'", + ] + ) + with pytest.raises(exception, match=msg): + getattr(gb, method)() + elif method in ("sum", "mean", "median", "prod"): + msg = "|".join( + [ + "category type does not support sum operations", + re.escape(f"agg function failed [how->{method},dtype->object]"), + re.escape(f"agg function failed [how->{method},dtype->string]"), + f"dtype 'str' does not support operation '{method}'", + ] + ) + with pytest.raises(exception, match=msg): + getattr(gb, method)() + else: + result = getattr(gb, method)() + tm.assert_index_equal(result.columns, expected_columns_numeric) + + if method not in ("first", "last"): + msg = "|".join( + [ + "Categorical is not ordered", + "category type does not support", + "function is not implemented for this dtype", + f"Cannot perform {method} with non-ordered Categorical", + re.escape(f"agg function failed [how->{method},dtype->object]"), + re.escape(f"agg function failed [how->{method},dtype->string]"), + f"dtype 'str' does not support operation '{method}'", + ] + ) + with pytest.raises(exception, match=msg): + getattr(gb, method)(numeric_only=False) + else: + result = getattr(gb, method)(numeric_only=False) + tm.assert_index_equal(result.columns, expected_columns) + + +@pytest.mark.parametrize("numeric_only", [True, False, None]) +def test_axis1_numeric_only(request, groupby_func, numeric_only, using_infer_string): + if groupby_func in ("idxmax", "idxmin"): + pytest.skip("idxmax and idx_min tested in test_idxmin_idxmax_axis1") + if groupby_func in ("corrwith", "skew"): + msg = "GH#47723 groupby.corrwith and skew do not correctly implement axis=1" + request.applymarker(pytest.mark.xfail(reason=msg)) + + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), columns=["A", "B", "C", "D"] + ) + df["E"] = "x" + groups = [1, 2, 3, 1, 2, 3, 1, 2, 3, 4] + gb = df.groupby(groups) + method = getattr(gb, groupby_func) + args = get_groupby_method_args(groupby_func, df) + kwargs = {"axis": 1} + if numeric_only is not None: + # when numeric_only is None we don't pass any argument + kwargs["numeric_only"] = numeric_only + + # Functions without numeric_only and axis args + no_args = ("cumprod", "cumsum", "diff", "fillna", "pct_change", "rank", "shift") + # Functions with axis args + has_axis = ( + "cumprod", + "cumsum", + "diff", + "pct_change", + "rank", + "shift", + "cummax", + "cummin", + "idxmin", + "idxmax", + "fillna", + ) + warn_msg = f"DataFrameGroupBy.{groupby_func} with axis=1 is deprecated" + if numeric_only is not None and groupby_func in no_args: + msg = "got an unexpected keyword argument 'numeric_only'" + if groupby_func in ["cumprod", "cumsum"]: + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + method(*args, **kwargs) + else: + with pytest.raises(TypeError, match=msg): + method(*args, **kwargs) + elif groupby_func not in has_axis: + msg = "got an unexpected keyword argument 'axis'" + with pytest.raises(TypeError, match=msg): + method(*args, **kwargs) + # fillna and shift are successful even on object dtypes + elif (numeric_only is None or not numeric_only) and groupby_func not in ( + "fillna", + "shift", + ): + msgs = ( + # cummax, cummin, rank + "not supported between instances of", + # cumprod + "can't multiply sequence by non-int of type 'float'", + # cumsum, diff, pct_change + "unsupported operand type", + "has no kernel", + "operation 'sub' not supported for dtype 'str' with dtype 'float64'", + ) + if using_infer_string: + pa = pytest.importorskip("pyarrow") + + errs = (TypeError, pa.lib.ArrowNotImplementedError) + else: + errs = TypeError + with pytest.raises(errs, match=f"({'|'.join(msgs)})"): + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + method(*args, **kwargs) + else: + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + result = method(*args, **kwargs) + + df_expected = df.drop(columns="E").T if numeric_only else df.T + expected = getattr(df_expected, groupby_func)(*args).T + if groupby_func == "shift" and not numeric_only: + # shift with axis=1 leaves the leftmost column as numeric + # but transposing for expected gives us object dtype + expected = expected.astype(float) + + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "kernel, has_arg", + [ + ("all", False), + ("any", False), + ("bfill", False), + ("corr", True), + ("corrwith", True), + ("cov", True), + ("cummax", True), + ("cummin", True), + ("cumprod", True), + ("cumsum", True), + ("diff", False), + ("ffill", False), + ("fillna", False), + ("first", True), + ("idxmax", True), + ("idxmin", True), + ("last", True), + ("max", True), + ("mean", True), + ("median", True), + ("min", True), + ("nth", False), + ("nunique", False), + ("pct_change", False), + ("prod", True), + ("quantile", True), + ("sem", True), + ("skew", True), + ("std", True), + ("sum", True), + ("var", True), + ], +) +@pytest.mark.parametrize("numeric_only", [True, False, lib.no_default]) +@pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) +def test_numeric_only(kernel, has_arg, numeric_only, keys): + # GH#46072 + # drops_nuisance: Whether the op drops nuisance columns even when numeric_only=False + # has_arg: Whether the op has a numeric_only arg + df = DataFrame({"a1": [1, 1], "a2": [2, 2], "a3": [5, 6], "b": 2 * [object]}) + + args = get_groupby_method_args(kernel, df) + kwargs = {} if numeric_only is lib.no_default else {"numeric_only": numeric_only} + + gb = df.groupby(keys) + method = getattr(gb, kernel) + if has_arg and numeric_only is True: + # Cases where b does not appear in the result + result = method(*args, **kwargs) + assert "b" not in result.columns + elif ( + # kernels that work on any dtype and have numeric_only arg + kernel in ("first", "last") + or ( + # kernels that work on any dtype and don't have numeric_only arg + kernel in ("any", "all", "bfill", "ffill", "fillna", "nth", "nunique") + and numeric_only is lib.no_default + ) + ): + warn = FutureWarning if kernel == "fillna" else None + msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = method(*args, **kwargs) + assert "b" in result.columns + elif has_arg: + assert numeric_only is not True + # kernels that are successful on any dtype were above; this will fail + + # object dtypes for transformations are not implemented in Cython and + # have no Python fallback + exception = NotImplementedError if kernel.startswith("cum") else TypeError + + msg = "|".join( + [ + "not allowed for this dtype", + "cannot be performed against 'object' dtypes", + # On PY39 message is "a number"; on PY310 and after is "a real number" + "must be a string or a.* number", + "unsupported operand type", + "function is not implemented for this dtype", + re.escape(f"agg function failed [how->{kernel},dtype->object]"), + ] + ) + if kernel == "quantile": + msg = "dtype 'object' does not support operation 'quantile'" + elif kernel == "idxmin": + msg = "'<' not supported between instances of 'type' and 'type'" + elif kernel == "idxmax": + msg = "'>' not supported between instances of 'type' and 'type'" + with pytest.raises(exception, match=msg): + method(*args, **kwargs) + elif not has_arg and numeric_only is not lib.no_default: + with pytest.raises( + TypeError, match="got an unexpected keyword argument 'numeric_only'" + ): + method(*args, **kwargs) + else: + assert kernel in ("diff", "pct_change") + assert numeric_only is lib.no_default + # Doesn't have numeric_only argument and fails on nuisance columns + with pytest.raises(TypeError, match=r"unsupported operand type"): + method(*args, **kwargs) + + +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") +@pytest.mark.parametrize("dtype", [bool, int, float, object]) +def test_deprecate_numeric_only_series(dtype, groupby_func, request): + # GH#46560 + grouper = [0, 0, 1] + + ser = Series([1, 0, 0], dtype=dtype) + gb = ser.groupby(grouper) + + if groupby_func == "corrwith": + # corrwith is not implemented on SeriesGroupBy + assert not hasattr(gb, groupby_func) + return + + method = getattr(gb, groupby_func) + + expected_ser = Series([1, 0, 0]) + expected_gb = expected_ser.groupby(grouper) + expected_method = getattr(expected_gb, groupby_func) + + args = get_groupby_method_args(groupby_func, ser) + + fails_on_numeric_object = ( + "corr", + "cov", + "cummax", + "cummin", + "cumprod", + "cumsum", + "quantile", + ) + # ops that give an object result on object input + obj_result = ( + "first", + "last", + "nth", + "bfill", + "ffill", + "shift", + "sum", + "diff", + "pct_change", + "var", + "mean", + "median", + "min", + "max", + "prod", + "skew", + ) + + # Test default behavior; kernels that fail may be enabled in the future but kernels + # that succeed should not be allowed to fail (without deprecation, at least) + if groupby_func in fails_on_numeric_object and dtype is object: + if groupby_func == "quantile": + msg = "dtype 'object' does not support operation 'quantile'" + else: + msg = "is not supported for object dtype" + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "DataFrameGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + with pytest.raises(TypeError, match=msg): + method(*args) + elif dtype is object: + warn = FutureWarning if groupby_func == "fillna" else None + warn_msg = "SeriesGroupBy.fillna is deprecated" + with tm.assert_produces_warning(warn, match=warn_msg): + result = method(*args) + with tm.assert_produces_warning(warn, match=warn_msg): + expected = expected_method(*args) + if groupby_func in obj_result: + expected = expected.astype(object) + tm.assert_series_equal(result, expected) + + has_numeric_only = ( + "first", + "last", + "max", + "mean", + "median", + "min", + "prod", + "quantile", + "sem", + "skew", + "std", + "sum", + "var", + "cummax", + "cummin", + "cumprod", + "cumsum", + ) + if groupby_func not in has_numeric_only: + msg = "got an unexpected keyword argument 'numeric_only'" + with pytest.raises(TypeError, match=msg): + method(*args, numeric_only=True) + elif dtype is object: + msg = "|".join( + [ + "SeriesGroupBy.sem called with numeric_only=True and dtype object", + "Series.skew does not allow numeric_only=True with non-numeric", + "cum(sum|prod|min|max) is not supported for object dtype", + r"Cannot use numeric_only=True with SeriesGroupBy\..* and non-numeric", + ] + ) + with pytest.raises(TypeError, match=msg): + method(*args, numeric_only=True) + elif dtype == bool and groupby_func == "quantile": + msg = "Allowing bool dtype in SeriesGroupBy.quantile" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#51424 + result = method(*args, numeric_only=True) + expected = method(*args, numeric_only=False) + tm.assert_series_equal(result, expected) + else: + result = method(*args, numeric_only=True) + expected = method(*args, numeric_only=False) + tm.assert_series_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_pipe.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..ee59a93695bcf84bcfcd8f1add8120e2c04004f5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_pipe.py @@ -0,0 +1,80 @@ +import numpy as np + +import pandas as pd +from pandas import ( + DataFrame, + Index, +) +import pandas._testing as tm + + +def test_pipe(): + # Test the pipe method of DataFrameGroupBy. + # Issue #17871 + + random_state = np.random.default_rng(2) + + df = DataFrame( + { + "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"], + "B": random_state.standard_normal(8), + "C": random_state.standard_normal(8), + } + ) + + def f(dfgb): + return dfgb.B.max() - dfgb.C.min().min() + + def square(srs): + return srs**2 + + # Note that the transformations are + # GroupBy -> Series + # Series -> Series + # This then chains the GroupBy.pipe and the + # NDFrame.pipe methods + result = df.groupby("A").pipe(f).pipe(square) + + index = Index(["bar", "foo"], name="A") + expected = pd.Series([3.749306591013693, 6.717707873081384], name="B", index=index) + + tm.assert_series_equal(expected, result) + + +def test_pipe_args(): + # Test passing args to the pipe method of DataFrameGroupBy. + # Issue #17871 + + df = DataFrame( + { + "group": ["A", "A", "B", "B", "C"], + "x": [1.0, 2.0, 3.0, 2.0, 5.0], + "y": [10.0, 100.0, 1000.0, -100.0, -1000.0], + } + ) + + def f(dfgb, arg1): + filtered = dfgb.filter(lambda grp: grp.y.mean() > arg1, dropna=False) + return filtered.groupby("group") + + def g(dfgb, arg2): + return dfgb.sum() / dfgb.sum().sum() + arg2 + + def h(df, arg3): + return df.x + df.y - arg3 + + result = df.groupby("group").pipe(f, 0).pipe(g, 10).pipe(h, 100) + + # Assert the results here + index = Index(["A", "B"], name="group") + expected = pd.Series([-79.5160891089, -78.4839108911], index=index) + + tm.assert_series_equal(result, expected) + + # test SeriesGroupby.pipe + ser = pd.Series([1, 1, 2, 2, 3, 3]) + result = ser.groupby(ser).pipe(lambda grp: grp.sum() * grp.count()) + + expected = pd.Series([4, 8, 12], index=Index([1, 2, 3], dtype=np.int64)) + + tm.assert_series_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_raises.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_raises.py new file mode 100644 index 0000000000000000000000000000000000000000..bc39f67829792a5c4e254add7100f306ba19be61 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_raises.py @@ -0,0 +1,757 @@ +# Only tests that raise an error and have no better location should go here. +# Tests for specific groupby methods should go in their respective +# test file. + +import datetime +import re + +import numpy as np +import pytest + +from pandas import ( + Categorical, + DataFrame, + Grouper, + Series, +) +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args + + +@pytest.fixture( + params=[ + "a", + ["a"], + ["a", "b"], + Grouper(key="a"), + lambda x: x % 2, + [0, 0, 0, 1, 2, 2, 2, 3, 3], + np.array([0, 0, 0, 1, 2, 2, 2, 3, 3]), + dict(zip(range(9), [0, 0, 0, 1, 2, 2, 2, 3, 3])), + Series([1, 1, 1, 1, 1, 2, 2, 2, 2]), + [Series([1, 1, 1, 1, 1, 2, 2, 2, 2]), Series([3, 3, 4, 4, 4, 4, 4, 3, 3])], + ] +) +def by(request): + return request.param + + +@pytest.fixture(params=[True, False]) +def groupby_series(request): + return request.param + + +@pytest.fixture +def df_with_string_col(): + df = DataFrame( + { + "a": [1, 1, 1, 1, 1, 2, 2, 2, 2], + "b": [3, 3, 4, 4, 4, 4, 4, 3, 3], + "c": range(9), + "d": list("xyzwtyuio"), + } + ) + return df + + +@pytest.fixture +def df_with_datetime_col(): + df = DataFrame( + { + "a": [1, 1, 1, 1, 1, 2, 2, 2, 2], + "b": [3, 3, 4, 4, 4, 4, 4, 3, 3], + "c": range(9), + "d": datetime.datetime(2005, 1, 1, 10, 30, 23, 540000), + } + ) + return df + + +@pytest.fixture +def df_with_timedelta_col(): + df = DataFrame( + { + "a": [1, 1, 1, 1, 1, 2, 2, 2, 2], + "b": [3, 3, 4, 4, 4, 4, 4, 3, 3], + "c": range(9), + "d": datetime.timedelta(days=1), + } + ) + return df + + +@pytest.fixture +def df_with_cat_col(): + df = DataFrame( + { + "a": [1, 1, 1, 1, 1, 2, 2, 2, 2], + "b": [3, 3, 4, 4, 4, 4, 4, 3, 3], + "c": range(9), + "d": Categorical( + ["a", "a", "a", "a", "b", "b", "b", "b", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ), + } + ) + return df + + +def _call_and_check(klass, msg, how, gb, groupby_func, args, warn_msg=""): + warn_klass = None if warn_msg == "" else FutureWarning + with tm.assert_produces_warning(warn_klass, match=warn_msg): + if klass is None: + if how == "method": + getattr(gb, groupby_func)(*args) + elif how == "agg": + gb.agg(groupby_func, *args) + else: + gb.transform(groupby_func, *args) + else: + with pytest.raises(klass, match=msg): + if how == "method": + getattr(gb, groupby_func)(*args) + elif how == "agg": + gb.agg(groupby_func, *args) + else: + gb.transform(groupby_func, *args) + + +@pytest.mark.parametrize("how", ["method", "agg", "transform"]) +def test_groupby_raises_string( + how, by, groupby_series, groupby_func, df_with_string_col, using_infer_string +): + df = df_with_string_col + args = get_groupby_method_args(groupby_func, df) + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + if groupby_func == "corrwith": + assert not hasattr(gb, "corrwith") + return + + klass, msg = { + "all": (None, ""), + "any": (None, ""), + "bfill": (None, ""), + "corrwith": (TypeError, "Could not convert"), + "count": (None, ""), + "cumcount": (None, ""), + "cummax": ( + (NotImplementedError, TypeError), + "(function|cummax) is not (implemented|supported) for (this|object) dtype", + ), + "cummin": ( + (NotImplementedError, TypeError), + "(function|cummin) is not (implemented|supported) for (this|object) dtype", + ), + "cumprod": ( + (NotImplementedError, TypeError), + "(function|cumprod) is not (implemented|supported) for (this|object) dtype", + ), + "cumsum": ( + (NotImplementedError, TypeError), + "(function|cumsum) is not (implemented|supported) for (this|object) dtype", + ), + "diff": (TypeError, "unsupported operand type"), + "ffill": (None, ""), + "fillna": (None, ""), + "first": (None, ""), + "idxmax": (None, ""), + "idxmin": (None, ""), + "last": (None, ""), + "max": (None, ""), + "mean": ( + TypeError, + re.escape("agg function failed [how->mean,dtype->object]"), + ), + "median": ( + TypeError, + re.escape("agg function failed [how->median,dtype->object]"), + ), + "min": (None, ""), + "ngroup": (None, ""), + "nunique": (None, ""), + "pct_change": (TypeError, "unsupported operand type"), + "prod": ( + TypeError, + re.escape("agg function failed [how->prod,dtype->object]"), + ), + "quantile": (TypeError, "dtype 'object' does not support operation 'quantile'"), + "rank": (None, ""), + "sem": (ValueError, "could not convert string to float"), + "shift": (None, ""), + "size": (None, ""), + "skew": (ValueError, "could not convert string to float"), + "std": (ValueError, "could not convert string to float"), + "sum": (None, ""), + "var": ( + TypeError, + re.escape("agg function failed [how->var,dtype->"), + ), + }[groupby_func] + + if using_infer_string: + if groupby_func in [ + "prod", + "mean", + "median", + "cumsum", + "cumprod", + "std", + "sem", + "var", + "skew", + "quantile", + ]: + msg = f"dtype 'str' does not support operation '{groupby_func}'" + if groupby_func in ["sem", "std", "skew"]: + # The object-dtype raises ValueError when trying to convert to numeric. + klass = TypeError + elif groupby_func == "pct_change" and df["d"].dtype.storage == "pyarrow": + # This doesn't go through EA._groupby_op so the message isn't controlled + # there. + msg = "operation 'truediv' not supported for dtype 'str' with dtype 'str'" + elif groupby_func == "diff" and df["d"].dtype.storage == "pyarrow": + # This doesn't go through EA._groupby_op so the message isn't controlled + # there. + msg = "operation 'sub' not supported for dtype 'str' with dtype 'str'" + + elif groupby_func in ["cummin", "cummax"]: + msg = msg.replace("object", "str") + elif groupby_func == "corrwith": + msg = "Cannot perform reduction 'mean' with string dtype" + + if groupby_func == "fillna": + kind = "Series" if groupby_series else "DataFrame" + warn_msg = f"{kind}GroupBy.fillna is deprecated" + else: + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_msg) + + +@pytest.mark.parametrize("how", ["agg", "transform"]) +def test_groupby_raises_string_udf(how, by, groupby_series, df_with_string_col): + df = df_with_string_col + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + def func(x): + raise TypeError("Test error message") + + with pytest.raises(TypeError, match="Test error message"): + getattr(gb, how)(func) + + +@pytest.mark.parametrize("how", ["agg", "transform"]) +@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean]) +def test_groupby_raises_string_np( + how, + by, + groupby_series, + groupby_func_np, + df_with_string_col, + using_infer_string, +): + # GH#50749 + df = df_with_string_col + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + klass, msg = { + np.sum: (None, ""), + np.mean: ( + TypeError, + "agg function failed|Cannot perform reduction 'mean' with string dtype", + ), + }[groupby_func_np] + + if using_infer_string: + if groupby_func_np is np.mean: + klass = TypeError + msg = "dtype 'str' does not support operation 'mean'" + + if groupby_series: + warn_msg = "using SeriesGroupBy.[sum|mean]" + else: + warn_msg = "using DataFrameGroupBy.[sum|mean]" + _call_and_check(klass, msg, how, gb, groupby_func_np, (), warn_msg=warn_msg) + + +@pytest.mark.parametrize("how", ["method", "agg", "transform"]) +def test_groupby_raises_datetime( + how, by, groupby_series, groupby_func, df_with_datetime_col +): + df = df_with_datetime_col + args = get_groupby_method_args(groupby_func, df) + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + if groupby_func == "corrwith": + assert not hasattr(gb, "corrwith") + return + + klass, msg = { + "all": (None, ""), + "any": (None, ""), + "bfill": (None, ""), + "corrwith": (TypeError, "cannot perform __mul__ with this index type"), + "count": (None, ""), + "cumcount": (None, ""), + "cummax": (None, ""), + "cummin": (None, ""), + "cumprod": (TypeError, "datetime64 type does not support cumprod operations"), + "cumsum": (TypeError, "datetime64 type does not support cumsum operations"), + "diff": (None, ""), + "ffill": (None, ""), + "fillna": (None, ""), + "first": (None, ""), + "idxmax": (None, ""), + "idxmin": (None, ""), + "last": (None, ""), + "max": (None, ""), + "mean": (None, ""), + "median": (None, ""), + "min": (None, ""), + "ngroup": (None, ""), + "nunique": (None, ""), + "pct_change": (TypeError, "cannot perform __truediv__ with this index type"), + "prod": (TypeError, "datetime64 type does not support prod"), + "quantile": (None, ""), + "rank": (None, ""), + "sem": (None, ""), + "shift": (None, ""), + "size": (None, ""), + "skew": ( + TypeError, + "|".join( + [ + r"dtype datetime64\[ns\] does not support reduction", + "datetime64 type does not support skew operations", + ] + ), + ), + "std": (None, ""), + "sum": (TypeError, "datetime64 type does not support sum operations"), + "var": (TypeError, "datetime64 type does not support var operations"), + }[groupby_func] + + if groupby_func in ["any", "all"]: + warn_msg = f"'{groupby_func}' with datetime64 dtypes is deprecated" + elif groupby_func == "fillna": + kind = "Series" if groupby_series else "DataFrame" + warn_msg = f"{kind}GroupBy.fillna is deprecated" + else: + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_msg=warn_msg) + + +@pytest.mark.parametrize("how", ["agg", "transform"]) +def test_groupby_raises_datetime_udf(how, by, groupby_series, df_with_datetime_col): + df = df_with_datetime_col + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + def func(x): + raise TypeError("Test error message") + + with pytest.raises(TypeError, match="Test error message"): + getattr(gb, how)(func) + + +@pytest.mark.parametrize("how", ["agg", "transform"]) +@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean]) +def test_groupby_raises_datetime_np( + how, by, groupby_series, groupby_func_np, df_with_datetime_col +): + # GH#50749 + df = df_with_datetime_col + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + klass, msg = { + np.sum: (TypeError, "datetime64 type does not support sum operations"), + np.mean: (None, ""), + }[groupby_func_np] + + if groupby_series: + warn_msg = "using SeriesGroupBy.[sum|mean]" + else: + warn_msg = "using DataFrameGroupBy.[sum|mean]" + _call_and_check(klass, msg, how, gb, groupby_func_np, (), warn_msg=warn_msg) + + +@pytest.mark.parametrize("func", ["prod", "cumprod", "skew", "var"]) +def test_groupby_raises_timedelta(func, df_with_timedelta_col): + df = df_with_timedelta_col + gb = df.groupby(by="a") + + _call_and_check( + TypeError, + "timedelta64 type does not support .* operations", + "method", + gb, + func, + [], + ) + + +@pytest.mark.parametrize("how", ["method", "agg", "transform"]) +def test_groupby_raises_category( + how, by, groupby_series, groupby_func, using_copy_on_write, df_with_cat_col +): + # GH#50749 + df = df_with_cat_col + args = get_groupby_method_args(groupby_func, df) + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + if groupby_func == "corrwith": + assert not hasattr(gb, "corrwith") + return + + klass, msg = { + "all": (None, ""), + "any": (None, ""), + "bfill": (None, ""), + "corrwith": ( + TypeError, + r"unsupported operand type\(s\) for \*: 'Categorical' and 'int'", + ), + "count": (None, ""), + "cumcount": (None, ""), + "cummax": ( + (NotImplementedError, TypeError), + "(category type does not support cummax operations|" + "category dtype not supported|" + "cummax is not supported for category dtype)", + ), + "cummin": ( + (NotImplementedError, TypeError), + "(category type does not support cummin operations|" + "category dtype not supported|" + "cummin is not supported for category dtype)", + ), + "cumprod": ( + (NotImplementedError, TypeError), + "(category type does not support cumprod operations|" + "category dtype not supported|" + "cumprod is not supported for category dtype)", + ), + "cumsum": ( + (NotImplementedError, TypeError), + "(category type does not support cumsum operations|" + "category dtype not supported|" + "cumsum is not supported for category dtype)", + ), + "diff": ( + TypeError, + r"unsupported operand type\(s\) for -: 'Categorical' and 'Categorical'", + ), + "ffill": (None, ""), + "fillna": ( + TypeError, + r"Cannot setitem on a Categorical with a new category \(0\), " + "set the categories first", + ) + if not using_copy_on_write + else (None, ""), # no-op with CoW + "first": (None, ""), + "idxmax": (None, ""), + "idxmin": (None, ""), + "last": (None, ""), + "max": (None, ""), + "mean": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'mean'", + "category dtype does not support aggregation 'mean'", + ] + ), + ), + "median": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'median'", + "category dtype does not support aggregation 'median'", + ] + ), + ), + "min": (None, ""), + "ngroup": (None, ""), + "nunique": (None, ""), + "pct_change": ( + TypeError, + r"unsupported operand type\(s\) for /: 'Categorical' and 'Categorical'", + ), + "prod": (TypeError, "category type does not support prod operations"), + "quantile": (TypeError, "No matching signature found"), + "rank": (None, ""), + "sem": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'sem'", + "category dtype does not support aggregation 'sem'", + ] + ), + ), + "shift": (None, ""), + "size": (None, ""), + "skew": ( + TypeError, + "|".join( + [ + "dtype category does not support reduction 'skew'", + "category type does not support skew operations", + ] + ), + ), + "std": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'std'", + "category dtype does not support aggregation 'std'", + ] + ), + ), + "sum": (TypeError, "category type does not support sum operations"), + "var": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'var'", + "category dtype does not support aggregation 'var'", + ] + ), + ), + }[groupby_func] + + if groupby_func == "fillna": + kind = "Series" if groupby_series else "DataFrame" + warn_msg = f"{kind}GroupBy.fillna is deprecated" + else: + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_msg) + + +@pytest.mark.parametrize("how", ["agg", "transform"]) +def test_groupby_raises_category_udf(how, by, groupby_series, df_with_cat_col): + # GH#50749 + df = df_with_cat_col + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + def func(x): + raise TypeError("Test error message") + + with pytest.raises(TypeError, match="Test error message"): + getattr(gb, how)(func) + + +@pytest.mark.parametrize("how", ["agg", "transform"]) +@pytest.mark.parametrize("groupby_func_np", [np.sum, np.mean]) +def test_groupby_raises_category_np( + how, by, groupby_series, groupby_func_np, df_with_cat_col +): + # GH#50749 + df = df_with_cat_col + gb = df.groupby(by=by) + + if groupby_series: + gb = gb["d"] + + klass, msg = { + np.sum: (TypeError, "category type does not support sum operations"), + np.mean: ( + TypeError, + "category dtype does not support aggregation 'mean'", + ), + }[groupby_func_np] + + if groupby_series: + warn_msg = "using SeriesGroupBy.[sum|mean]" + else: + warn_msg = "using DataFrameGroupBy.[sum|mean]" + _call_and_check(klass, msg, how, gb, groupby_func_np, (), warn_msg=warn_msg) + + +@pytest.mark.parametrize("how", ["method", "agg", "transform"]) +def test_groupby_raises_category_on_category( + how, + by, + groupby_series, + groupby_func, + observed, + using_copy_on_write, + df_with_cat_col, +): + # GH#50749 + df = df_with_cat_col + df["a"] = Categorical( + ["a", "a", "a", "a", "b", "b", "b", "b", "c"], + categories=["a", "b", "c", "d"], + ordered=True, + ) + args = get_groupby_method_args(groupby_func, df) + gb = df.groupby(by=by, observed=observed) + + if groupby_series: + gb = gb["d"] + + if groupby_func == "corrwith": + assert not hasattr(gb, "corrwith") + return + + empty_groups = not observed and any(group.empty for group in gb.groups.values()) + if ( + not observed + and how != "transform" + and isinstance(by, list) + and isinstance(by[0], str) + and by == ["a", "b"] + ): + assert not empty_groups + # TODO: empty_groups should be true due to unobserved categorical combinations + empty_groups = True + if how == "transform": + # empty groups will be ignored + empty_groups = False + + klass, msg = { + "all": (None, ""), + "any": (None, ""), + "bfill": (None, ""), + "corrwith": ( + TypeError, + r"unsupported operand type\(s\) for \*: 'Categorical' and 'int'", + ), + "count": (None, ""), + "cumcount": (None, ""), + "cummax": ( + (NotImplementedError, TypeError), + "(cummax is not supported for category dtype|" + "category dtype not supported|" + "category type does not support cummax operations)", + ), + "cummin": ( + (NotImplementedError, TypeError), + "(cummin is not supported for category dtype|" + "category dtype not supported|" + "category type does not support cummin operations)", + ), + "cumprod": ( + (NotImplementedError, TypeError), + "(cumprod is not supported for category dtype|" + "category dtype not supported|" + "category type does not support cumprod operations)", + ), + "cumsum": ( + (NotImplementedError, TypeError), + "(cumsum is not supported for category dtype|" + "category dtype not supported|" + "category type does not support cumsum operations)", + ), + "diff": (TypeError, "unsupported operand type"), + "ffill": (None, ""), + "fillna": ( + TypeError, + r"Cannot setitem on a Categorical with a new category \(0\), " + "set the categories first", + ) + if not using_copy_on_write + else (None, ""), # no-op with CoW + "first": (None, ""), + "idxmax": (ValueError, "empty group due to unobserved categories") + if empty_groups + else (None, ""), + "idxmin": (ValueError, "empty group due to unobserved categories") + if empty_groups + else (None, ""), + "last": (None, ""), + "max": (None, ""), + "mean": (TypeError, "category dtype does not support aggregation 'mean'"), + "median": (TypeError, "category dtype does not support aggregation 'median'"), + "min": (None, ""), + "ngroup": (None, ""), + "nunique": (None, ""), + "pct_change": (TypeError, "unsupported operand type"), + "prod": (TypeError, "category type does not support prod operations"), + "quantile": (TypeError, "No matching signature found"), + "rank": (None, ""), + "sem": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'sem'", + "category dtype does not support aggregation 'sem'", + ] + ), + ), + "shift": (None, ""), + "size": (None, ""), + "skew": ( + TypeError, + "|".join( + [ + "category type does not support skew operations", + "dtype category does not support reduction 'skew'", + ] + ), + ), + "std": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'std'", + "category dtype does not support aggregation 'std'", + ] + ), + ), + "sum": (TypeError, "category type does not support sum operations"), + "var": ( + TypeError, + "|".join( + [ + "'Categorical' .* does not support reduction 'var'", + "category dtype does not support aggregation 'var'", + ] + ), + ), + }[groupby_func] + + if groupby_func == "fillna": + kind = "Series" if groupby_series else "DataFrame" + warn_msg = f"{kind}GroupBy.fillna is deprecated" + else: + warn_msg = "" + _call_and_check(klass, msg, how, gb, groupby_func, args, warn_msg) + + +def test_subsetting_columns_axis_1_raises(): + # GH 35443 + df = DataFrame({"a": [1], "b": [2], "c": [3]}) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("a", axis=1) + with pytest.raises(ValueError, match="Cannot subset columns when using axis=1"): + gb["b"] diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_reductions.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_reductions.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ef86adc92275842567a537343faa335a8eb59a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_reductions.py @@ -0,0 +1,1277 @@ +import builtins +import datetime as dt +from string import ascii_lowercase + +import numpy as np +import pytest + +from pandas._libs.tslibs import iNaT + +from pandas.core.dtypes.common import pandas_dtype +from pandas.core.dtypes.missing import na_value_for_dtype + +import pandas as pd +from pandas import ( + DataFrame, + MultiIndex, + Series, + Timestamp, + date_range, + isna, +) +import pandas._testing as tm +from pandas.tests.groupby import get_groupby_method_args +from pandas.util import _test_decorators as td + + +@pytest.mark.parametrize("agg_func", ["any", "all"]) +@pytest.mark.parametrize( + "vals", + [ + ["foo", "bar", "baz"], + ["foo", "", ""], + ["", "", ""], + [1, 2, 3], + [1, 0, 0], + [0, 0, 0], + [1.0, 2.0, 3.0], + [1.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [True, True, True], + [True, False, False], + [False, False, False], + [np.nan, np.nan, np.nan], + ], +) +def test_groupby_bool_aggs(skipna, agg_func, vals): + df = DataFrame({"key": ["a"] * 3 + ["b"] * 3, "val": vals * 2}) + + # Figure out expectation using Python builtin + exp = getattr(builtins, agg_func)(vals) + + # edge case for missing data with skipna and 'any' + if skipna and all(isna(vals)) and agg_func == "any": + exp = False + + expected = DataFrame( + [exp] * 2, columns=["val"], index=pd.Index(["a", "b"], name="key") + ) + result = getattr(df.groupby("key"), agg_func)(skipna=skipna) + tm.assert_frame_equal(result, expected) + + +def test_any(): + df = DataFrame( + [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], + columns=["A", "B", "C"], + ) + expected = DataFrame( + [[True, True], [False, True]], columns=["B", "C"], index=[1, 3] + ) + expected.index.name = "A" + result = df.groupby("A").any() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +def test_bool_aggs_dup_column_labels(bool_agg_func): + # GH#21668 + df = DataFrame([[True, True]], columns=["a", "a"]) + grp_by = df.groupby([0]) + result = getattr(grp_by, bool_agg_func)() + + expected = df.set_axis(np.array([0])) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +@pytest.mark.parametrize( + "data", + [ + [False, False, False], + [True, True, True], + [pd.NA, pd.NA, pd.NA], + [False, pd.NA, False], + [True, pd.NA, True], + [True, pd.NA, False], + ], +) +def test_masked_kleene_logic(bool_agg_func, skipna, data): + # GH#37506 + ser = Series(data, dtype="boolean") + + # The result should match aggregating on the whole series. Correctness + # there is verified in test_reductions.py::test_any_all_boolean_kleene_logic + expected_data = getattr(ser, bool_agg_func)(skipna=skipna) + expected = Series(expected_data, index=np.array([0]), dtype="boolean") + + result = ser.groupby([0, 0, 0]).agg(bool_agg_func, skipna=skipna) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "dtype1,dtype2,exp_col1,exp_col2", + [ + ( + "float", + "Float64", + np.array([True], dtype=bool), + pd.array([pd.NA], dtype="boolean"), + ), + ( + "Int64", + "float", + pd.array([pd.NA], dtype="boolean"), + np.array([True], dtype=bool), + ), + ( + "Int64", + "Int64", + pd.array([pd.NA], dtype="boolean"), + pd.array([pd.NA], dtype="boolean"), + ), + ( + "Float64", + "boolean", + pd.array([pd.NA], dtype="boolean"), + pd.array([pd.NA], dtype="boolean"), + ), + ], +) +def test_masked_mixed_types(dtype1, dtype2, exp_col1, exp_col2): + # GH#37506 + data = [1.0, np.nan] + df = DataFrame( + {"col1": pd.array(data, dtype=dtype1), "col2": pd.array(data, dtype=dtype2)} + ) + result = df.groupby([1, 1]).agg("all", skipna=False) + + expected = DataFrame({"col1": exp_col1, "col2": exp_col2}, index=np.array([1])) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"]) +def test_masked_bool_aggs_skipna(bool_agg_func, dtype, skipna, frame_or_series): + # GH#40585 + obj = frame_or_series([pd.NA, 1], dtype=dtype) + expected_res = True + if not skipna and bool_agg_func == "all": + expected_res = pd.NA + expected = frame_or_series([expected_res], index=np.array([1]), dtype="boolean") + + result = obj.groupby([1, 1]).agg(bool_agg_func, skipna=skipna) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize( + "bool_agg_func,data,expected_res", + [ + ("any", [pd.NA, np.nan], False), + ("any", [pd.NA, 1, np.nan], True), + ("all", [pd.NA, pd.NaT], True), + ("all", [pd.NA, False, pd.NaT], False), + ], +) +def test_object_type_missing_vals(bool_agg_func, data, expected_res, frame_or_series): + # GH#37501 + obj = frame_or_series(data, dtype=object) + result = obj.groupby([1] * len(data)).agg(bool_agg_func) + expected = frame_or_series([expected_res], index=np.array([1]), dtype="bool") + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +def test_object_NA_raises_with_skipna_false(bool_agg_func): + # GH#37501 + ser = Series([pd.NA], dtype=object) + with pytest.raises(TypeError, match="boolean value of NA is ambiguous"): + ser.groupby([1]).agg(bool_agg_func, skipna=False) + + +@pytest.mark.parametrize("bool_agg_func", ["any", "all"]) +def test_empty(frame_or_series, bool_agg_func): + # GH 45231 + kwargs = {"columns": ["a"]} if frame_or_series is DataFrame else {"name": "a"} + obj = frame_or_series(**kwargs, dtype=object) + result = getattr(obj.groupby(obj.index), bool_agg_func)() + expected = frame_or_series(**kwargs, dtype=bool) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmin", "idxmax"]) +def test_idxmin_idxmax_extremes(how, any_real_numpy_dtype): + # GH#57040 + if any_real_numpy_dtype is int or any_real_numpy_dtype is float: + # No need to test + return + info = np.iinfo if "int" in any_real_numpy_dtype else np.finfo + min_value = info(any_real_numpy_dtype).min + max_value = info(any_real_numpy_dtype).max + df = DataFrame( + {"a": [2, 1, 1, 2], "b": [min_value, max_value, max_value, min_value]}, + dtype=any_real_numpy_dtype, + ) + gb = df.groupby("a") + result = getattr(gb, how)() + expected = DataFrame( + {"b": [1, 0]}, index=pd.Index([1, 2], name="a", dtype=any_real_numpy_dtype) + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["idxmin", "idxmax"]) +def test_idxmin_idxmax_extremes_skipna(skipna, how, float_numpy_dtype): + # GH#57040 + min_value = np.finfo(float_numpy_dtype).min + max_value = np.finfo(float_numpy_dtype).max + df = DataFrame( + { + "a": Series(np.repeat(range(1, 6), repeats=2), dtype="intp"), + "b": Series( + [ + np.nan, + min_value, + np.nan, + max_value, + min_value, + np.nan, + max_value, + np.nan, + np.nan, + np.nan, + ], + dtype=float_numpy_dtype, + ), + }, + ) + gb = df.groupby("a") + + warn = None if skipna else FutureWarning + msg = f"The behavior of DataFrameGroupBy.{how} with all-NA values" + with tm.assert_produces_warning(warn, match=msg): + result = getattr(gb, how)(skipna=skipna) + if skipna: + values = [1, 3, 4, 6, np.nan] + else: + values = np.nan + expected = DataFrame( + {"b": values}, index=pd.Index(range(1, 6), name="a", dtype="intp") + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "func, values", + [ + ("idxmin", {"c_int": [0, 2], "c_float": [1, 3], "c_date": [1, 2]}), + ("idxmax", {"c_int": [1, 3], "c_float": [0, 2], "c_date": [0, 3]}), + ], +) +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_idxmin_idxmax_returns_int_types(func, values, numeric_only): + # GH 25444 + df = DataFrame( + { + "name": ["A", "A", "B", "B"], + "c_int": [1, 2, 3, 4], + "c_float": [4.02, 3.03, 2.04, 1.05], + "c_date": ["2019", "2018", "2016", "2017"], + } + ) + df["c_date"] = pd.to_datetime(df["c_date"]) + df["c_date_tz"] = df["c_date"].dt.tz_localize("US/Pacific") + df["c_timedelta"] = df["c_date"] - df["c_date"].iloc[0] + df["c_period"] = df["c_date"].dt.to_period("W") + df["c_Integer"] = df["c_int"].astype("Int64") + df["c_Floating"] = df["c_float"].astype("Float64") + + result = getattr(df.groupby("name"), func)(numeric_only=numeric_only) + + expected = DataFrame(values, index=pd.Index(["A", "B"], name="name")) + if numeric_only: + expected = expected.drop(columns=["c_date"]) + else: + expected["c_date_tz"] = expected["c_date"] + expected["c_timedelta"] = expected["c_date"] + expected["c_period"] = expected["c_date"] + expected["c_Integer"] = expected["c_int"] + expected["c_Floating"] = expected["c_float"] + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "data", + [ + ( + Timestamp("2011-01-15 12:50:28.502376"), + Timestamp("2011-01-20 12:50:28.593448"), + ), + (24650000000000001, 24650000000000002), + ], +) +@pytest.mark.parametrize("method", ["count", "min", "max", "first", "last"]) +def test_groupby_non_arithmetic_agg_int_like_precision(method, data): + # GH#6620, GH#9311 + df = DataFrame({"a": [1, 1], "b": data}) + + grouped = df.groupby("a") + result = getattr(grouped, method)() + if method == "count": + expected_value = 2 + elif method == "first": + expected_value = data[0] + elif method == "last": + expected_value = data[1] + else: + expected_value = getattr(df["b"], method)() + expected = DataFrame({"b": [expected_value]}, index=pd.Index([1], name="a")) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("how", ["first", "last"]) +def test_first_last_skipna(any_real_nullable_dtype, sort, skipna, how): + # GH#57019 + na_value = na_value_for_dtype(pandas_dtype(any_real_nullable_dtype)) + df = DataFrame( + { + "a": [2, 1, 1, 2, 3, 3], + "b": [na_value, 3.0, na_value, 4.0, np.nan, np.nan], + "c": [na_value, 3.0, na_value, 4.0, np.nan, np.nan], + }, + dtype=any_real_nullable_dtype, + ) + gb = df.groupby("a", sort=sort) + method = getattr(gb, how) + result = method(skipna=skipna) + + ilocs = { + ("first", True): [3, 1, 4], + ("first", False): [0, 1, 4], + ("last", True): [3, 1, 5], + ("last", False): [3, 2, 5], + }[how, skipna] + expected = df.iloc[ilocs].set_index("a") + if sort: + expected = expected.sort_index() + tm.assert_frame_equal(result, expected) + + +def test_idxmin_idxmax_axis1(): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), columns=["A", "B", "C", "D"] + ) + df["A"] = [1, 2, 3, 1, 2, 3, 1, 2, 3, 4] + + gb = df.groupby("A") + + warn_msg = "DataFrameGroupBy.idxmax with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + res = gb.idxmax(axis=1) + + alt = df.iloc[:, 1:].idxmax(axis=1) + indexer = res.index.get_level_values(1) + + tm.assert_series_equal(alt[indexer], res.droplevel("A")) + + df["E"] = date_range("2016-01-01", periods=10) + gb2 = df.groupby("A") + + msg = "'>' not supported between instances of 'Timestamp' and 'float'" + with pytest.raises(TypeError, match=msg): + with tm.assert_produces_warning(FutureWarning, match=warn_msg): + gb2.idxmax(axis=1) + + +def test_groupby_mean_no_overflow(): + # Regression test for (#22487) + df = DataFrame( + { + "user": ["A", "A", "A", "A", "A"], + "connections": [4970, 4749, 4719, 4704, 18446744073699999744], + } + ) + assert df.groupby("user")["connections"].mean()["A"] == 3689348814740003840 + + +def test_mean_on_timedelta(): + # GH 17382 + df = DataFrame({"time": pd.to_timedelta(range(10)), "cat": ["A", "B"] * 5}) + result = df.groupby("cat")["time"].mean() + expected = Series( + pd.to_timedelta([4, 5]), name="time", index=pd.Index(["A", "B"], name="cat") + ) + tm.assert_series_equal(result, expected) + + +def test_cython_median(): + arr = np.random.default_rng(2).standard_normal(1000) + arr[::2] = np.nan + df = DataFrame(arr) + + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + labels[::17] = np.nan + + result = df.groupby(labels).median() + msg = "using DataFrameGroupBy.median" + with tm.assert_produces_warning(FutureWarning, match=msg): + exp = df.groupby(labels).agg(np.nanmedian) + tm.assert_frame_equal(result, exp) + + df = DataFrame(np.random.default_rng(2).standard_normal((1000, 5))) + msg = "using DataFrameGroupBy.median" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = df.groupby(labels).agg(np.median) + xp = df.groupby(labels).median() + tm.assert_frame_equal(rs, xp) + + +def test_median_empty_bins(observed): + df = DataFrame(np.random.default_rng(2).integers(0, 44, 500)) + + grps = range(0, 55, 5) + bins = pd.cut(df[0], grps) + + result = df.groupby(bins, observed=observed).median() + expected = df.groupby(bins, observed=observed).agg(lambda x: x.median()) + tm.assert_frame_equal(result, expected) + + +def test_max_min_non_numeric(): + # #2700 + aa = DataFrame({"nn": [11, 11, 22, 22], "ii": [1, 2, 3, 4], "ss": 4 * ["mama"]}) + + result = aa.groupby("nn").max() + assert "ss" in result + + result = aa.groupby("nn").max(numeric_only=False) + assert "ss" in result + + result = aa.groupby("nn").min() + assert "ss" in result + + result = aa.groupby("nn").min(numeric_only=False) + assert "ss" in result + + +def test_max_min_object_multiple_columns(using_array_manager, using_infer_string): + # GH#41111 case where the aggregation is valid for some columns but not + # others; we split object blocks column-wise, consistent with + # DataFrame._reduce + + df = DataFrame( + { + "A": [1, 1, 2, 2, 3], + "B": [1, "foo", 2, "bar", False], + "C": ["a", "b", "c", "d", "e"], + } + ) + df._consolidate_inplace() # should already be consolidate, but double-check + if not using_array_manager: + assert len(df._mgr.blocks) == 3 if using_infer_string else 2 + + gb = df.groupby("A") + + result = gb[["C"]].max() + # "max" is valid for column "C" but not for "B" + ei = pd.Index([1, 2, 3], name="A") + expected = DataFrame({"C": ["b", "d", "e"]}, index=ei) + tm.assert_frame_equal(result, expected) + + result = gb[["C"]].min() + # "min" is valid for column "C" but not for "B" + ei = pd.Index([1, 2, 3], name="A") + expected = DataFrame({"C": ["a", "c", "e"]}, index=ei) + tm.assert_frame_equal(result, expected) + + +def test_min_date_with_nans(): + # GH26321 + dates = pd.to_datetime( + Series(["2019-05-09", "2019-05-09", "2019-05-09"]), format="%Y-%m-%d" + ).dt.date + df = DataFrame({"a": [np.nan, "1", np.nan], "b": [0, 1, 1], "c": dates}) + + result = df.groupby("b", as_index=False)["c"].min()["c"] + expected = pd.to_datetime( + Series(["2019-05-09", "2019-05-09"], name="c"), format="%Y-%m-%d" + ).dt.date + tm.assert_series_equal(result, expected) + + result = df.groupby("b")["c"].min() + expected.index.name = "b" + tm.assert_series_equal(result, expected) + + +def test_max_inat(): + # GH#40767 dont interpret iNaT as NaN + ser = Series([1, iNaT]) + key = np.array([1, 1], dtype=np.int64) + gb = ser.groupby(key) + + result = gb.max(min_count=2) + expected = Series({1: 1}, dtype=np.int64) + tm.assert_series_equal(result, expected, check_exact=True) + + result = gb.min(min_count=2) + expected = Series({1: iNaT}, dtype=np.int64) + tm.assert_series_equal(result, expected, check_exact=True) + + # not enough entries -> gets masked to NaN + result = gb.min(min_count=3) + expected = Series({1: np.nan}) + tm.assert_series_equal(result, expected, check_exact=True) + + +def test_max_inat_not_all_na(): + # GH#40767 dont interpret iNaT as NaN + + # make sure we dont round iNaT+1 to iNaT + ser = Series([1, iNaT, 2, iNaT + 1]) + gb = ser.groupby([1, 2, 3, 3]) + result = gb.min(min_count=2) + + # Note: in converting to float64, the iNaT + 1 maps to iNaT, i.e. is lossy + expected = Series({1: np.nan, 2: np.nan, 3: iNaT + 1}) + expected.index = expected.index.astype(int) + tm.assert_series_equal(result, expected, check_exact=True) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_groupby_aggregate_period_column(func): + # GH 31471 + groups = [1, 2] + periods = pd.period_range("2020", periods=2, freq="Y") + df = DataFrame({"a": groups, "b": periods}) + + result = getattr(df.groupby("a")["b"], func)() + idx = pd.Index([1, 2], name="a") + expected = Series(periods, index=idx, name="b") + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_groupby_aggregate_period_frame(func): + # GH 31471 + groups = [1, 2] + periods = pd.period_range("2020", periods=2, freq="Y") + df = DataFrame({"a": groups, "b": periods}) + + result = getattr(df.groupby("a"), func)() + idx = pd.Index([1, 2], name="a") + expected = DataFrame({"b": periods}, index=idx) + + tm.assert_frame_equal(result, expected) + + +def test_aggregate_numeric_object_dtype(): + # https://github.com/pandas-dev/pandas/issues/39329 + # simplified case: multiple object columns where one is all-NaN + # -> gets split as the all-NaN is inferred as float + df = DataFrame( + {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": [np.nan] * 4}, + ).astype(object) + result = df.groupby("key").min() + expected = ( + DataFrame( + {"key": ["A", "B"], "col1": ["a", "c"], "col2": [np.nan, np.nan]}, + ) + .set_index("key") + .astype(object) + ) + tm.assert_frame_equal(result, expected) + + # same but with numbers + df = DataFrame( + {"key": ["A", "A", "B", "B"], "col1": list("abcd"), "col2": range(4)}, + ).astype(object) + result = df.groupby("key").min() + expected = ( + DataFrame({"key": ["A", "B"], "col1": ["a", "c"], "col2": [0, 2]}) + .set_index("key") + .astype(object) + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_aggregate_categorical_lost_index(func: str): + # GH: 28641 groupby drops index, when grouping over categorical column with min/max + ds = Series(["b"], dtype="category").cat.as_ordered() + df = DataFrame({"A": [1997], "B": ds}) + result = df.groupby("A").agg({"B": func}) + expected = DataFrame({"B": ["b"]}, index=pd.Index([1997], name="A")) + + # ordered categorical dtype should be preserved + expected["B"] = expected["B"].astype(ds.dtype) + + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", ["Int64", "Int32", "Float64", "Float32", "boolean"]) +def test_groupby_min_max_nullable(dtype): + if dtype == "Int64": + # GH#41743 avoid precision loss + ts = 1618556707013635762 + elif dtype == "boolean": + ts = 0 + else: + ts = 4.0 + + df = DataFrame({"id": [2, 2], "ts": [ts, ts + 1]}) + df["ts"] = df["ts"].astype(dtype) + + gb = df.groupby("id") + + result = gb.min() + expected = df.iloc[:1].set_index("id") + tm.assert_frame_equal(result, expected) + + res_max = gb.max() + expected_max = df.iloc[1:].set_index("id") + tm.assert_frame_equal(res_max, expected_max) + + result2 = gb.min(min_count=3) + expected2 = DataFrame({"ts": [pd.NA]}, index=expected.index, dtype=dtype) + tm.assert_frame_equal(result2, expected2) + + res_max2 = gb.max(min_count=3) + tm.assert_frame_equal(res_max2, expected2) + + # Case with NA values + df2 = DataFrame({"id": [2, 2, 2], "ts": [ts, pd.NA, ts + 1]}) + df2["ts"] = df2["ts"].astype(dtype) + gb2 = df2.groupby("id") + + result3 = gb2.min() + tm.assert_frame_equal(result3, expected) + + res_max3 = gb2.max() + tm.assert_frame_equal(res_max3, expected_max) + + result4 = gb2.min(min_count=100) + tm.assert_frame_equal(result4, expected2) + + res_max4 = gb2.max(min_count=100) + tm.assert_frame_equal(res_max4, expected2) + + +def test_min_max_nullable_uint64_empty_group(): + # don't raise NotImplementedError from libgroupby + cat = pd.Categorical([0] * 10, categories=[0, 1]) + df = DataFrame({"A": cat, "B": pd.array(np.arange(10, dtype=np.uint64))}) + gb = df.groupby("A", observed=False) + + res = gb.min() + + idx = pd.CategoricalIndex([0, 1], dtype=cat.dtype, name="A") + expected = DataFrame({"B": pd.array([0, pd.NA], dtype="UInt64")}, index=idx) + tm.assert_frame_equal(res, expected) + + res = gb.max() + expected.iloc[0, 0] = 9 + tm.assert_frame_equal(res, expected) + + +@pytest.mark.parametrize("func", ["first", "last", "min", "max"]) +def test_groupby_min_max_categorical(func): + # GH: 52151 + df = DataFrame( + { + "col1": pd.Categorical(["A"], categories=list("AB"), ordered=True), + "col2": pd.Categorical([1], categories=[1, 2], ordered=True), + "value": 0.1, + } + ) + result = getattr(df.groupby("col1", observed=False), func)() + + idx = pd.CategoricalIndex(data=["A", "B"], name="col1", ordered=True) + expected = DataFrame( + { + "col2": pd.Categorical([1, None], categories=[1, 2], ordered=True), + "value": [0.1, None], + }, + index=idx, + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("func", ["min", "max"]) +def test_min_empty_string_dtype(func, string_dtype_no_object): + # GH#55619 + dtype = string_dtype_no_object + df = DataFrame({"a": ["a"], "b": "a", "c": "a"}, dtype=dtype).iloc[:0] + result = getattr(df.groupby("a"), func)() + expected = DataFrame( + columns=["b", "c"], dtype=dtype, index=pd.Index([], dtype=dtype, name="a") + ) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("min_count", [0, 1]) +@pytest.mark.parametrize("test_series", [True, False]) +def test_string_dtype_all_na( + string_dtype_no_object, reduction_func, min_count, test_series +): + # https://github.com/pandas-dev/pandas/issues/60985 + if reduction_func == "corrwith": + # corrwith is deprecated. + return + + dtype = string_dtype_no_object + + if reduction_func in [ + "any", + "all", + "idxmin", + "idxmax", + "mean", + "median", + "std", + "var", + ]: + kwargs = {} + elif reduction_func in ["kurt"]: + kwargs = {"min_count": min_count} + elif reduction_func in ["count", "nunique", "quantile", "sem", "size"]: + kwargs = {} + else: + kwargs = {"min_count": min_count} + + expected_dtype, expected_value = dtype, pd.NA + if reduction_func in ["all", "any"]: + expected_dtype = "bool" + # TODO: For skipna=False, bool(pd.NA) raises; should groupby? + expected_value = False if reduction_func == "any" else True + elif reduction_func in ["count", "nunique", "size"]: + # TODO: Should be more consistent - return Int64 when dtype.na_value is pd.NA? + if ( + test_series + and reduction_func == "size" + and dtype.storage == "pyarrow" + and dtype.na_value is pd.NA + ): + expected_dtype = "Int64" + else: + expected_dtype = "int64" + expected_value = 1 if reduction_func == "size" else 0 + elif reduction_func in ["idxmin", "idxmax"]: + expected_dtype, expected_value = "float64", np.nan + elif min_count > 0: + expected_value = pd.NA + elif reduction_func == "sum": + # https://github.com/pandas-dev/pandas/pull/60936 + expected_value = "" + + df = DataFrame({"a": ["x"], "b": [pd.NA]}, dtype=dtype) + obj = df["b"] if test_series else df + args = get_groupby_method_args(reduction_func, obj) + gb = obj.groupby(df["a"]) + method = getattr(gb, reduction_func) + + if reduction_func in [ + "mean", + "median", + "kurt", + "prod", + "quantile", + "sem", + "skew", + "std", + "var", + ]: + msg = f"dtype '{dtype}' does not support operation '{reduction_func}'" + with pytest.raises(TypeError, match=msg): + method(*args, **kwargs) + return + + result = method(*args, **kwargs) + index = pd.Index(["x"], name="a", dtype=dtype) + if test_series or reduction_func == "size": + name = None if not test_series and reduction_func == "size" else "b" + expected = Series(expected_value, index=index, dtype=expected_dtype, name=name) + else: + expected = DataFrame({"b": expected_value}, index=index, dtype=expected_dtype) + tm.assert_equal(result, expected) + + +@pytest.mark.parametrize("min_count", [0, 1]) +def test_string_dtype_empty_sum(string_dtype_no_object, min_count): + # https://github.com/pandas-dev/pandas/issues/60229 + dtype = string_dtype_no_object + df = DataFrame({"a": ["x"], "b": [pd.NA]}, dtype=dtype) + gb = df.groupby("a") + result = gb.sum(min_count=min_count) + value = "" if min_count == 0 else pd.NA + expected = DataFrame( + {"b": value}, index=pd.Index(["x"], name="a", dtype=dtype), dtype=dtype + ) + tm.assert_frame_equal(result, expected) + + +def test_max_nan_bug(): + df = DataFrame( + { + "Unnamed: 0": ["-04-23", "-05-06", "-05-07"], + "Date": [ + "2013-04-23 00:00:00", + "2013-05-06 00:00:00", + "2013-05-07 00:00:00", + ], + "app": Series([np.nan, np.nan, "OE"]), + "File": ["log080001.log", "log.log", "xlsx"], + } + ) + gb = df.groupby("Date") + r = gb[["File"]].max() + e = gb["File"].max().to_frame() + tm.assert_frame_equal(r, e) + assert not r["File"].isna().any() + + +@pytest.mark.slow +@pytest.mark.parametrize("sort", [False, True]) +@pytest.mark.parametrize("dropna", [False, True]) +@pytest.mark.parametrize("as_index", [True, False]) +@pytest.mark.parametrize("with_nan", [True, False]) +@pytest.mark.parametrize("keys", [["joe"], ["joe", "jim"]]) +def test_series_groupby_nunique(sort, dropna, as_index, with_nan, keys): + n = 100 + m = 10 + days = date_range("2015-08-23", periods=10) + df = DataFrame( + { + "jim": np.random.default_rng(2).choice(list(ascii_lowercase), n), + "joe": np.random.default_rng(2).choice(days, n), + "julie": np.random.default_rng(2).integers(0, m, n), + } + ) + if with_nan: + df = df.astype({"julie": float}) # Explicit cast to avoid implicit cast below + df.loc[1::17, "jim"] = None + df.loc[3::37, "joe"] = None + df.loc[7::19, "julie"] = None + df.loc[8::19, "julie"] = None + df.loc[9::19, "julie"] = None + original_df = df.copy() + gr = df.groupby(keys, as_index=as_index, sort=sort) + left = gr["julie"].nunique(dropna=dropna) + + gr = df.groupby(keys, as_index=as_index, sort=sort) + right = gr["julie"].apply(Series.nunique, dropna=dropna) + if not as_index: + right = right.reset_index(drop=True) + + if as_index: + tm.assert_series_equal(left, right, check_names=False) + else: + tm.assert_frame_equal(left, right, check_names=False) + tm.assert_frame_equal(df, original_df) + + +def test_nunique(): + df = DataFrame({"A": list("abbacc"), "B": list("abxacc"), "C": list("abbacx")}) + + expected = DataFrame({"A": list("abc"), "B": [1, 2, 1], "C": [1, 1, 2]}) + result = df.groupby("A", as_index=False).nunique() + tm.assert_frame_equal(result, expected) + + # as_index + expected.index = list("abc") + expected.index.name = "A" + expected = expected.drop(columns="A") + result = df.groupby("A").nunique() + tm.assert_frame_equal(result, expected) + + # with na + result = df.replace({"x": None}).groupby("A").nunique(dropna=False) + tm.assert_frame_equal(result, expected) + + # dropna + expected = DataFrame({"B": [1] * 3, "C": [1] * 3}, index=list("abc")) + expected.index.name = "A" + result = df.replace({"x": None}).groupby("A").nunique() + tm.assert_frame_equal(result, expected) + + +def test_nunique_with_object(): + # GH 11077 + data = DataFrame( + [ + [100, 1, "Alice"], + [200, 2, "Bob"], + [300, 3, "Charlie"], + [-400, 4, "Dan"], + [500, 5, "Edith"], + ], + columns=["amount", "id", "name"], + ) + + result = data.groupby(["id", "amount"])["name"].nunique() + index = MultiIndex.from_arrays([data.id, data.amount]) + expected = Series([1] * 5, name="name", index=index) + tm.assert_series_equal(result, expected) + + +def test_nunique_with_empty_series(): + # GH 12553 + data = Series(name="name", dtype=object) + result = data.groupby(level=0).nunique() + expected = Series(name="name", dtype="int64") + tm.assert_series_equal(result, expected) + + +def test_nunique_with_timegrouper(): + # GH 13453 + test = DataFrame( + { + "time": [ + Timestamp("2016-06-28 09:35:35"), + Timestamp("2016-06-28 16:09:30"), + Timestamp("2016-06-28 16:46:28"), + ], + "data": ["1", "2", "3"], + } + ).set_index("time") + result = test.groupby(pd.Grouper(freq="h"))["data"].nunique() + expected = test.groupby(pd.Grouper(freq="h"))["data"].apply(Series.nunique) + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "key, data, dropna, expected", + [ + ( + ["x", "x", "x"], + [Timestamp("2019-01-01"), pd.NaT, Timestamp("2019-01-01")], + True, + Series([1], index=pd.Index(["x"], name="key"), name="data"), + ), + ( + ["x", "x", "x"], + [dt.date(2019, 1, 1), pd.NaT, dt.date(2019, 1, 1)], + True, + Series([1], index=pd.Index(["x"], name="key"), name="data"), + ), + ( + ["x", "x", "x", "y", "y"], + [ + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + ], + False, + Series([2, 2], index=pd.Index(["x", "y"], name="key"), name="data"), + ), + ( + ["x", "x", "x", "x", "y"], + [ + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + pd.NaT, + dt.date(2019, 1, 1), + ], + False, + Series([2, 1], index=pd.Index(["x", "y"], name="key"), name="data"), + ), + ], +) +def test_nunique_with_NaT(key, data, dropna, expected): + # GH 27951 + df = DataFrame({"key": key, "data": data}) + result = df.groupby(["key"])["data"].nunique(dropna=dropna) + tm.assert_series_equal(result, expected) + + +def test_nunique_preserves_column_level_names(): + # GH 23222 + test = DataFrame([1, 2, 2], columns=pd.Index(["A"], name="level_0")) + result = test.groupby([0, 0, 0]).nunique() + expected = DataFrame([2], index=np.array([0]), columns=test.columns) + tm.assert_frame_equal(result, expected) + + +def test_nunique_transform_with_datetime(): + # GH 35109 - transform with nunique on datetimes results in integers + df = DataFrame(date_range("2008-12-31", "2009-01-02"), columns=["date"]) + result = df.groupby([0, 0, 1])["date"].transform("nunique") + expected = Series([2, 2, 1], name="date") + tm.assert_series_equal(result, expected) + + +def test_empty_categorical(observed): + # GH#21334 + cat = Series([1]).astype("category") + ser = cat[:0] + gb = ser.groupby(ser, observed=observed) + result = gb.nunique() + if observed: + expected = Series([], index=cat[:0], dtype="int64") + else: + expected = Series([0], index=cat, dtype="int64") + tm.assert_series_equal(result, expected) + + +def test_intercept_builtin_sum(): + s = Series([1.0, 2.0, np.nan, 3.0]) + grouped = s.groupby([0, 1, 2, 2]) + + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = grouped.agg(builtins.sum) + msg = "using np.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result2 = grouped.apply(builtins.sum) + expected = grouped.sum() + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, expected) + + +@pytest.mark.parametrize("min_count", [0, 10]) +def test_groupby_sum_mincount_boolean(min_count): + b = True + a = False + na = np.nan + dfg = pd.array([b, b, na, na, a, a, b], dtype="boolean") + + df = DataFrame({"A": [1, 1, 2, 2, 3, 3, 1], "B": dfg}) + result = df.groupby("A").sum(min_count=min_count) + if min_count == 0: + expected = DataFrame( + {"B": pd.array([3, 0, 0], dtype="Int64")}, + index=pd.Index([1, 2, 3], name="A"), + ) + tm.assert_frame_equal(result, expected) + else: + expected = DataFrame( + {"B": pd.array([pd.NA] * 3, dtype="Int64")}, + index=pd.Index([1, 2, 3], name="A"), + ) + tm.assert_frame_equal(result, expected) + + +def test_groupby_sum_below_mincount_nullable_integer(): + # https://github.com/pandas-dev/pandas/issues/32861 + df = DataFrame({"a": [0, 1, 2], "b": [0, 1, 2], "c": [0, 1, 2]}, dtype="Int64") + grouped = df.groupby("a") + idx = pd.Index([0, 1, 2], name="a", dtype="Int64") + + result = grouped["b"].sum(min_count=2) + expected = Series([pd.NA] * 3, dtype="Int64", index=idx, name="b") + tm.assert_series_equal(result, expected) + + result = grouped.sum(min_count=2) + expected = DataFrame({"b": [pd.NA] * 3, "c": [pd.NA] * 3}, dtype="Int64", index=idx) + tm.assert_frame_equal(result, expected) + + +def test_groupby_sum_timedelta_with_nat(): + # GH#42659 + df = DataFrame( + { + "a": [1, 1, 2, 2], + "b": [pd.Timedelta("1d"), pd.Timedelta("2d"), pd.Timedelta("3d"), pd.NaT], + } + ) + td3 = pd.Timedelta(days=3) + + gb = df.groupby("a") + + res = gb.sum() + expected = DataFrame({"b": [td3, td3]}, index=pd.Index([1, 2], name="a")) + tm.assert_frame_equal(res, expected) + + res = gb["b"].sum() + tm.assert_series_equal(res, expected["b"]) + + res = gb["b"].sum(min_count=2) + expected = Series([td3, pd.NaT], dtype="m8[ns]", name="b", index=expected.index) + tm.assert_series_equal(res, expected) + + +@pytest.mark.parametrize( + "dtype", ["int8", "int16", "int32", "int64", "float32", "float64", "uint64"] +) +@pytest.mark.parametrize( + "method,data", + [ + ("first", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), + ("last", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), + ("min", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), + ("max", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), + ("count", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 2}], "out_type": "int64"}), + ], +) +def test_groupby_non_arithmetic_agg_types(dtype, method, data): + # GH9311, GH6620 + df = DataFrame( + [{"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 2, "b": 3}, {"a": 2, "b": 4}] + ) + + df["b"] = df.b.astype(dtype) + + if "args" not in data: + data["args"] = [] + + if "out_type" in data: + out_type = data["out_type"] + else: + out_type = dtype + + exp = data["df"] + df_out = DataFrame(exp) + + df_out["b"] = df_out.b.astype(out_type) + df_out.set_index("a", inplace=True) + + grpd = df.groupby("a") + t = getattr(grpd, method)(*data["args"]) + tm.assert_frame_equal(t, df_out) + + +def scipy_sem(*args, **kwargs): + from scipy.stats import sem + + return sem(*args, ddof=1, **kwargs) + + +@pytest.mark.parametrize( + "op,targop", + [ + ("mean", np.mean), + ("median", np.median), + ("std", np.std), + ("var", np.var), + ("sum", np.sum), + ("prod", np.prod), + ("min", np.min), + ("max", np.max), + ("first", lambda x: x.iloc[0]), + ("last", lambda x: x.iloc[-1]), + ("count", np.size), + pytest.param("sem", scipy_sem, marks=td.skip_if_no("scipy")), + ], +) +def test_ops_general(op, targop): + df = DataFrame(np.random.default_rng(2).standard_normal(1000)) + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + + result = getattr(df.groupby(labels), op)() + warn = None if op in ("first", "last", "count", "sem") else FutureWarning + msg = f"using DataFrameGroupBy.{op}" + with tm.assert_produces_warning(warn, match=msg): + expected = df.groupby(labels).agg(targop) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "values", + [ + { + "a": [1, 1, 1, 2, 2, 2, 3, 3, 3], + "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2], + }, + {"a": [1, 1, 2, 2, 3, 3], "b": [1, 2, 1, 2, 1, 2]}, + ], +) +@pytest.mark.parametrize("function", ["mean", "median", "var"]) +def test_apply_to_nullable_integer_returns_float(values, function): + # https://github.com/pandas-dev/pandas/issues/32219 + output = 0.5 if function == "var" else 1.5 + arr = np.array([output] * 3, dtype=float) + idx = pd.Index([1, 2, 3], name="a", dtype="Int64") + expected = DataFrame({"b": arr}, index=idx).astype("Float64") + + groups = DataFrame(values, dtype="Int64").groupby("a") + + result = getattr(groups, function)() + tm.assert_frame_equal(result, expected) + + result = groups.agg(function) + tm.assert_frame_equal(result, expected) + + result = groups.agg([function]) + expected.columns = MultiIndex.from_tuples([("b", function)]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op", + [ + "sum", + "prod", + "min", + "max", + "median", + "mean", + "skew", + "std", + "var", + "sem", + ], +) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("skipna", [True, False]) +@pytest.mark.parametrize("sort", [True, False]) +def test_regression_allowlist_methods(op, axis, skipna, sort): + # GH6944 + # GH 17537 + # explicitly test the allowlist methods + raw_frame = DataFrame([0]) + if axis == 0: + frame = raw_frame + msg = "The 'axis' keyword in DataFrame.groupby is deprecated and will be" + else: + frame = raw_frame.T + msg = "DataFrame.groupby with axis=1 is deprecated" + + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = frame.groupby(level=0, axis=axis, sort=sort) + + if op == "skew": + # skew has skipna + result = getattr(grouped, op)(skipna=skipna) + expected = frame.groupby(level=0).apply( + lambda h: getattr(h, op)(axis=axis, skipna=skipna) + ) + if sort: + expected = expected.sort_index(axis=axis) + tm.assert_frame_equal(result, expected) + else: + result = getattr(grouped, op)() + expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)(axis=axis)) + if sort: + expected = expected.sort_index(axis=axis) + tm.assert_frame_equal(result, expected) + + +def test_groupby_prod_with_int64_dtype(): + # GH#46573 + data = [ + [1, 11], + [1, 41], + [1, 17], + [1, 37], + [1, 7], + [1, 29], + [1, 31], + [1, 2], + [1, 3], + [1, 43], + [1, 5], + [1, 47], + [1, 19], + [1, 88], + ] + df = DataFrame(data, columns=["A", "B"], dtype="int64") + result = df.groupby(["A"]).prod().reset_index() + expected = DataFrame({"A": [1], "B": [180970905912331920]}, dtype="int64") + tm.assert_frame_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_timegrouper.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_timegrouper.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc2e84c559532e73fc18fa389614ca988fd4f17 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/groupby/test_timegrouper.py @@ -0,0 +1,965 @@ +""" +test with the TimeGrouper / grouping with datetimes +""" +from datetime import ( + datetime, + timedelta, +) + +import numpy as np +import pytest +import pytz + +import pandas as pd +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + Timestamp, + date_range, + offsets, +) +import pandas._testing as tm +from pandas.core.groupby.grouper import Grouper +from pandas.core.groupby.ops import BinGrouper + + +@pytest.fixture +def frame_for_truncated_bingrouper(): + """ + DataFrame used by groupby_with_truncated_bingrouper, made into + a separate fixture for easier reuse in + test_groupby_apply_timegrouper_with_nat_apply_squeeze + """ + df = DataFrame( + { + "Quantity": [18, 3, 5, 1, 9, 3], + "Date": [ + Timestamp(2013, 9, 1, 13, 0), + Timestamp(2013, 9, 1, 13, 5), + Timestamp(2013, 10, 1, 20, 0), + Timestamp(2013, 10, 3, 10, 0), + pd.NaT, + Timestamp(2013, 9, 2, 14, 0), + ], + } + ) + return df + + +@pytest.fixture +def groupby_with_truncated_bingrouper(frame_for_truncated_bingrouper): + """ + GroupBy object such that gb._grouper is a BinGrouper and + len(gb._grouper.result_index) < len(gb._grouper.group_keys_seq) + + Aggregations on this groupby should have + + dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date") + + As either the index or an index level. + """ + df = frame_for_truncated_bingrouper + + tdg = Grouper(key="Date", freq="5D") + gb = df.groupby(tdg) + + # check we're testing the case we're interested in + assert len(gb._grouper.result_index) != len(gb._grouper.group_keys_seq) + + return gb + + +class TestGroupBy: + def test_groupby_with_timegrouper(self, using_infer_string): + # GH 4161 + # TimeGrouper requires a sorted index + # also verifies that the resultant index has the correct name + df_original = DataFrame( + { + "Buyer": "Carl Carl Carl Carl Joe Carl".split(), + "Quantity": [18, 3, 5, 1, 9, 3], + "Date": [ + datetime(2013, 9, 1, 13, 0), + datetime(2013, 9, 1, 13, 5), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 3, 10, 0), + datetime(2013, 12, 2, 12, 0), + datetime(2013, 9, 2, 14, 0), + ], + } + ) + + # GH 6908 change target column's order + df_reordered = df_original.sort_values(by="Quantity") + + for df in [df_original, df_reordered]: + df = df.set_index(["Date"]) + + exp_dti = date_range( + "20130901", + "20131205", + freq="5D", + name="Date", + inclusive="left", + unit=df.index.unit, + ) + expected = DataFrame( + {"Buyer": "" if using_infer_string else 0, "Quantity": 0}, + index=exp_dti, + ) + # Cast to object to avoid implicit cast when setting entry to "CarlCarlCarl" + expected = expected.astype({"Buyer": object}) + if using_infer_string: + expected = expected.astype({"Buyer": "str"}) + expected.iloc[0, 0] = "CarlCarlCarl" + expected.iloc[6, 0] = "CarlCarl" + expected.iloc[18, 0] = "Joe" + expected.iloc[[0, 6, 18], 1] = np.array([24, 6, 9], dtype="int64") + + result1 = df.resample("5D").sum() + tm.assert_frame_equal(result1, expected) + + df_sorted = df.sort_index() + result2 = df_sorted.groupby(Grouper(freq="5D")).sum() + tm.assert_frame_equal(result2, expected) + + result3 = df.groupby(Grouper(freq="5D")).sum() + tm.assert_frame_equal(result3, expected) + + @pytest.mark.parametrize("should_sort", [True, False]) + def test_groupby_with_timegrouper_methods(self, should_sort): + # GH 3881 + # make sure API of timegrouper conforms + + df = DataFrame( + { + "Branch": "A A A A A B".split(), + "Buyer": "Carl Mark Carl Joe Joe Carl".split(), + "Quantity": [1, 3, 5, 8, 9, 3], + "Date": [ + datetime(2013, 1, 1, 13, 0), + datetime(2013, 1, 1, 13, 5), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 2, 10, 0), + datetime(2013, 12, 2, 12, 0), + datetime(2013, 12, 2, 14, 0), + ], + } + ) + + if should_sort: + df = df.sort_values(by="Quantity", ascending=False) + + df = df.set_index("Date", drop=False) + g = df.groupby(Grouper(freq="6ME")) + assert g.group_keys + + assert isinstance(g._grouper, BinGrouper) + groups = g.groups + assert isinstance(groups, dict) + assert len(groups) == 3 + + def test_timegrouper_with_reg_groups(self): + # GH 3794 + # allow combination of timegrouper/reg groups + + df_original = DataFrame( + { + "Branch": "A A A A A A A B".split(), + "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(), + "Quantity": [1, 3, 5, 1, 8, 1, 9, 3], + "Date": [ + datetime(2013, 1, 1, 13, 0), + datetime(2013, 1, 1, 13, 5), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 2, 10, 0), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 2, 10, 0), + datetime(2013, 12, 2, 12, 0), + datetime(2013, 12, 2, 14, 0), + ], + } + ).set_index("Date") + + df_sorted = df_original.sort_values(by="Quantity", ascending=False) + + for df in [df_original, df_sorted]: + expected = DataFrame( + { + "Buyer": "Carl Joe Mark".split(), + "Quantity": [10, 18, 3], + "Date": [ + datetime(2013, 12, 31, 0, 0), + datetime(2013, 12, 31, 0, 0), + datetime(2013, 12, 31, 0, 0), + ], + } + ).set_index(["Date", "Buyer"]) + + msg = "The default value of numeric_only" + result = df.groupby([Grouper(freq="YE"), "Buyer"]).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + expected = DataFrame( + { + "Buyer": "Carl Mark Carl Joe".split(), + "Quantity": [1, 3, 9, 18], + "Date": [ + datetime(2013, 1, 1, 0, 0), + datetime(2013, 1, 1, 0, 0), + datetime(2013, 7, 1, 0, 0), + datetime(2013, 7, 1, 0, 0), + ], + } + ).set_index(["Date", "Buyer"]) + result = df.groupby([Grouper(freq="6MS"), "Buyer"]).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + df_original = DataFrame( + { + "Branch": "A A A A A A A B".split(), + "Buyer": "Carl Mark Carl Carl Joe Joe Joe Carl".split(), + "Quantity": [1, 3, 5, 1, 8, 1, 9, 3], + "Date": [ + datetime(2013, 10, 1, 13, 0), + datetime(2013, 10, 1, 13, 5), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 2, 10, 0), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 2, 10, 0), + datetime(2013, 10, 2, 12, 0), + datetime(2013, 10, 2, 14, 0), + ], + } + ).set_index("Date") + + df_sorted = df_original.sort_values(by="Quantity", ascending=False) + for df in [df_original, df_sorted]: + expected = DataFrame( + { + "Buyer": "Carl Joe Mark Carl Joe".split(), + "Quantity": [6, 8, 3, 4, 10], + "Date": [ + datetime(2013, 10, 1, 0, 0), + datetime(2013, 10, 1, 0, 0), + datetime(2013, 10, 1, 0, 0), + datetime(2013, 10, 2, 0, 0), + datetime(2013, 10, 2, 0, 0), + ], + } + ).set_index(["Date", "Buyer"]) + + result = df.groupby([Grouper(freq="1D"), "Buyer"]).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + result = df.groupby([Grouper(freq="1ME"), "Buyer"]).sum(numeric_only=True) + expected = DataFrame( + { + "Buyer": "Carl Joe Mark".split(), + "Quantity": [10, 18, 3], + "Date": [ + datetime(2013, 10, 31, 0, 0), + datetime(2013, 10, 31, 0, 0), + datetime(2013, 10, 31, 0, 0), + ], + } + ).set_index(["Date", "Buyer"]) + tm.assert_frame_equal(result, expected) + + # passing the name + df = df.reset_index() + result = df.groupby([Grouper(freq="1ME", key="Date"), "Buyer"]).sum( + numeric_only=True + ) + tm.assert_frame_equal(result, expected) + + with pytest.raises(KeyError, match="'The grouper name foo is not found'"): + df.groupby([Grouper(freq="1ME", key="foo"), "Buyer"]).sum() + + # passing the level + df = df.set_index("Date") + result = df.groupby([Grouper(freq="1ME", level="Date"), "Buyer"]).sum( + numeric_only=True + ) + tm.assert_frame_equal(result, expected) + result = df.groupby([Grouper(freq="1ME", level=0), "Buyer"]).sum( + numeric_only=True + ) + tm.assert_frame_equal(result, expected) + + with pytest.raises(ValueError, match="The level foo is not valid"): + df.groupby([Grouper(freq="1ME", level="foo"), "Buyer"]).sum() + + # multi names + df = df.copy() + df["Date"] = df.index + offsets.MonthEnd(2) + result = df.groupby([Grouper(freq="1ME", key="Date"), "Buyer"]).sum( + numeric_only=True + ) + expected = DataFrame( + { + "Buyer": "Carl Joe Mark".split(), + "Quantity": [10, 18, 3], + "Date": [ + datetime(2013, 11, 30, 0, 0), + datetime(2013, 11, 30, 0, 0), + datetime(2013, 11, 30, 0, 0), + ], + } + ).set_index(["Date", "Buyer"]) + tm.assert_frame_equal(result, expected) + + # error as we have both a level and a name! + msg = "The Grouper cannot specify both a key and a level!" + with pytest.raises(ValueError, match=msg): + df.groupby( + [Grouper(freq="1ME", key="Date", level="Date"), "Buyer"] + ).sum() + + # single groupers + expected = DataFrame( + [[31]], + columns=["Quantity"], + index=DatetimeIndex( + [datetime(2013, 10, 31, 0, 0)], freq=offsets.MonthEnd(), name="Date" + ), + ) + result = df.groupby(Grouper(freq="1ME")).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + result = df.groupby([Grouper(freq="1ME")]).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + expected.index = expected.index.shift(1) + assert expected.index.freq == offsets.MonthEnd() + result = df.groupby(Grouper(freq="1ME", key="Date")).sum(numeric_only=True) + tm.assert_frame_equal(result, expected) + + result = df.groupby([Grouper(freq="1ME", key="Date")]).sum( + numeric_only=True + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("freq", ["D", "ME", "YE", "QE-APR"]) + def test_timegrouper_with_reg_groups_freq(self, freq): + # GH 6764 multiple grouping with/without sort + df = DataFrame( + { + "date": pd.to_datetime( + [ + "20121002", + "20121007", + "20130130", + "20130202", + "20130305", + "20121002", + "20121207", + "20130130", + "20130202", + "20130305", + "20130202", + "20130305", + ] + ), + "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5], + "whole_cost": [ + 1790, + 364, + 280, + 259, + 201, + 623, + 90, + 312, + 359, + 301, + 359, + 801, + ], + "cost1": [12, 15, 10, 24, 39, 1, 0, 90, 45, 34, 1, 12], + } + ).set_index("date") + + expected = ( + df.groupby("user_id")["whole_cost"] + .resample(freq) + .sum(min_count=1) # XXX + .dropna() + .reorder_levels(["date", "user_id"]) + .sort_index() + .astype("int64") + ) + expected.name = "whole_cost" + + result1 = ( + df.sort_index().groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum() + ) + tm.assert_series_equal(result1, expected) + + result2 = df.groupby([Grouper(freq=freq), "user_id"])["whole_cost"].sum() + tm.assert_series_equal(result2, expected) + + def test_timegrouper_get_group(self): + # GH 6914 + + df_original = DataFrame( + { + "Buyer": "Carl Joe Joe Carl Joe Carl".split(), + "Quantity": [18, 3, 5, 1, 9, 3], + "Date": [ + datetime(2013, 9, 1, 13, 0), + datetime(2013, 9, 1, 13, 5), + datetime(2013, 10, 1, 20, 0), + datetime(2013, 10, 3, 10, 0), + datetime(2013, 12, 2, 12, 0), + datetime(2013, 9, 2, 14, 0), + ], + } + ) + df_reordered = df_original.sort_values(by="Quantity") + + # single grouping + expected_list = [ + df_original.iloc[[0, 1, 5]], + df_original.iloc[[2, 3]], + df_original.iloc[[4]], + ] + dt_list = ["2013-09-30", "2013-10-31", "2013-12-31"] + + for df in [df_original, df_reordered]: + grouped = df.groupby(Grouper(freq="ME", key="Date")) + for t, expected in zip(dt_list, expected_list): + dt = Timestamp(t) + result = grouped.get_group(dt) + tm.assert_frame_equal(result, expected) + + # multiple grouping + expected_list = [ + df_original.iloc[[1]], + df_original.iloc[[3]], + df_original.iloc[[4]], + ] + g_list = [("Joe", "2013-09-30"), ("Carl", "2013-10-31"), ("Joe", "2013-12-31")] + + for df in [df_original, df_reordered]: + grouped = df.groupby(["Buyer", Grouper(freq="ME", key="Date")]) + for (b, t), expected in zip(g_list, expected_list): + dt = Timestamp(t) + result = grouped.get_group((b, dt)) + tm.assert_frame_equal(result, expected) + + # with index + df_original = df_original.set_index("Date") + df_reordered = df_original.sort_values(by="Quantity") + + expected_list = [ + df_original.iloc[[0, 1, 5]], + df_original.iloc[[2, 3]], + df_original.iloc[[4]], + ] + + for df in [df_original, df_reordered]: + grouped = df.groupby(Grouper(freq="ME")) + for t, expected in zip(dt_list, expected_list): + dt = Timestamp(t) + result = grouped.get_group(dt) + tm.assert_frame_equal(result, expected) + + def test_timegrouper_apply_return_type_series(self): + # Using `apply` with the `TimeGrouper` should give the + # same return type as an `apply` with a `Grouper`. + # Issue #11742 + df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]}) + df_dt = df.copy() + df_dt["date"] = pd.to_datetime(df_dt["date"]) + + def sumfunc_series(x): + return Series([x["value"].sum()], ("sum",)) + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.groupby(Grouper(key="date")).apply(sumfunc_series) + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df_dt.groupby(Grouper(freq="ME", key="date")).apply(sumfunc_series) + tm.assert_frame_equal( + result.reset_index(drop=True), expected.reset_index(drop=True) + ) + + def test_timegrouper_apply_return_type_value(self): + # Using `apply` with the `TimeGrouper` should give the + # same return type as an `apply` with a `Grouper`. + # Issue #11742 + df = DataFrame({"date": ["10/10/2000", "11/10/2000"], "value": [10, 13]}) + df_dt = df.copy() + df_dt["date"] = pd.to_datetime(df_dt["date"]) + + def sumfunc_value(x): + return x.value.sum() + + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.groupby(Grouper(key="date")).apply(sumfunc_value) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df_dt.groupby(Grouper(freq="ME", key="date")).apply(sumfunc_value) + tm.assert_series_equal( + result.reset_index(drop=True), expected.reset_index(drop=True) + ) + + def test_groupby_groups_datetimeindex(self): + # GH#1430 + periods = 1000 + ind = date_range(start="2012/1/1", freq="5min", periods=periods) + df = DataFrame( + {"high": np.arange(periods), "low": np.arange(periods)}, index=ind + ) + grouped = df.groupby(lambda x: datetime(x.year, x.month, x.day)) + + # it works! + groups = grouped.groups + assert isinstance(next(iter(groups.keys())), datetime) + + def test_groupby_groups_datetimeindex2(self): + # GH#11442 + index = date_range("2015/01/01", periods=5, name="date") + df = DataFrame({"A": [5, 6, 7, 8, 9], "B": [1, 2, 3, 4, 5]}, index=index) + result = df.groupby(level="date").groups + dates = ["2015-01-05", "2015-01-04", "2015-01-03", "2015-01-02", "2015-01-01"] + expected = { + Timestamp(date): DatetimeIndex([date], name="date") for date in dates + } + tm.assert_dict_equal(result, expected) + + grouped = df.groupby(level="date") + for date in dates: + result = grouped.get_group(date) + data = [[df.loc[date, "A"], df.loc[date, "B"]]] + expected_index = DatetimeIndex( + [date], name="date", freq="D", dtype=index.dtype + ) + expected = DataFrame(data, columns=list("AB"), index=expected_index) + tm.assert_frame_equal(result, expected) + + def test_groupby_groups_datetimeindex_tz(self): + # GH 3950 + dates = [ + "2011-07-19 07:00:00", + "2011-07-19 08:00:00", + "2011-07-19 09:00:00", + "2011-07-19 07:00:00", + "2011-07-19 08:00:00", + "2011-07-19 09:00:00", + ] + df = DataFrame( + { + "label": ["a", "a", "a", "b", "b", "b"], + "datetime": dates, + "value1": np.arange(6, dtype="int64"), + "value2": [1, 2] * 3, + } + ) + df["datetime"] = df["datetime"].apply(lambda d: Timestamp(d, tz="US/Pacific")) + + exp_idx1 = DatetimeIndex( + [ + "2011-07-19 07:00:00", + "2011-07-19 07:00:00", + "2011-07-19 08:00:00", + "2011-07-19 08:00:00", + "2011-07-19 09:00:00", + "2011-07-19 09:00:00", + ], + tz="US/Pacific", + name="datetime", + ) + exp_idx2 = Index(["a", "b"] * 3, name="label") + exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) + expected = DataFrame( + {"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]}, + index=exp_idx, + columns=["value1", "value2"], + ) + + result = df.groupby(["datetime", "label"]).sum() + tm.assert_frame_equal(result, expected) + + # by level + didx = DatetimeIndex(dates, tz="Asia/Tokyo") + df = DataFrame( + {"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]}, + index=didx, + ) + + exp_idx = DatetimeIndex( + ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"], + tz="Asia/Tokyo", + ) + expected = DataFrame( + {"value1": [3, 5, 7], "value2": [2, 4, 6]}, + index=exp_idx, + columns=["value1", "value2"], + ) + + result = df.groupby(level=0).sum() + tm.assert_frame_equal(result, expected) + + def test_frame_datetime64_handling_groupby(self): + # it works! + df = DataFrame( + [(3, np.datetime64("2012-07-03")), (3, np.datetime64("2012-07-04"))], + columns=["a", "date"], + ) + result = df.groupby("a").first() + assert result["date"][3] == Timestamp("2012-07-03") + + def test_groupby_multi_timezone(self): + # combining multiple / different timezones yields UTC + df = DataFrame( + { + "value": range(5), + "date": [ + "2000-01-28 16:47:00", + "2000-01-29 16:48:00", + "2000-01-30 16:49:00", + "2000-01-31 16:50:00", + "2000-01-01 16:50:00", + ], + "tz": [ + "America/Chicago", + "America/Chicago", + "America/Los_Angeles", + "America/Chicago", + "America/New_York", + ], + } + ) + + result = df.groupby("tz", group_keys=False).date.apply( + lambda x: pd.to_datetime(x).dt.tz_localize(x.name) + ) + + expected = Series( + [ + Timestamp("2000-01-28 16:47:00-0600", tz="America/Chicago"), + Timestamp("2000-01-29 16:48:00-0600", tz="America/Chicago"), + Timestamp("2000-01-30 16:49:00-0800", tz="America/Los_Angeles"), + Timestamp("2000-01-31 16:50:00-0600", tz="America/Chicago"), + Timestamp("2000-01-01 16:50:00-0500", tz="America/New_York"), + ], + name="date", + dtype=object, + ) + tm.assert_series_equal(result, expected) + + tz = "America/Chicago" + res_values = df.groupby("tz").date.get_group(tz) + result = pd.to_datetime(res_values).dt.tz_localize(tz) + exp_values = Series( + ["2000-01-28 16:47:00", "2000-01-29 16:48:00", "2000-01-31 16:50:00"], + index=[0, 1, 3], + name="date", + ) + expected = pd.to_datetime(exp_values).dt.tz_localize(tz) + tm.assert_series_equal(result, expected) + + def test_groupby_groups_periods(self): + dates = [ + "2011-07-19 07:00:00", + "2011-07-19 08:00:00", + "2011-07-19 09:00:00", + "2011-07-19 07:00:00", + "2011-07-19 08:00:00", + "2011-07-19 09:00:00", + ] + df = DataFrame( + { + "label": ["a", "a", "a", "b", "b", "b"], + "period": [pd.Period(d, freq="h") for d in dates], + "value1": np.arange(6, dtype="int64"), + "value2": [1, 2] * 3, + } + ) + + exp_idx1 = pd.PeriodIndex( + [ + "2011-07-19 07:00:00", + "2011-07-19 07:00:00", + "2011-07-19 08:00:00", + "2011-07-19 08:00:00", + "2011-07-19 09:00:00", + "2011-07-19 09:00:00", + ], + freq="h", + name="period", + ) + exp_idx2 = Index(["a", "b"] * 3, name="label") + exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) + expected = DataFrame( + {"value1": [0, 3, 1, 4, 2, 5], "value2": [1, 2, 2, 1, 1, 2]}, + index=exp_idx, + columns=["value1", "value2"], + ) + + result = df.groupby(["period", "label"]).sum() + tm.assert_frame_equal(result, expected) + + # by level + didx = pd.PeriodIndex(dates, freq="h") + df = DataFrame( + {"value1": np.arange(6, dtype="int64"), "value2": [1, 2, 3, 1, 2, 3]}, + index=didx, + ) + + exp_idx = pd.PeriodIndex( + ["2011-07-19 07:00:00", "2011-07-19 08:00:00", "2011-07-19 09:00:00"], + freq="h", + ) + expected = DataFrame( + {"value1": [3, 5, 7], "value2": [2, 4, 6]}, + index=exp_idx, + columns=["value1", "value2"], + ) + + result = df.groupby(level=0).sum() + tm.assert_frame_equal(result, expected) + + def test_groupby_first_datetime64(self): + df = DataFrame([(1, 1351036800000000000), (2, 1351036800000000000)]) + df[1] = df[1].astype("M8[ns]") + + assert issubclass(df[1].dtype.type, np.datetime64) + + result = df.groupby(level=0).first() + got_dt = result[1].dtype + assert issubclass(got_dt.type, np.datetime64) + + result = df[1].groupby(level=0).first() + got_dt = result.dtype + assert issubclass(got_dt.type, np.datetime64) + + def test_groupby_max_datetime64(self): + # GH 5869 + # datetimelike dtype conversion from int + df = DataFrame({"A": Timestamp("20130101"), "B": np.arange(5)}) + # TODO: can we retain second reso in .apply here? + expected = df.groupby("A")["A"].apply(lambda x: x.max()).astype("M8[s]") + result = df.groupby("A")["A"].max() + tm.assert_series_equal(result, expected) + + def test_groupby_datetime64_32_bit(self): + # GH 6410 / numpy 4328 + # 32-bit under 1.9-dev indexing issue + + df = DataFrame({"A": range(2), "B": [Timestamp("2000-01-1")] * 2}) + result = df.groupby("A")["B"].transform("min") + expected = Series([Timestamp("2000-01-1")] * 2, name="B") + tm.assert_series_equal(result, expected) + + def test_groupby_with_timezone_selection(self): + # GH 11616 + # Test that column selection returns output in correct timezone. + + df = DataFrame( + { + "factor": np.random.default_rng(2).integers(0, 3, size=60), + "time": date_range("01/01/2000 00:00", periods=60, freq="s", tz="UTC"), + } + ) + df1 = df.groupby("factor").max()["time"] + df2 = df.groupby("factor")["time"].max() + tm.assert_series_equal(df1, df2) + + def test_timezone_info(self): + # see gh-11682: Timezone info lost when broadcasting + # scalar datetime to DataFrame + + df = DataFrame({"a": [1], "b": [datetime.now(pytz.utc)]}) + assert df["b"][0].tzinfo == pytz.utc + df = DataFrame({"a": [1, 2, 3]}) + df["b"] = datetime.now(pytz.utc) + assert df["b"][0].tzinfo == pytz.utc + + def test_datetime_count(self): + df = DataFrame( + {"a": [1, 2, 3] * 2, "dates": date_range("now", periods=6, freq="min")} + ) + result = df.groupby("a").dates.count() + expected = Series([2, 2, 2], index=Index([1, 2, 3], name="a"), name="dates") + tm.assert_series_equal(result, expected) + + def test_first_last_max_min_on_time_data(self): + # GH 10295 + # Verify that NaT is not in the result of max, min, first and last on + # Dataframe with datetime or timedelta values. + df_test = DataFrame( + { + "dt": [ + np.nan, + "2015-07-24 10:10", + "2015-07-25 11:11", + "2015-07-23 12:12", + np.nan, + ], + "td": [ + np.nan, + timedelta(days=1), + timedelta(days=2), + timedelta(days=3), + np.nan, + ], + } + ) + df_test.dt = pd.to_datetime(df_test.dt) + df_test["group"] = "A" + df_ref = df_test[df_test.dt.notna()] + + grouped_test = df_test.groupby("group") + grouped_ref = df_ref.groupby("group") + + tm.assert_frame_equal(grouped_ref.max(), grouped_test.max()) + tm.assert_frame_equal(grouped_ref.min(), grouped_test.min()) + tm.assert_frame_equal(grouped_ref.first(), grouped_test.first()) + tm.assert_frame_equal(grouped_ref.last(), grouped_test.last()) + + def test_nunique_with_timegrouper_and_nat(self): + # GH 17575 + test = DataFrame( + { + "time": [ + Timestamp("2016-06-28 09:35:35"), + pd.NaT, + Timestamp("2016-06-28 16:46:28"), + ], + "data": ["1", "2", "3"], + } + ) + + grouper = Grouper(key="time", freq="h") + result = test.groupby(grouper)["data"].nunique() + expected = test[test.time.notnull()].groupby(grouper)["data"].nunique() + expected.index = expected.index._with_freq(None) + tm.assert_series_equal(result, expected) + + def test_scalar_call_versus_list_call(self): + # Issue: 17530 + data_frame = { + "location": ["shanghai", "beijing", "shanghai"], + "time": Series( + ["2017-08-09 13:32:23", "2017-08-11 23:23:15", "2017-08-11 22:23:15"], + dtype="datetime64[ns]", + ), + "value": [1, 2, 3], + } + data_frame = DataFrame(data_frame).set_index("time") + grouper = Grouper(freq="D") + + grouped = data_frame.groupby(grouper) + result = grouped.count() + grouped = data_frame.groupby([grouper]) + expected = grouped.count() + + tm.assert_frame_equal(result, expected) + + def test_grouper_period_index(self): + # GH 32108 + periods = 2 + index = pd.period_range( + start="2018-01", periods=periods, freq="M", name="Month" + ) + period_series = Series(range(periods), index=index) + result = period_series.groupby(period_series.index.month).sum() + + expected = Series( + range(periods), index=Index(range(1, periods + 1), name=index.name) + ) + tm.assert_series_equal(result, expected) + + def test_groupby_apply_timegrouper_with_nat_dict_returns( + self, groupby_with_truncated_bingrouper + ): + # GH#43500 case where gb._grouper.result_index and gb._grouper.group_keys_seq + # have different lengths that goes through the `isinstance(values[0], dict)` + # path + gb = groupby_with_truncated_bingrouper + + res = gb["Quantity"].apply(lambda x: {"foo": len(x)}) + + df = gb.obj + unit = df["Date"]._values.unit + dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date", unit=unit) + mi = MultiIndex.from_arrays([dti, ["foo"] * len(dti)]) + expected = Series([3, 0, 0, 0, 0, 0, 2], index=mi, name="Quantity") + tm.assert_series_equal(res, expected) + + def test_groupby_apply_timegrouper_with_nat_scalar_returns( + self, groupby_with_truncated_bingrouper + ): + # GH#43500 Previously raised ValueError bc used index with incorrect + # length in wrap_applied_result + gb = groupby_with_truncated_bingrouper + + res = gb["Quantity"].apply(lambda x: x.iloc[0] if len(x) else np.nan) + + df = gb.obj + unit = df["Date"]._values.unit + dti = date_range("2013-09-01", "2013-10-01", freq="5D", name="Date", unit=unit) + expected = Series( + [18, np.nan, np.nan, np.nan, np.nan, np.nan, 5], + index=dti._with_freq(None), + name="Quantity", + ) + + tm.assert_series_equal(res, expected) + + def test_groupby_apply_timegrouper_with_nat_apply_squeeze( + self, frame_for_truncated_bingrouper + ): + df = frame_for_truncated_bingrouper + + # We need to create a GroupBy object with only one non-NaT group, + # so use a huge freq so that all non-NaT dates will be grouped together + tdg = Grouper(key="Date", freq="100YE") + gb = df.groupby(tdg) + + # check that we will go through the singular_series path + # in _wrap_applied_output_series + assert gb.ngroups == 1 + assert gb._selected_obj._get_axis(gb.axis).nlevels == 1 + + # function that returns a Series + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = gb.apply(lambda x: x["Quantity"] * 2) + + dti = Index([Timestamp("2013-12-31")], dtype=df["Date"].dtype, name="Date") + expected = DataFrame( + [[36, 6, 6, 10, 2]], + index=dti, + columns=Index([0, 1, 5, 2, 3], name="Quantity"), + ) + tm.assert_frame_equal(res, expected) + + @pytest.mark.single_cpu + def test_groupby_agg_numba_timegrouper_with_nat( + self, groupby_with_truncated_bingrouper + ): + pytest.importorskip("numba") + + # See discussion in GH#43487 + gb = groupby_with_truncated_bingrouper + + result = gb["Quantity"].aggregate( + lambda values, index: np.nanmean(values), engine="numba" + ) + + expected = gb["Quantity"].aggregate("mean") + tm.assert_series_equal(result, expected) + + result_df = gb[["Quantity"]].aggregate( + lambda values, index: np.nanmean(values), engine="numba" + ) + expected_df = gb[["Quantity"]].aggregate("mean") + tm.assert_frame_equal(result_df, expected_df) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/__init__.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_api.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..1251a6ae97a1cb9304de036dba252de54e7fb10b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_api.py @@ -0,0 +1,86 @@ +""" +Tests for the pseudo-public API implemented in internals/api.py and exposed +in core.internals +""" + +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core import internals +from pandas.core.internals import api + + +def test_internals_api(): + assert internals.make_block is api.make_block + + +def test_namespace(): + # SUBJECT TO CHANGE + + modules = [ + "blocks", + "concat", + "managers", + "construction", + "array_manager", + "base", + "api", + "ops", + ] + expected = [ + "make_block", + "DataManager", + "ArrayManager", + "BlockManager", + "SingleDataManager", + "SingleBlockManager", + "SingleArrayManager", + "concatenate_managers", + ] + + result = [x for x in dir(internals) if not x.startswith("__")] + assert set(result) == set(expected + modules) + + +@pytest.mark.parametrize( + "name", + [ + "NumericBlock", + "ObjectBlock", + "Block", + "ExtensionBlock", + "DatetimeTZBlock", + ], +) +def test_deprecations(name): + # GH#55139 + msg = f"{name} is deprecated.* Use public APIs instead" + with tm.assert_produces_warning(DeprecationWarning, match=msg): + getattr(internals, name) + + if name not in ["NumericBlock", "ObjectBlock"]: + # NumericBlock and ObjectBlock are not in the internals.api namespace + with tm.assert_produces_warning(DeprecationWarning, match=msg): + getattr(api, name) + + +def test_make_block_2d_with_dti(): + # GH#41168 + dti = pd.date_range("2012", periods=3, tz="UTC") + blk = api.make_block(dti, placement=[0]) + + assert blk.shape == (1, 3) + assert blk.values.shape == (1, 3) + + +def test_create_block_manager_from_blocks_deprecated(): + # GH#33892 + # If they must, downstream packages should get this from internals.api, + # not internals. + msg = ( + "create_block_manager_from_blocks is deprecated and will be " + "removed in a future version. Use public APIs instead" + ) + with tm.assert_produces_warning(DeprecationWarning, match=msg): + internals.create_block_manager_from_blocks diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_internals.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_internals.py new file mode 100644 index 0000000000000000000000000000000000000000..30c5d3177c5a569676c20b47e2776f266bb308cc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_internals.py @@ -0,0 +1,1422 @@ +from datetime import ( + date, + datetime, +) +import itertools +import re + +import numpy as np +import pytest + +from pandas._libs.internals import BlockPlacement +from pandas.compat import IS64 +import pandas.util._test_decorators as td + +from pandas.core.dtypes.common import is_scalar + +import pandas as pd +from pandas import ( + Categorical, + DataFrame, + DatetimeIndex, + Index, + IntervalIndex, + Series, + Timedelta, + Timestamp, + period_range, +) +import pandas._testing as tm +import pandas.core.algorithms as algos +from pandas.core.arrays import ( + DatetimeArray, + SparseArray, + TimedeltaArray, +) +from pandas.core.internals import ( + BlockManager, + SingleBlockManager, + make_block, +) +from pandas.core.internals.blocks import ( + ensure_block_shape, + maybe_coerce_values, + new_block, +) + +# this file contains BlockManager specific tests +# TODO(ArrayManager) factor out interleave_dtype tests +pytestmark = td.skip_array_manager_invalid_test + + +@pytest.fixture(params=[new_block, make_block]) +def block_maker(request): + """ + Fixture to test both the internal new_block and pseudo-public make_block. + """ + return request.param + + +@pytest.fixture +def mgr(): + return create_mgr( + "a: f8; b: object; c: f8; d: object; e: f8;" + "f: bool; g: i8; h: complex; i: datetime-1; j: datetime-2;" + "k: M8[ns, US/Eastern]; l: M8[ns, CET];" + ) + + +def assert_block_equal(left, right): + tm.assert_numpy_array_equal(left.values, right.values) + assert left.dtype == right.dtype + assert isinstance(left.mgr_locs, BlockPlacement) + assert isinstance(right.mgr_locs, BlockPlacement) + tm.assert_numpy_array_equal(left.mgr_locs.as_array, right.mgr_locs.as_array) + + +def get_numeric_mat(shape): + arr = np.arange(shape[0]) + return np.lib.stride_tricks.as_strided( + x=arr, shape=shape, strides=(arr.itemsize,) + (0,) * (len(shape) - 1) + ).copy() + + +N = 10 + + +def create_block(typestr, placement, item_shape=None, num_offset=0, maker=new_block): + """ + Supported typestr: + + * float, f8, f4, f2 + * int, i8, i4, i2, i1 + * uint, u8, u4, u2, u1 + * complex, c16, c8 + * bool + * object, string, O + * datetime, dt, M8[ns], M8[ns, tz] + * timedelta, td, m8[ns] + * sparse (SparseArray with fill_value=0.0) + * sparse_na (SparseArray with fill_value=np.nan) + * category, category2 + + """ + placement = BlockPlacement(placement) + num_items = len(placement) + + if item_shape is None: + item_shape = (N,) + + shape = (num_items,) + item_shape + + mat = get_numeric_mat(shape) + + if typestr in ( + "float", + "f8", + "f4", + "f2", + "int", + "i8", + "i4", + "i2", + "i1", + "uint", + "u8", + "u4", + "u2", + "u1", + ): + values = mat.astype(typestr) + num_offset + elif typestr in ("complex", "c16", "c8"): + values = 1.0j * (mat.astype(typestr) + num_offset) + elif typestr in ("object", "string", "O"): + values = np.reshape([f"A{i:d}" for i in mat.ravel() + num_offset], shape) + elif typestr in ("b", "bool"): + values = np.ones(shape, dtype=np.bool_) + elif typestr in ("datetime", "dt", "M8[ns]"): + values = (mat * 1e9).astype("M8[ns]") + elif typestr.startswith("M8[ns"): + # datetime with tz + m = re.search(r"M8\[ns,\s*(\w+\/?\w*)\]", typestr) + assert m is not None, f"incompatible typestr -> {typestr}" + tz = m.groups()[0] + assert num_items == 1, "must have only 1 num items for a tz-aware" + values = DatetimeIndex(np.arange(N) * 10**9, tz=tz)._data + values = ensure_block_shape(values, ndim=len(shape)) + elif typestr in ("timedelta", "td", "m8[ns]"): + values = (mat * 1).astype("m8[ns]") + elif typestr in ("category",): + values = Categorical([1, 1, 2, 2, 3, 3, 3, 3, 4, 4]) + elif typestr in ("category2",): + values = Categorical(["a", "a", "a", "a", "b", "b", "c", "c", "c", "d"]) + elif typestr in ("sparse", "sparse_na"): + if shape[-1] != 10: + # We also are implicitly assuming this in the category cases above + raise NotImplementedError + + assert all(s == 1 for s in shape[:-1]) + if typestr.endswith("_na"): + fill_value = np.nan + else: + fill_value = 0.0 + values = SparseArray( + [fill_value, fill_value, 1, 2, 3, fill_value, 4, 5, fill_value, 6], + fill_value=fill_value, + ) + arr = values.sp_values.view() + arr += num_offset - 1 + else: + raise ValueError(f'Unsupported typestr: "{typestr}"') + + values = maybe_coerce_values(values) + return maker(values, placement=placement, ndim=len(shape)) + + +def create_single_mgr(typestr, num_rows=None): + if num_rows is None: + num_rows = N + + return SingleBlockManager( + create_block(typestr, placement=slice(0, num_rows), item_shape=()), + Index(np.arange(num_rows)), + ) + + +def create_mgr(descr, item_shape=None): + """ + Construct BlockManager from string description. + + String description syntax looks similar to np.matrix initializer. It looks + like this:: + + a,b,c: f8; d,e,f: i8 + + Rules are rather simple: + + * see list of supported datatypes in `create_block` method + * components are semicolon-separated + * each component is `NAME,NAME,NAME: DTYPE_ID` + * whitespace around colons & semicolons are removed + * components with same DTYPE_ID are combined into single block + * to force multiple blocks with same dtype, use '-SUFFIX':: + + 'a:f8-1; b:f8-2; c:f8-foobar' + + """ + if item_shape is None: + item_shape = (N,) + + offset = 0 + mgr_items = [] + block_placements = {} + for d in descr.split(";"): + d = d.strip() + if not len(d): + continue + names, blockstr = d.partition(":")[::2] + blockstr = blockstr.strip() + names = names.strip().split(",") + + mgr_items.extend(names) + placement = list(np.arange(len(names)) + offset) + try: + block_placements[blockstr].extend(placement) + except KeyError: + block_placements[blockstr] = placement + offset += len(names) + + mgr_items = Index(mgr_items) + + blocks = [] + num_offset = 0 + for blockstr, placement in block_placements.items(): + typestr = blockstr.split("-")[0] + blocks.append( + create_block( + typestr, placement, item_shape=item_shape, num_offset=num_offset + ) + ) + num_offset += len(placement) + + sblocks = sorted(blocks, key=lambda b: b.mgr_locs[0]) + return BlockManager( + tuple(sblocks), + [mgr_items] + [Index(np.arange(n)) for n in item_shape], + ) + + +@pytest.fixture +def fblock(): + return create_block("float", [0, 2, 4]) + + +class TestBlock: + def test_constructor(self): + int32block = create_block("i4", [0]) + assert int32block.dtype == np.int32 + + @pytest.mark.parametrize( + "typ, data", + [ + ["float", [0, 2, 4]], + ["complex", [7]], + ["object", [1, 3]], + ["bool", [5]], + ], + ) + def test_pickle(self, typ, data): + blk = create_block(typ, data) + assert_block_equal(tm.round_trip_pickle(blk), blk) + + def test_mgr_locs(self, fblock): + assert isinstance(fblock.mgr_locs, BlockPlacement) + tm.assert_numpy_array_equal( + fblock.mgr_locs.as_array, np.array([0, 2, 4], dtype=np.intp) + ) + + def test_attrs(self, fblock): + assert fblock.shape == fblock.values.shape + assert fblock.dtype == fblock.values.dtype + assert len(fblock) == len(fblock.values) + + def test_copy(self, fblock): + cop = fblock.copy() + assert cop is not fblock + assert_block_equal(fblock, cop) + + def test_delete(self, fblock): + newb = fblock.copy() + locs = newb.mgr_locs + nb = newb.delete(0)[0] + assert newb.mgr_locs is locs + + assert nb is not newb + + tm.assert_numpy_array_equal( + nb.mgr_locs.as_array, np.array([2, 4], dtype=np.intp) + ) + assert not (newb.values[0] == 1).all() + assert (nb.values[0] == 1).all() + + newb = fblock.copy() + locs = newb.mgr_locs + nb = newb.delete(1) + assert len(nb) == 2 + assert newb.mgr_locs is locs + + tm.assert_numpy_array_equal( + nb[0].mgr_locs.as_array, np.array([0], dtype=np.intp) + ) + tm.assert_numpy_array_equal( + nb[1].mgr_locs.as_array, np.array([4], dtype=np.intp) + ) + assert not (newb.values[1] == 2).all() + assert (nb[1].values[0] == 2).all() + + newb = fblock.copy() + nb = newb.delete(2) + assert len(nb) == 1 + tm.assert_numpy_array_equal( + nb[0].mgr_locs.as_array, np.array([0, 2], dtype=np.intp) + ) + assert (nb[0].values[1] == 1).all() + + newb = fblock.copy() + + with pytest.raises(IndexError, match=None): + newb.delete(3) + + def test_delete_datetimelike(self): + # dont use np.delete on values, as that will coerce from DTA/TDA to ndarray + arr = np.arange(20, dtype="i8").reshape(5, 4).view("m8[ns]") + df = DataFrame(arr) + blk = df._mgr.blocks[0] + assert isinstance(blk.values, TimedeltaArray) + + nb = blk.delete(1) + assert len(nb) == 2 + assert isinstance(nb[0].values, TimedeltaArray) + assert isinstance(nb[1].values, TimedeltaArray) + + df = DataFrame(arr.view("M8[ns]")) + blk = df._mgr.blocks[0] + assert isinstance(blk.values, DatetimeArray) + + nb = blk.delete([1, 3]) + assert len(nb) == 2 + assert isinstance(nb[0].values, DatetimeArray) + assert isinstance(nb[1].values, DatetimeArray) + + def test_split(self): + # GH#37799 + values = np.random.default_rng(2).standard_normal((3, 4)) + blk = new_block(values, placement=BlockPlacement([3, 1, 6]), ndim=2) + result = blk._split() + + # check that we get views, not copies + values[:] = -9999 + assert (blk.values == -9999).all() + + assert len(result) == 3 + expected = [ + new_block(values[[0]], placement=BlockPlacement([3]), ndim=2), + new_block(values[[1]], placement=BlockPlacement([1]), ndim=2), + new_block(values[[2]], placement=BlockPlacement([6]), ndim=2), + ] + for res, exp in zip(result, expected): + assert_block_equal(res, exp) + + +class TestBlockManager: + def test_attrs(self): + mgr = create_mgr("a,b,c: f8-1; d,e,f: f8-2") + assert mgr.nblocks == 2 + assert len(mgr) == 6 + + def test_duplicate_ref_loc_failure(self): + tmp_mgr = create_mgr("a:bool; a: f8") + + axes, blocks = tmp_mgr.axes, tmp_mgr.blocks + + blocks[0].mgr_locs = BlockPlacement(np.array([0])) + blocks[1].mgr_locs = BlockPlacement(np.array([0])) + + # test trying to create block manager with overlapping ref locs + + msg = "Gaps in blk ref_locs" + + with pytest.raises(AssertionError, match=msg): + mgr = BlockManager(blocks, axes) + mgr._rebuild_blknos_and_blklocs() + + blocks[0].mgr_locs = BlockPlacement(np.array([0])) + blocks[1].mgr_locs = BlockPlacement(np.array([1])) + mgr = BlockManager(blocks, axes) + mgr.iget(1) + + def test_pickle(self, mgr): + mgr2 = tm.round_trip_pickle(mgr) + tm.assert_frame_equal( + DataFrame._from_mgr(mgr, axes=mgr.axes), + DataFrame._from_mgr(mgr2, axes=mgr2.axes), + ) + + # GH2431 + assert hasattr(mgr2, "_is_consolidated") + assert hasattr(mgr2, "_known_consolidated") + + # reset to False on load + assert not mgr2._is_consolidated + assert not mgr2._known_consolidated + + @pytest.mark.parametrize("mgr_string", ["a,a,a:f8", "a: f8; a: i8"]) + def test_non_unique_pickle(self, mgr_string): + mgr = create_mgr(mgr_string) + mgr2 = tm.round_trip_pickle(mgr) + tm.assert_frame_equal( + DataFrame._from_mgr(mgr, axes=mgr.axes), + DataFrame._from_mgr(mgr2, axes=mgr2.axes), + ) + + def test_categorical_block_pickle(self): + mgr = create_mgr("a: category") + mgr2 = tm.round_trip_pickle(mgr) + tm.assert_frame_equal( + DataFrame._from_mgr(mgr, axes=mgr.axes), + DataFrame._from_mgr(mgr2, axes=mgr2.axes), + ) + + smgr = create_single_mgr("category") + smgr2 = tm.round_trip_pickle(smgr) + tm.assert_series_equal( + Series()._constructor_from_mgr(smgr, axes=smgr.axes), + Series()._constructor_from_mgr(smgr2, axes=smgr2.axes), + ) + + def test_iget(self): + cols = Index(list("abc")) + values = np.random.default_rng(2).random((3, 3)) + block = new_block( + values=values.copy(), + placement=BlockPlacement(np.arange(3, dtype=np.intp)), + ndim=values.ndim, + ) + mgr = BlockManager(blocks=(block,), axes=[cols, Index(np.arange(3))]) + + tm.assert_almost_equal(mgr.iget(0).internal_values(), values[0]) + tm.assert_almost_equal(mgr.iget(1).internal_values(), values[1]) + tm.assert_almost_equal(mgr.iget(2).internal_values(), values[2]) + + def test_set(self): + mgr = create_mgr("a,b,c: int", item_shape=(3,)) + + mgr.insert(len(mgr.items), "d", np.array(["foo"] * 3)) + mgr.iset(1, np.array(["bar"] * 3)) + tm.assert_numpy_array_equal(mgr.iget(0).internal_values(), np.array([0] * 3)) + tm.assert_numpy_array_equal( + mgr.iget(1).internal_values(), np.array(["bar"] * 3, dtype=np.object_) + ) + tm.assert_numpy_array_equal(mgr.iget(2).internal_values(), np.array([2] * 3)) + tm.assert_numpy_array_equal( + mgr.iget(3).internal_values(), np.array(["foo"] * 3, dtype=np.object_) + ) + + def test_set_change_dtype(self, mgr): + mgr.insert(len(mgr.items), "baz", np.zeros(N, dtype=bool)) + + mgr.iset(mgr.items.get_loc("baz"), np.repeat("foo", N)) + idx = mgr.items.get_loc("baz") + assert mgr.iget(idx).dtype == np.object_ + + mgr2 = mgr.consolidate() + mgr2.iset(mgr2.items.get_loc("baz"), np.repeat("foo", N)) + idx = mgr2.items.get_loc("baz") + assert mgr2.iget(idx).dtype == np.object_ + + mgr2.insert( + len(mgr2.items), + "quux", + np.random.default_rng(2).standard_normal(N).astype(int), + ) + idx = mgr2.items.get_loc("quux") + assert mgr2.iget(idx).dtype == np.dtype(int) + + mgr2.iset( + mgr2.items.get_loc("quux"), np.random.default_rng(2).standard_normal(N) + ) + assert mgr2.iget(idx).dtype == np.float64 + + def test_copy(self, mgr): + cp = mgr.copy(deep=False) + for blk, cp_blk in zip(mgr.blocks, cp.blocks): + # view assertion + tm.assert_equal(cp_blk.values, blk.values) + if isinstance(blk.values, np.ndarray): + assert cp_blk.values.base is blk.values.base + else: + # DatetimeTZBlock has DatetimeIndex values + assert cp_blk.values._ndarray.base is blk.values._ndarray.base + + # copy(deep=True) consolidates, so the block-wise assertions will + # fail is mgr is not consolidated + mgr._consolidate_inplace() + cp = mgr.copy(deep=True) + for blk, cp_blk in zip(mgr.blocks, cp.blocks): + bvals = blk.values + cpvals = cp_blk.values + + tm.assert_equal(cpvals, bvals) + + if isinstance(cpvals, np.ndarray): + lbase = cpvals.base + rbase = bvals.base + else: + lbase = cpvals._ndarray.base + rbase = bvals._ndarray.base + + # copy assertion we either have a None for a base or in case of + # some blocks it is an array (e.g. datetimetz), but was copied + if isinstance(cpvals, DatetimeArray): + assert (lbase is None and rbase is None) or (lbase is not rbase) + elif not isinstance(cpvals, np.ndarray): + assert lbase is not rbase + else: + assert lbase is None and rbase is None + + def test_sparse(self): + mgr = create_mgr("a: sparse-1; b: sparse-2") + assert mgr.as_array().dtype == np.float64 + + def test_sparse_mixed(self): + mgr = create_mgr("a: sparse-1; b: sparse-2; c: f8") + assert len(mgr.blocks) == 3 + assert isinstance(mgr, BlockManager) + + @pytest.mark.parametrize( + "mgr_string, dtype", + [("c: f4; d: f2", np.float32), ("c: f4; d: f2; e: f8", np.float64)], + ) + def test_as_array_float(self, mgr_string, dtype): + mgr = create_mgr(mgr_string) + assert mgr.as_array().dtype == dtype + + @pytest.mark.parametrize( + "mgr_string, dtype", + [ + ("a: bool-1; b: bool-2", np.bool_), + ("a: i8-1; b: i8-2; c: i4; d: i2; e: u1", np.int64), + ("c: i4; d: i2; e: u1", np.int32), + ], + ) + def test_as_array_int_bool(self, mgr_string, dtype): + mgr = create_mgr(mgr_string) + assert mgr.as_array().dtype == dtype + + def test_as_array_datetime(self): + mgr = create_mgr("h: datetime-1; g: datetime-2") + assert mgr.as_array().dtype == "M8[ns]" + + def test_as_array_datetime_tz(self): + mgr = create_mgr("h: M8[ns, US/Eastern]; g: M8[ns, CET]") + assert mgr.iget(0).dtype == "datetime64[ns, US/Eastern]" + assert mgr.iget(1).dtype == "datetime64[ns, CET]" + assert mgr.as_array().dtype == "object" + + @pytest.mark.parametrize("t", ["float16", "float32", "float64", "int32", "int64"]) + def test_astype(self, t): + # coerce all + mgr = create_mgr("c: f4; d: f2; e: f8") + + t = np.dtype(t) + tmgr = mgr.astype(t) + assert tmgr.iget(0).dtype.type == t + assert tmgr.iget(1).dtype.type == t + assert tmgr.iget(2).dtype.type == t + + # mixed + mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8") + + t = np.dtype(t) + tmgr = mgr.astype(t, errors="ignore") + assert tmgr.iget(2).dtype.type == t + assert tmgr.iget(4).dtype.type == t + assert tmgr.iget(5).dtype.type == t + assert tmgr.iget(6).dtype.type == t + + assert tmgr.iget(0).dtype.type == np.object_ + assert tmgr.iget(1).dtype.type == np.object_ + if t != np.int64: + assert tmgr.iget(3).dtype.type == np.datetime64 + else: + assert tmgr.iget(3).dtype.type == t + + def test_convert(self, using_infer_string): + def _compare(old_mgr, new_mgr): + """compare the blocks, numeric compare ==, object don't""" + old_blocks = set(old_mgr.blocks) + new_blocks = set(new_mgr.blocks) + assert len(old_blocks) == len(new_blocks) + + # compare non-numeric + for b in old_blocks: + found = False + for nb in new_blocks: + if (b.values == nb.values).all(): + found = True + break + assert found + + for b in new_blocks: + found = False + for ob in old_blocks: + if (b.values == ob.values).all(): + found = True + break + assert found + + # noops + mgr = create_mgr("f: i8; g: f8") + new_mgr = mgr.convert(copy=True) + _compare(mgr, new_mgr) + + # convert + mgr = create_mgr("a,b,foo: object; f: i8; g: f8") + mgr.iset(0, np.array(["1"] * N, dtype=np.object_)) + mgr.iset(1, np.array(["2."] * N, dtype=np.object_)) + mgr.iset(2, np.array(["foo."] * N, dtype=np.object_)) + new_mgr = mgr.convert(copy=True) + dtype = "str" if using_infer_string else np.object_ + assert new_mgr.iget(0).dtype == dtype + assert new_mgr.iget(1).dtype == dtype + assert new_mgr.iget(2).dtype == dtype + assert new_mgr.iget(3).dtype == np.int64 + assert new_mgr.iget(4).dtype == np.float64 + + mgr = create_mgr( + "a,b,foo: object; f: i4; bool: bool; dt: datetime; i: i8; g: f8; h: f2" + ) + mgr.iset(0, np.array(["1"] * N, dtype=np.object_)) + mgr.iset(1, np.array(["2."] * N, dtype=np.object_)) + mgr.iset(2, np.array(["foo."] * N, dtype=np.object_)) + new_mgr = mgr.convert(copy=True) + assert new_mgr.iget(0).dtype == dtype + assert new_mgr.iget(1).dtype == dtype + assert new_mgr.iget(2).dtype == dtype + assert new_mgr.iget(3).dtype == np.int32 + assert new_mgr.iget(4).dtype == np.bool_ + assert new_mgr.iget(5).dtype.type, np.datetime64 + assert new_mgr.iget(6).dtype == np.int64 + assert new_mgr.iget(7).dtype == np.float64 + assert new_mgr.iget(8).dtype == np.float16 + + def test_interleave(self): + # self + for dtype in ["f8", "i8", "object", "bool", "complex", "M8[ns]", "m8[ns]"]: + mgr = create_mgr(f"a: {dtype}") + assert mgr.as_array().dtype == dtype + mgr = create_mgr(f"a: {dtype}; b: {dtype}") + assert mgr.as_array().dtype == dtype + + @pytest.mark.parametrize( + "mgr_string, dtype", + [ + ("a: category", "i8"), + ("a: category; b: category", "i8"), + ("a: category; b: category2", "object"), + ("a: category2", "object"), + ("a: category2; b: category2", "object"), + ("a: f8", "f8"), + ("a: f8; b: i8", "f8"), + ("a: f4; b: i8", "f8"), + ("a: f4; b: i8; d: object", "object"), + ("a: bool; b: i8", "object"), + ("a: complex", "complex"), + ("a: f8; b: category", "object"), + ("a: M8[ns]; b: category", "object"), + ("a: M8[ns]; b: bool", "object"), + ("a: M8[ns]; b: i8", "object"), + ("a: m8[ns]; b: bool", "object"), + ("a: m8[ns]; b: i8", "object"), + ("a: M8[ns]; b: m8[ns]", "object"), + ], + ) + def test_interleave_dtype(self, mgr_string, dtype): + # will be converted according the actual dtype of the underlying + mgr = create_mgr("a: category") + assert mgr.as_array().dtype == "i8" + mgr = create_mgr("a: category; b: category2") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: category2") + assert mgr.as_array().dtype == "object" + + # combinations + mgr = create_mgr("a: f8") + assert mgr.as_array().dtype == "f8" + mgr = create_mgr("a: f8; b: i8") + assert mgr.as_array().dtype == "f8" + mgr = create_mgr("a: f4; b: i8") + assert mgr.as_array().dtype == "f8" + mgr = create_mgr("a: f4; b: i8; d: object") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: bool; b: i8") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: complex") + assert mgr.as_array().dtype == "complex" + mgr = create_mgr("a: f8; b: category") + assert mgr.as_array().dtype == "f8" + mgr = create_mgr("a: M8[ns]; b: category") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: M8[ns]; b: bool") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: M8[ns]; b: i8") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: m8[ns]; b: bool") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: m8[ns]; b: i8") + assert mgr.as_array().dtype == "object" + mgr = create_mgr("a: M8[ns]; b: m8[ns]") + assert mgr.as_array().dtype == "object" + + def test_consolidate_ordering_issues(self, mgr): + mgr.iset(mgr.items.get_loc("f"), np.random.default_rng(2).standard_normal(N)) + mgr.iset(mgr.items.get_loc("d"), np.random.default_rng(2).standard_normal(N)) + mgr.iset(mgr.items.get_loc("b"), np.random.default_rng(2).standard_normal(N)) + mgr.iset(mgr.items.get_loc("g"), np.random.default_rng(2).standard_normal(N)) + mgr.iset(mgr.items.get_loc("h"), np.random.default_rng(2).standard_normal(N)) + + # we have datetime/tz blocks in mgr + cons = mgr.consolidate() + assert cons.nblocks == 4 + cons = mgr.consolidate().get_numeric_data() + assert cons.nblocks == 1 + assert isinstance(cons.blocks[0].mgr_locs, BlockPlacement) + tm.assert_numpy_array_equal( + cons.blocks[0].mgr_locs.as_array, np.arange(len(cons.items), dtype=np.intp) + ) + + def test_reindex_items(self): + # mgr is not consolidated, f8 & f8-2 blocks + mgr = create_mgr("a: f8; b: i8; c: f8; d: i8; e: f8; f: bool; g: f8-2") + + reindexed = mgr.reindex_axis(["g", "c", "a", "d"], axis=0) + # reindex_axis does not consolidate_inplace, as that risks failing to + # invalidate _item_cache + assert not reindexed.is_consolidated() + + tm.assert_index_equal(reindexed.items, Index(["g", "c", "a", "d"])) + tm.assert_almost_equal( + mgr.iget(6).internal_values(), reindexed.iget(0).internal_values() + ) + tm.assert_almost_equal( + mgr.iget(2).internal_values(), reindexed.iget(1).internal_values() + ) + tm.assert_almost_equal( + mgr.iget(0).internal_values(), reindexed.iget(2).internal_values() + ) + tm.assert_almost_equal( + mgr.iget(3).internal_values(), reindexed.iget(3).internal_values() + ) + + def test_get_numeric_data(self, using_copy_on_write): + mgr = create_mgr( + "int: int; float: float; complex: complex;" + "str: object; bool: bool; obj: object; dt: datetime", + item_shape=(3,), + ) + mgr.iset(5, np.array([1, 2, 3], dtype=np.object_)) + + numeric = mgr.get_numeric_data() + tm.assert_index_equal(numeric.items, Index(["int", "float", "complex", "bool"])) + tm.assert_almost_equal( + mgr.iget(mgr.items.get_loc("float")).internal_values(), + numeric.iget(numeric.items.get_loc("float")).internal_values(), + ) + + # Check sharing + numeric.iset( + numeric.items.get_loc("float"), + np.array([100.0, 200.0, 300.0]), + inplace=True, + ) + if using_copy_on_write: + tm.assert_almost_equal( + mgr.iget(mgr.items.get_loc("float")).internal_values(), + np.array([1.0, 1.0, 1.0]), + ) + else: + tm.assert_almost_equal( + mgr.iget(mgr.items.get_loc("float")).internal_values(), + np.array([100.0, 200.0, 300.0]), + ) + + def test_get_bool_data(self, using_copy_on_write): + mgr = create_mgr( + "int: int; float: float; complex: complex;" + "str: object; bool: bool; obj: object; dt: datetime", + item_shape=(3,), + ) + mgr.iset(6, np.array([True, False, True], dtype=np.object_)) + + bools = mgr.get_bool_data() + tm.assert_index_equal(bools.items, Index(["bool"])) + tm.assert_almost_equal( + mgr.iget(mgr.items.get_loc("bool")).internal_values(), + bools.iget(bools.items.get_loc("bool")).internal_values(), + ) + + bools.iset(0, np.array([True, False, True]), inplace=True) + if using_copy_on_write: + tm.assert_numpy_array_equal( + mgr.iget(mgr.items.get_loc("bool")).internal_values(), + np.array([True, True, True]), + ) + else: + tm.assert_numpy_array_equal( + mgr.iget(mgr.items.get_loc("bool")).internal_values(), + np.array([True, False, True]), + ) + + def test_unicode_repr_doesnt_raise(self): + repr(create_mgr("b,\u05d0: object")) + + @pytest.mark.parametrize( + "mgr_string", ["a,b,c: i8-1; d,e,f: i8-2", "a,a,a: i8-1; b,b,b: i8-2"] + ) + def test_equals(self, mgr_string): + # unique items + bm1 = create_mgr(mgr_string) + bm2 = BlockManager(bm1.blocks[::-1], bm1.axes) + assert bm1.equals(bm2) + + @pytest.mark.parametrize( + "mgr_string", + [ + "a:i8;b:f8", # basic case + "a:i8;b:f8;c:c8;d:b", # many types + "a:i8;e:dt;f:td;g:string", # more types + "a:i8;b:category;c:category2", # categories + "c:sparse;d:sparse_na;b:f8", # sparse + ], + ) + def test_equals_block_order_different_dtypes(self, mgr_string): + # GH 9330 + bm = create_mgr(mgr_string) + block_perms = itertools.permutations(bm.blocks) + for bm_perm in block_perms: + bm_this = BlockManager(tuple(bm_perm), bm.axes) + assert bm.equals(bm_this) + assert bm_this.equals(bm) + + def test_single_mgr_ctor(self): + mgr = create_single_mgr("f8", num_rows=5) + assert mgr.external_values().tolist() == [0.0, 1.0, 2.0, 3.0, 4.0] + + @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) + def test_validate_bool_args(self, value): + bm1 = create_mgr("a,b,c: i8-1; d,e,f: i8-2") + + msg = ( + 'For argument "inplace" expected type bool, ' + f"received type {type(value).__name__}." + ) + with pytest.raises(ValueError, match=msg): + bm1.replace_list([1], [2], inplace=value) + + def test_iset_split_block(self): + bm = create_mgr("a,b,c: i8; d: f8") + bm._iset_split_block(0, np.array([0])) + tm.assert_numpy_array_equal( + bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32") + ) + # First indexer currently does not have a block associated with it in case + tm.assert_numpy_array_equal( + bm.blknos, np.array([0, 0, 0, 1], dtype="int64" if IS64 else "int32") + ) + assert len(bm.blocks) == 2 + + def test_iset_split_block_values(self): + bm = create_mgr("a,b,c: i8; d: f8") + bm._iset_split_block(0, np.array([0]), np.array([list(range(10))])) + tm.assert_numpy_array_equal( + bm.blklocs, np.array([0, 0, 1, 0], dtype="int64" if IS64 else "int32") + ) + # First indexer currently does not have a block associated with it in case + tm.assert_numpy_array_equal( + bm.blknos, np.array([0, 2, 2, 1], dtype="int64" if IS64 else "int32") + ) + assert len(bm.blocks) == 3 + + +def _as_array(mgr): + if mgr.ndim == 1: + return mgr.external_values() + return mgr.as_array().T + + +class TestIndexing: + # Nosetests-style data-driven tests. + # + # This test applies different indexing routines to block managers and + # compares the outcome to the result of same operations on np.ndarray. + # + # NOTE: sparse (SparseBlock with fill_value != np.nan) fail a lot of tests + # and are disabled. + + MANAGERS = [ + create_single_mgr("f8", N), + create_single_mgr("i8", N), + # 2-dim + create_mgr("a,b,c,d,e,f: f8", item_shape=(N,)), + create_mgr("a,b,c,d,e,f: i8", item_shape=(N,)), + create_mgr("a,b: f8; c,d: i8; e,f: string", item_shape=(N,)), + create_mgr("a,b: f8; c,d: i8; e,f: f8", item_shape=(N,)), + ] + + @pytest.mark.parametrize("mgr", MANAGERS) + def test_get_slice(self, mgr): + def assert_slice_ok(mgr, axis, slobj): + mat = _as_array(mgr) + + # we maybe using an ndarray to test slicing and + # might not be the full length of the axis + if isinstance(slobj, np.ndarray): + ax = mgr.axes[axis] + if len(ax) and len(slobj) and len(slobj) != len(ax): + slobj = np.concatenate( + [slobj, np.zeros(len(ax) - len(slobj), dtype=bool)] + ) + + if isinstance(slobj, slice): + sliced = mgr.get_slice(slobj, axis=axis) + elif ( + mgr.ndim == 1 + and axis == 0 + and isinstance(slobj, np.ndarray) + and slobj.dtype == bool + ): + sliced = mgr.get_rows_with_mask(slobj) + else: + # BlockManager doesn't support non-slice, SingleBlockManager + # doesn't support axis > 0 + raise TypeError(slobj) + + mat_slobj = (slice(None),) * axis + (slobj,) + tm.assert_numpy_array_equal( + mat[mat_slobj], _as_array(sliced), check_dtype=False + ) + tm.assert_index_equal(mgr.axes[axis][slobj], sliced.axes[axis]) + + assert mgr.ndim <= 2, mgr.ndim + for ax in range(mgr.ndim): + # slice + assert_slice_ok(mgr, ax, slice(None)) + assert_slice_ok(mgr, ax, slice(3)) + assert_slice_ok(mgr, ax, slice(100)) + assert_slice_ok(mgr, ax, slice(1, 4)) + assert_slice_ok(mgr, ax, slice(3, 0, -2)) + + if mgr.ndim < 2: + # 2D only support slice objects + + # boolean mask + assert_slice_ok(mgr, ax, np.ones(mgr.shape[ax], dtype=np.bool_)) + assert_slice_ok(mgr, ax, np.zeros(mgr.shape[ax], dtype=np.bool_)) + + if mgr.shape[ax] >= 3: + assert_slice_ok(mgr, ax, np.arange(mgr.shape[ax]) % 3 == 0) + assert_slice_ok( + mgr, ax, np.array([True, True, False], dtype=np.bool_) + ) + + @pytest.mark.parametrize("mgr", MANAGERS) + def test_take(self, mgr): + def assert_take_ok(mgr, axis, indexer): + mat = _as_array(mgr) + taken = mgr.take(indexer, axis) + tm.assert_numpy_array_equal( + np.take(mat, indexer, axis), _as_array(taken), check_dtype=False + ) + tm.assert_index_equal(mgr.axes[axis].take(indexer), taken.axes[axis]) + + for ax in range(mgr.ndim): + # take/fancy indexer + assert_take_ok(mgr, ax, indexer=np.array([], dtype=np.intp)) + assert_take_ok(mgr, ax, indexer=np.array([0, 0, 0], dtype=np.intp)) + assert_take_ok( + mgr, ax, indexer=np.array(list(range(mgr.shape[ax])), dtype=np.intp) + ) + + if mgr.shape[ax] >= 3: + assert_take_ok(mgr, ax, indexer=np.array([0, 1, 2], dtype=np.intp)) + assert_take_ok(mgr, ax, indexer=np.array([-1, -2, -3], dtype=np.intp)) + + @pytest.mark.parametrize("mgr", MANAGERS) + @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0]) + def test_reindex_axis(self, fill_value, mgr): + def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value): + mat = _as_array(mgr) + indexer = mgr.axes[axis].get_indexer_for(new_labels) + + reindexed = mgr.reindex_axis(new_labels, axis, fill_value=fill_value) + tm.assert_numpy_array_equal( + algos.take_nd(mat, indexer, axis, fill_value=fill_value), + _as_array(reindexed), + check_dtype=False, + ) + tm.assert_index_equal(reindexed.axes[axis], new_labels) + + for ax in range(mgr.ndim): + assert_reindex_axis_is_ok(mgr, ax, Index([]), fill_value) + assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax], fill_value) + assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][[0, 0, 0]], fill_value) + assert_reindex_axis_is_ok(mgr, ax, Index(["foo", "bar", "baz"]), fill_value) + assert_reindex_axis_is_ok( + mgr, ax, Index(["foo", mgr.axes[ax][0], "baz"]), fill_value + ) + + if mgr.shape[ax] >= 3: + assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][:-3], fill_value) + assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][-3::-1], fill_value) + assert_reindex_axis_is_ok( + mgr, ax, mgr.axes[ax][[0, 1, 2, 0, 1, 2]], fill_value + ) + + @pytest.mark.parametrize("mgr", MANAGERS) + @pytest.mark.parametrize("fill_value", [None, np.nan, 100.0]) + def test_reindex_indexer(self, fill_value, mgr): + def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value): + mat = _as_array(mgr) + reindexed_mat = algos.take_nd(mat, indexer, axis, fill_value=fill_value) + reindexed = mgr.reindex_indexer( + new_labels, indexer, axis, fill_value=fill_value + ) + tm.assert_numpy_array_equal( + reindexed_mat, _as_array(reindexed), check_dtype=False + ) + tm.assert_index_equal(reindexed.axes[axis], new_labels) + + for ax in range(mgr.ndim): + assert_reindex_indexer_is_ok( + mgr, ax, Index([]), np.array([], dtype=np.intp), fill_value + ) + assert_reindex_indexer_is_ok( + mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax]), fill_value + ) + assert_reindex_indexer_is_ok( + mgr, + ax, + Index(["foo"] * mgr.shape[ax]), + np.arange(mgr.shape[ax]), + fill_value, + ) + assert_reindex_indexer_is_ok( + mgr, ax, mgr.axes[ax][::-1], np.arange(mgr.shape[ax]), fill_value + ) + assert_reindex_indexer_is_ok( + mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax])[::-1], fill_value + ) + assert_reindex_indexer_is_ok( + mgr, ax, Index(["foo", "bar", "baz"]), np.array([0, 0, 0]), fill_value + ) + assert_reindex_indexer_is_ok( + mgr, ax, Index(["foo", "bar", "baz"]), np.array([-1, 0, -1]), fill_value + ) + assert_reindex_indexer_is_ok( + mgr, + ax, + Index(["foo", mgr.axes[ax][0], "baz"]), + np.array([-1, -1, -1]), + fill_value, + ) + + if mgr.shape[ax] >= 3: + assert_reindex_indexer_is_ok( + mgr, + ax, + Index(["foo", "bar", "baz"]), + np.array([0, 1, 2]), + fill_value, + ) + + +class TestBlockPlacement: + @pytest.mark.parametrize( + "slc, expected", + [ + (slice(0, 4), 4), + (slice(0, 4, 2), 2), + (slice(0, 3, 2), 2), + (slice(0, 1, 2), 1), + (slice(1, 0, -1), 1), + ], + ) + def test_slice_len(self, slc, expected): + assert len(BlockPlacement(slc)) == expected + + @pytest.mark.parametrize("slc", [slice(1, 1, 0), slice(1, 2, 0)]) + def test_zero_step_raises(self, slc): + msg = "slice step cannot be zero" + with pytest.raises(ValueError, match=msg): + BlockPlacement(slc) + + def test_slice_canonize_negative_stop(self): + # GH#37524 negative stop is OK with negative step and positive start + slc = slice(3, -1, -2) + + bp = BlockPlacement(slc) + assert bp.indexer == slice(3, None, -2) + + @pytest.mark.parametrize( + "slc", + [ + slice(None, None), + slice(10, None), + slice(None, None, -1), + slice(None, 10, -1), + # These are "unbounded" because negative index will + # change depending on container shape. + slice(-1, None), + slice(None, -1), + slice(-1, -1), + slice(-1, None, -1), + slice(None, -1, -1), + slice(-1, -1, -1), + ], + ) + def test_unbounded_slice_raises(self, slc): + msg = "unbounded slice" + with pytest.raises(ValueError, match=msg): + BlockPlacement(slc) + + @pytest.mark.parametrize( + "slc", + [ + slice(0, 0), + slice(100, 0), + slice(100, 100), + slice(100, 100, -1), + slice(0, 100, -1), + ], + ) + def test_not_slice_like_slices(self, slc): + assert not BlockPlacement(slc).is_slice_like + + @pytest.mark.parametrize( + "arr, slc", + [ + ([0], slice(0, 1, 1)), + ([100], slice(100, 101, 1)), + ([0, 1, 2], slice(0, 3, 1)), + ([0, 5, 10], slice(0, 15, 5)), + ([0, 100], slice(0, 200, 100)), + ([2, 1], slice(2, 0, -1)), + ], + ) + def test_array_to_slice_conversion(self, arr, slc): + assert BlockPlacement(arr).as_slice == slc + + @pytest.mark.parametrize( + "arr", + [ + [], + [-1], + [-1, -2, -3], + [-10], + [-1], + [-1, 0, 1, 2], + [-2, 0, 2, 4], + [1, 0, -1], + [1, 1, 1], + ], + ) + def test_not_slice_like_arrays(self, arr): + assert not BlockPlacement(arr).is_slice_like + + @pytest.mark.parametrize( + "slc, expected", + [(slice(0, 3), [0, 1, 2]), (slice(0, 0), []), (slice(3, 0), [])], + ) + def test_slice_iter(self, slc, expected): + assert list(BlockPlacement(slc)) == expected + + @pytest.mark.parametrize( + "slc, arr", + [ + (slice(0, 3), [0, 1, 2]), + (slice(0, 0), []), + (slice(3, 0), []), + (slice(3, 0, -1), [3, 2, 1]), + ], + ) + def test_slice_to_array_conversion(self, slc, arr): + tm.assert_numpy_array_equal( + BlockPlacement(slc).as_array, np.asarray(arr, dtype=np.intp) + ) + + def test_blockplacement_add(self): + bpl = BlockPlacement(slice(0, 5)) + assert bpl.add(1).as_slice == slice(1, 6, 1) + assert bpl.add(np.arange(5)).as_slice == slice(0, 10, 2) + assert list(bpl.add(np.arange(5, 0, -1))) == [5, 5, 5, 5, 5] + + @pytest.mark.parametrize( + "val, inc, expected", + [ + (slice(0, 0), 0, []), + (slice(1, 4), 0, [1, 2, 3]), + (slice(3, 0, -1), 0, [3, 2, 1]), + ([1, 2, 4], 0, [1, 2, 4]), + (slice(0, 0), 10, []), + (slice(1, 4), 10, [11, 12, 13]), + (slice(3, 0, -1), 10, [13, 12, 11]), + ([1, 2, 4], 10, [11, 12, 14]), + (slice(0, 0), -1, []), + (slice(1, 4), -1, [0, 1, 2]), + ([1, 2, 4], -1, [0, 1, 3]), + ], + ) + def test_blockplacement_add_int(self, val, inc, expected): + assert list(BlockPlacement(val).add(inc)) == expected + + @pytest.mark.parametrize("val", [slice(1, 4), [1, 2, 4]]) + def test_blockplacement_add_int_raises(self, val): + msg = "iadd causes length change" + with pytest.raises(ValueError, match=msg): + BlockPlacement(val).add(-10) + + +class TestCanHoldElement: + @pytest.fixture( + params=[ + lambda x: x, + lambda x: x.to_series(), + lambda x: x._data, + lambda x: list(x), + lambda x: x.astype(object), + lambda x: np.asarray(x), + lambda x: x[0], + lambda x: x[:0], + ] + ) + def element(self, request): + """ + Functions that take an Index and return an element that should have + blk._can_hold_element(element) for a Block with this index's dtype. + """ + return request.param + + def test_datetime_block_can_hold_element(self): + block = create_block("datetime", [0]) + + assert block._can_hold_element([]) + + # We will check that block._can_hold_element iff arr.__setitem__ works + arr = pd.array(block.values.ravel()) + + # coerce None + assert block._can_hold_element(None) + arr[0] = None + assert arr[0] is pd.NaT + + # coerce different types of datetime objects + vals = [np.datetime64("2010-10-10"), datetime(2010, 10, 10)] + for val in vals: + assert block._can_hold_element(val) + arr[0] = val + + val = date(2010, 10, 10) + assert not block._can_hold_element(val) + + msg = ( + "value should be a 'Timestamp', 'NaT', " + "or array of those. Got 'date' instead." + ) + with pytest.raises(TypeError, match=msg): + arr[0] = val + + @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) + def test_interval_can_hold_element_emptylist(self, dtype, element): + arr = np.array([1, 3, 4], dtype=dtype) + ii = IntervalIndex.from_breaks(arr) + blk = new_block(ii._data, BlockPlacement([1]), ndim=2) + + assert blk._can_hold_element([]) + # TODO: check this holds for all blocks + + @pytest.mark.parametrize("dtype", [np.int64, np.uint64, np.float64]) + def test_interval_can_hold_element(self, dtype, element): + arr = np.array([1, 3, 4, 9], dtype=dtype) + ii = IntervalIndex.from_breaks(arr) + blk = new_block(ii._data, BlockPlacement([1]), ndim=2) + + elem = element(ii) + self.check_series_setitem(elem, ii, True) + assert blk._can_hold_element(elem) + + # Careful: to get the expected Series-inplace behavior we need + # `elem` to not have the same length as `arr` + ii2 = IntervalIndex.from_breaks(arr[:-1], closed="neither") + elem = element(ii2) + with tm.assert_produces_warning(FutureWarning): + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + ii3 = IntervalIndex.from_breaks([Timestamp(1), Timestamp(3), Timestamp(4)]) + elem = element(ii3) + with tm.assert_produces_warning(FutureWarning): + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + ii4 = IntervalIndex.from_breaks([Timedelta(1), Timedelta(3), Timedelta(4)]) + elem = element(ii4) + with tm.assert_produces_warning(FutureWarning): + self.check_series_setitem(elem, ii, False) + assert not blk._can_hold_element(elem) + + def test_period_can_hold_element_emptylist(self): + pi = period_range("2016", periods=3, freq="Y") + blk = new_block(pi._data.reshape(1, 3), BlockPlacement([1]), ndim=2) + + assert blk._can_hold_element([]) + + def test_period_can_hold_element(self, element): + pi = period_range("2016", periods=3, freq="Y") + + elem = element(pi) + self.check_series_setitem(elem, pi, True) + + # Careful: to get the expected Series-inplace behavior we need + # `elem` to not have the same length as `arr` + pi2 = pi.asfreq("D")[:-1] + elem = element(pi2) + with tm.assert_produces_warning(FutureWarning): + self.check_series_setitem(elem, pi, False) + + dti = pi.to_timestamp("s")[:-1] + elem = element(dti) + with tm.assert_produces_warning(FutureWarning): + self.check_series_setitem(elem, pi, False) + + def check_can_hold_element(self, obj, elem, inplace: bool): + blk = obj._mgr.blocks[0] + if inplace: + assert blk._can_hold_element(elem) + else: + assert not blk._can_hold_element(elem) + + def check_series_setitem(self, elem, index: Index, inplace: bool): + arr = index._data.copy() + ser = Series(arr, copy=False) + + self.check_can_hold_element(ser, elem, inplace) + + if is_scalar(elem): + ser[0] = elem + else: + ser[: len(elem)] = elem + + if inplace: + assert ser.array is arr # i.e. setting was done inplace + else: + assert ser.dtype == object + + +class TestShouldStore: + def test_should_store_categorical(self): + cat = Categorical(["A", "B", "C"]) + df = DataFrame(cat) + blk = df._mgr.blocks[0] + + # matching dtype + assert blk.should_store(cat) + assert blk.should_store(cat[:-1]) + + # different dtype + assert not blk.should_store(cat.as_ordered()) + + # ndarray instead of Categorical + assert not blk.should_store(np.asarray(cat)) + + +def test_validate_ndim(): + values = np.array([1.0, 2.0]) + placement = BlockPlacement(slice(2)) + msg = r"Wrong number of dimensions. values.ndim != ndim \[1 != 2\]" + + with pytest.raises(ValueError, match=msg): + make_block(values, placement, ndim=2) + + +def test_block_shape(): + idx = Index([0, 1, 2, 3, 4]) + a = Series([1, 2, 3]).reindex(idx) + b = Series(Categorical([1, 2, 3])).reindex(idx) + + assert a._mgr.blocks[0].mgr_locs.indexer == b._mgr.blocks[0].mgr_locs.indexer + + +def test_make_block_no_pandas_array(block_maker): + # https://github.com/pandas-dev/pandas/pull/24866 + arr = pd.arrays.NumpyExtensionArray(np.array([1, 2])) + + # NumpyExtensionArray, no dtype + result = block_maker(arr, BlockPlacement(slice(len(arr))), ndim=arr.ndim) + assert result.dtype.kind in ["i", "u"] + + if block_maker is make_block: + # new_block requires caller to unwrap NumpyExtensionArray + assert result.is_extension is False + + # NumpyExtensionArray, NumpyEADtype + result = block_maker(arr, slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim) + assert result.dtype.kind in ["i", "u"] + assert result.is_extension is False + + # new_block no longer taked dtype keyword + # ndarray, NumpyEADtype + result = block_maker( + arr.to_numpy(), slice(len(arr)), dtype=arr.dtype, ndim=arr.ndim + ) + assert result.dtype.kind in ["i", "u"] + assert result.is_extension is False diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_managers.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_managers.py new file mode 100644 index 0000000000000000000000000000000000000000..f40362c299717be5f2e8665e4547276c2af05fb0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/internals/test_managers.py @@ -0,0 +1,103 @@ +""" +Testing interaction between the different managers (BlockManager, ArrayManager) +""" +import os +import subprocess +import sys + +import pytest + +from pandas.core.dtypes.missing import array_equivalent + +import pandas as pd +import pandas._testing as tm +from pandas.core.internals import ( + ArrayManager, + BlockManager, + SingleArrayManager, + SingleBlockManager, +) + + +def test_dataframe_creation(): + msg = "data_manager option is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + with pd.option_context("mode.data_manager", "block"): + df_block = pd.DataFrame( + {"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]} + ) + assert isinstance(df_block._mgr, BlockManager) + + with tm.assert_produces_warning(FutureWarning, match=msg): + with pd.option_context("mode.data_manager", "array"): + df_array = pd.DataFrame( + {"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]} + ) + assert isinstance(df_array._mgr, ArrayManager) + + # also ensure both are seen as equal + tm.assert_frame_equal(df_block, df_array) + + # conversion from one manager to the other + result = df_block._as_manager("block") + assert isinstance(result._mgr, BlockManager) + result = df_block._as_manager("array") + assert isinstance(result._mgr, ArrayManager) + tm.assert_frame_equal(result, df_block) + assert all( + array_equivalent(left, right) + for left, right in zip(result._mgr.arrays, df_array._mgr.arrays) + ) + + result = df_array._as_manager("array") + assert isinstance(result._mgr, ArrayManager) + result = df_array._as_manager("block") + assert isinstance(result._mgr, BlockManager) + tm.assert_frame_equal(result, df_array) + assert len(result._mgr.blocks) == 2 + + +def test_series_creation(): + msg = "data_manager option is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + with pd.option_context("mode.data_manager", "block"): + s_block = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"]) + assert isinstance(s_block._mgr, SingleBlockManager) + + with tm.assert_produces_warning(FutureWarning, match=msg): + with pd.option_context("mode.data_manager", "array"): + s_array = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"]) + assert isinstance(s_array._mgr, SingleArrayManager) + + # also ensure both are seen as equal + tm.assert_series_equal(s_block, s_array) + + # conversion from one manager to the other + result = s_block._as_manager("block") + assert isinstance(result._mgr, SingleBlockManager) + result = s_block._as_manager("array") + assert isinstance(result._mgr, SingleArrayManager) + tm.assert_series_equal(result, s_block) + + result = s_array._as_manager("array") + assert isinstance(result._mgr, SingleArrayManager) + result = s_array._as_manager("block") + assert isinstance(result._mgr, SingleBlockManager) + tm.assert_series_equal(result, s_array) + + +@pytest.mark.single_cpu +@pytest.mark.parametrize("manager", ["block", "array"]) +def test_array_manager_depr_env_var(manager): + # GH#55043 + test_env = os.environ.copy() + test_env["PANDAS_DATA_MANAGER"] = manager + response = subprocess.run( + [sys.executable, "-c", "import pandas"], + capture_output=True, + env=test_env, + check=True, + ) + msg = "FutureWarning: The env variable PANDAS_DATA_MANAGER is set" + stderr_msg = response.stderr.decode("utf-8") + assert msg in stderr_msg, stderr_msg diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/__init__.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_hashtable.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_hashtable.py new file mode 100644 index 0000000000000000000000000000000000000000..e54764f9ac4a69714f740124ad886eca10f33fc2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_hashtable.py @@ -0,0 +1,748 @@ +from collections.abc import Generator +from contextlib import contextmanager +import re +import struct +import tracemalloc + +import numpy as np +import pytest + +from pandas._libs import hashtable as ht + +import pandas as pd +import pandas._testing as tm +from pandas.core.algorithms import isin + + +@contextmanager +def activated_tracemalloc() -> Generator[None, None, None]: + tracemalloc.start() + try: + yield + finally: + tracemalloc.stop() + + +def get_allocated_khash_memory(): + snapshot = tracemalloc.take_snapshot() + snapshot = snapshot.filter_traces( + (tracemalloc.DomainFilter(True, ht.get_hashtable_trace_domain()),) + ) + return sum(x.size for x in snapshot.traces) + + +@pytest.mark.parametrize( + "table_type, dtype", + [ + (ht.PyObjectHashTable, np.object_), + (ht.Complex128HashTable, np.complex128), + (ht.Int64HashTable, np.int64), + (ht.UInt64HashTable, np.uint64), + (ht.Float64HashTable, np.float64), + (ht.Complex64HashTable, np.complex64), + (ht.Int32HashTable, np.int32), + (ht.UInt32HashTable, np.uint32), + (ht.Float32HashTable, np.float32), + (ht.Int16HashTable, np.int16), + (ht.UInt16HashTable, np.uint16), + (ht.Int8HashTable, np.int8), + (ht.UInt8HashTable, np.uint8), + (ht.IntpHashTable, np.intp), + ], +) +class TestHashTable: + def test_get_set_contains_len(self, table_type, dtype): + index = 5 + table = table_type(55) + assert len(table) == 0 + assert index not in table + + table.set_item(index, 42) + assert len(table) == 1 + assert index in table + assert table.get_item(index) == 42 + + table.set_item(index + 1, 41) + assert index in table + assert index + 1 in table + assert len(table) == 2 + assert table.get_item(index) == 42 + assert table.get_item(index + 1) == 41 + + table.set_item(index, 21) + assert index in table + assert index + 1 in table + assert len(table) == 2 + assert table.get_item(index) == 21 + assert table.get_item(index + 1) == 41 + assert index + 2 not in table + + table.set_item(index + 1, 21) + assert index in table + assert index + 1 in table + assert len(table) == 2 + assert table.get_item(index) == 21 + assert table.get_item(index + 1) == 21 + + with pytest.raises(KeyError, match=str(index + 2)): + table.get_item(index + 2) + + def test_get_set_contains_len_mask(self, table_type, dtype): + if table_type == ht.PyObjectHashTable: + pytest.skip("Mask not supported for object") + index = 5 + table = table_type(55, uses_mask=True) + assert len(table) == 0 + assert index not in table + + table.set_item(index, 42) + assert len(table) == 1 + assert index in table + assert table.get_item(index) == 42 + with pytest.raises(KeyError, match="NA"): + table.get_na() + + table.set_item(index + 1, 41) + table.set_na(41) + assert pd.NA in table + assert index in table + assert index + 1 in table + assert len(table) == 3 + assert table.get_item(index) == 42 + assert table.get_item(index + 1) == 41 + assert table.get_na() == 41 + + table.set_na(21) + assert index in table + assert index + 1 in table + assert len(table) == 3 + assert table.get_item(index + 1) == 41 + assert table.get_na() == 21 + assert index + 2 not in table + + with pytest.raises(KeyError, match=str(index + 2)): + table.get_item(index + 2) + + def test_map_keys_to_values(self, table_type, dtype, writable): + # only Int64HashTable has this method + if table_type == ht.Int64HashTable: + N = 77 + table = table_type() + keys = np.arange(N).astype(dtype) + vals = np.arange(N).astype(np.int64) + N + keys.flags.writeable = writable + vals.flags.writeable = writable + table.map_keys_to_values(keys, vals) + for i in range(N): + assert table.get_item(keys[i]) == i + N + + def test_map_locations(self, table_type, dtype, writable): + N = 8 + table = table_type() + keys = (np.arange(N) + N).astype(dtype) + keys.flags.writeable = writable + table.map_locations(keys) + for i in range(N): + assert table.get_item(keys[i]) == i + + def test_map_locations_mask(self, table_type, dtype, writable): + if table_type == ht.PyObjectHashTable: + pytest.skip("Mask not supported for object") + N = 3 + table = table_type(uses_mask=True) + keys = (np.arange(N) + N).astype(dtype) + keys.flags.writeable = writable + table.map_locations(keys, np.array([False, False, True])) + for i in range(N - 1): + assert table.get_item(keys[i]) == i + + with pytest.raises(KeyError, match=re.escape(str(keys[N - 1]))): + table.get_item(keys[N - 1]) + + assert table.get_na() == 2 + + def test_lookup(self, table_type, dtype, writable): + N = 3 + table = table_type() + keys = (np.arange(N) + N).astype(dtype) + keys.flags.writeable = writable + table.map_locations(keys) + result = table.lookup(keys) + expected = np.arange(N) + tm.assert_numpy_array_equal(result.astype(np.int64), expected.astype(np.int64)) + + def test_lookup_wrong(self, table_type, dtype): + if dtype in (np.int8, np.uint8): + N = 100 + else: + N = 512 + table = table_type() + keys = (np.arange(N) + N).astype(dtype) + table.map_locations(keys) + wrong_keys = np.arange(N).astype(dtype) + result = table.lookup(wrong_keys) + assert np.all(result == -1) + + def test_lookup_mask(self, table_type, dtype, writable): + if table_type == ht.PyObjectHashTable: + pytest.skip("Mask not supported for object") + N = 3 + table = table_type(uses_mask=True) + keys = (np.arange(N) + N).astype(dtype) + mask = np.array([False, True, False]) + keys.flags.writeable = writable + table.map_locations(keys, mask) + result = table.lookup(keys, mask) + expected = np.arange(N) + tm.assert_numpy_array_equal(result.astype(np.int64), expected.astype(np.int64)) + + result = table.lookup(np.array([1 + N]).astype(dtype), np.array([False])) + tm.assert_numpy_array_equal( + result.astype(np.int64), np.array([-1], dtype=np.int64) + ) + + def test_unique(self, table_type, dtype, writable): + if dtype in (np.int8, np.uint8): + N = 88 + else: + N = 1000 + table = table_type() + expected = (np.arange(N) + N).astype(dtype) + keys = np.repeat(expected, 5) + keys.flags.writeable = writable + unique = table.unique(keys) + tm.assert_numpy_array_equal(unique, expected) + + def test_tracemalloc_works(self, table_type, dtype): + if dtype in (np.int8, np.uint8): + N = 256 + else: + N = 30000 + keys = np.arange(N).astype(dtype) + with activated_tracemalloc(): + table = table_type() + table.map_locations(keys) + used = get_allocated_khash_memory() + my_size = table.sizeof() + assert used == my_size + del table + assert get_allocated_khash_memory() == 0 + + def test_tracemalloc_for_empty(self, table_type, dtype): + with activated_tracemalloc(): + table = table_type() + used = get_allocated_khash_memory() + my_size = table.sizeof() + assert used == my_size + del table + assert get_allocated_khash_memory() == 0 + + def test_get_state(self, table_type, dtype): + table = table_type(1000) + state = table.get_state() + assert state["size"] == 0 + assert state["n_occupied"] == 0 + assert "n_buckets" in state + assert "upper_bound" in state + + @pytest.mark.parametrize("N", range(1, 110)) + def test_no_reallocation(self, table_type, dtype, N): + keys = np.arange(N).astype(dtype) + preallocated_table = table_type(N) + n_buckets_start = preallocated_table.get_state()["n_buckets"] + preallocated_table.map_locations(keys) + n_buckets_end = preallocated_table.get_state()["n_buckets"] + # original number of buckets was enough: + assert n_buckets_start == n_buckets_end + # check with clean table (not too much preallocated) + clean_table = table_type() + clean_table.map_locations(keys) + assert n_buckets_start == clean_table.get_state()["n_buckets"] + + +class TestHashTableUnsorted: + # TODO: moved from test_algos; may be redundancies with other tests + def test_string_hashtable_set_item_signature(self): + # GH#30419 fix typing in StringHashTable.set_item to prevent segfault + tbl = ht.StringHashTable() + + tbl.set_item("key", 1) + assert tbl.get_item("key") == 1 + + with pytest.raises(TypeError, match="'key' has incorrect type"): + # key arg typed as string, not object + tbl.set_item(4, 6) + with pytest.raises(TypeError, match="'val' has incorrect type"): + tbl.get_item(4) + + def test_lookup_nan(self, writable): + # GH#21688 ensure we can deal with readonly memory views + xs = np.array([2.718, 3.14, np.nan, -7, 5, 2, 3]) + xs.setflags(write=writable) + m = ht.Float64HashTable() + m.map_locations(xs) + tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.intp)) + + def test_add_signed_zeros(self): + # GH#21866 inconsistent hash-function for float64 + # default hash-function would lead to different hash-buckets + # for 0.0 and -0.0 if there are more than 2^30 hash-buckets + # but this would mean 16GB + N = 4 # 12 * 10**8 would trigger the error, if you have enough memory + m = ht.Float64HashTable(N) + m.set_item(0.0, 0) + m.set_item(-0.0, 0) + assert len(m) == 1 # 0.0 and -0.0 are equivalent + + def test_add_different_nans(self): + # GH#21866 inconsistent hash-function for float64 + # create different nans from bit-patterns: + NAN1 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000000))[0] + NAN2 = struct.unpack("d", struct.pack("=Q", 0x7FF8000000000001))[0] + assert NAN1 != NAN1 + assert NAN2 != NAN2 + # default hash function would lead to different hash-buckets + # for NAN1 and NAN2 even if there are only 4 buckets: + m = ht.Float64HashTable() + m.set_item(NAN1, 0) + m.set_item(NAN2, 0) + assert len(m) == 1 # NAN1 and NAN2 are equivalent + + def test_lookup_overflow(self, writable): + xs = np.array([1, 2, 2**63], dtype=np.uint64) + # GH 21688 ensure we can deal with readonly memory views + xs.setflags(write=writable) + m = ht.UInt64HashTable() + m.map_locations(xs) + tm.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs), dtype=np.intp)) + + @pytest.mark.parametrize("nvals", [0, 10]) # resizing to 0 is special case + @pytest.mark.parametrize( + "htable, uniques, dtype, safely_resizes", + [ + (ht.PyObjectHashTable, ht.ObjectVector, "object", False), + (ht.StringHashTable, ht.ObjectVector, "object", True), + (ht.Float64HashTable, ht.Float64Vector, "float64", False), + (ht.Int64HashTable, ht.Int64Vector, "int64", False), + (ht.Int32HashTable, ht.Int32Vector, "int32", False), + (ht.UInt64HashTable, ht.UInt64Vector, "uint64", False), + ], + ) + def test_vector_resize( + self, writable, htable, uniques, dtype, safely_resizes, nvals + ): + # Test for memory errors after internal vector + # reallocations (GH 7157) + # Changed from using np.random.default_rng(2).rand to range + # which could cause flaky CI failures when safely_resizes=False + vals = np.array(range(1000), dtype=dtype) + + # GH 21688 ensures we can deal with read-only memory views + vals.setflags(write=writable) + + # initialise instances; cannot initialise in parametrization, + # as otherwise external views would be held on the array (which is + # one of the things this test is checking) + htable = htable() + uniques = uniques() + + # get_labels may append to uniques + htable.get_labels(vals[:nvals], uniques, 0, -1) + # to_array() sets an external_view_exists flag on uniques. + tmp = uniques.to_array() + oldshape = tmp.shape + + # subsequent get_labels() calls can no longer append to it + # (except for StringHashTables + ObjectVector) + if safely_resizes: + htable.get_labels(vals, uniques, 0, -1) + else: + with pytest.raises(ValueError, match="external reference.*"): + htable.get_labels(vals, uniques, 0, -1) + + uniques.to_array() # should not raise here + assert tmp.shape == oldshape + + @pytest.mark.parametrize( + "hashtable", + [ + ht.PyObjectHashTable, + ht.StringHashTable, + ht.Float64HashTable, + ht.Int64HashTable, + ht.Int32HashTable, + ht.UInt64HashTable, + ], + ) + def test_hashtable_large_sizehint(self, hashtable): + # GH#22729 smoketest for not raising when passing a large size_hint + size_hint = np.iinfo(np.uint32).max + 1 + hashtable(size_hint=size_hint) + + +class TestPyObjectHashTableWithNans: + def test_nan_float(self): + nan1 = float("nan") + nan2 = float("nan") + assert nan1 is not nan2 + table = ht.PyObjectHashTable() + table.set_item(nan1, 42) + assert table.get_item(nan2) == 42 + + def test_nan_complex_both(self): + nan1 = complex(float("nan"), float("nan")) + nan2 = complex(float("nan"), float("nan")) + assert nan1 is not nan2 + table = ht.PyObjectHashTable() + table.set_item(nan1, 42) + assert table.get_item(nan2) == 42 + + def test_nan_complex_real(self): + nan1 = complex(float("nan"), 1) + nan2 = complex(float("nan"), 1) + other = complex(float("nan"), 2) + assert nan1 is not nan2 + table = ht.PyObjectHashTable() + table.set_item(nan1, 42) + assert table.get_item(nan2) == 42 + with pytest.raises(KeyError, match=None) as error: + table.get_item(other) + assert str(error.value) == str(other) + + def test_nan_complex_imag(self): + nan1 = complex(1, float("nan")) + nan2 = complex(1, float("nan")) + other = complex(2, float("nan")) + assert nan1 is not nan2 + table = ht.PyObjectHashTable() + table.set_item(nan1, 42) + assert table.get_item(nan2) == 42 + with pytest.raises(KeyError, match=None) as error: + table.get_item(other) + assert str(error.value) == str(other) + + def test_nan_in_tuple(self): + nan1 = (float("nan"),) + nan2 = (float("nan"),) + assert nan1[0] is not nan2[0] + table = ht.PyObjectHashTable() + table.set_item(nan1, 42) + assert table.get_item(nan2) == 42 + + def test_nan_in_nested_tuple(self): + nan1 = (1, (2, (float("nan"),))) + nan2 = (1, (2, (float("nan"),))) + other = (1, 2) + table = ht.PyObjectHashTable() + table.set_item(nan1, 42) + assert table.get_item(nan2) == 42 + with pytest.raises(KeyError, match=None) as error: + table.get_item(other) + assert str(error.value) == str(other) + + +def test_hash_equal_tuple_with_nans(): + a = (float("nan"), (float("nan"), float("nan"))) + b = (float("nan"), (float("nan"), float("nan"))) + assert ht.object_hash(a) == ht.object_hash(b) + assert ht.objects_are_equal(a, b) + + +def test_get_labels_groupby_for_Int64(writable): + table = ht.Int64HashTable() + vals = np.array([1, 2, -1, 2, 1, -1], dtype=np.int64) + vals.flags.writeable = writable + arr, unique = table.get_labels_groupby(vals) + expected_arr = np.array([0, 1, -1, 1, 0, -1], dtype=np.intp) + expected_unique = np.array([1, 2], dtype=np.int64) + tm.assert_numpy_array_equal(arr, expected_arr) + tm.assert_numpy_array_equal(unique, expected_unique) + + +def test_tracemalloc_works_for_StringHashTable(): + N = 1000 + keys = np.arange(N).astype(np.str_).astype(np.object_) + with activated_tracemalloc(): + table = ht.StringHashTable() + table.map_locations(keys) + used = get_allocated_khash_memory() + my_size = table.sizeof() + assert used == my_size + del table + assert get_allocated_khash_memory() == 0 + + +def test_tracemalloc_for_empty_StringHashTable(): + with activated_tracemalloc(): + table = ht.StringHashTable() + used = get_allocated_khash_memory() + my_size = table.sizeof() + assert used == my_size + del table + assert get_allocated_khash_memory() == 0 + + +@pytest.mark.parametrize("N", range(1, 110)) +def test_no_reallocation_StringHashTable(N): + keys = np.arange(N).astype(np.str_).astype(np.object_) + preallocated_table = ht.StringHashTable(N) + n_buckets_start = preallocated_table.get_state()["n_buckets"] + preallocated_table.map_locations(keys) + n_buckets_end = preallocated_table.get_state()["n_buckets"] + # original number of buckets was enough: + assert n_buckets_start == n_buckets_end + # check with clean table (not too much preallocated) + clean_table = ht.StringHashTable() + clean_table.map_locations(keys) + assert n_buckets_start == clean_table.get_state()["n_buckets"] + + +@pytest.mark.parametrize( + "table_type, dtype", + [ + (ht.Float64HashTable, np.float64), + (ht.Float32HashTable, np.float32), + (ht.Complex128HashTable, np.complex128), + (ht.Complex64HashTable, np.complex64), + ], +) +class TestHashTableWithNans: + def test_get_set_contains_len(self, table_type, dtype): + index = float("nan") + table = table_type() + assert index not in table + + table.set_item(index, 42) + assert len(table) == 1 + assert index in table + assert table.get_item(index) == 42 + + table.set_item(index, 41) + assert len(table) == 1 + assert index in table + assert table.get_item(index) == 41 + + def test_map_locations(self, table_type, dtype): + N = 10 + table = table_type() + keys = np.full(N, np.nan, dtype=dtype) + table.map_locations(keys) + assert len(table) == 1 + assert table.get_item(np.nan) == N - 1 + + def test_unique(self, table_type, dtype): + N = 1020 + table = table_type() + keys = np.full(N, np.nan, dtype=dtype) + unique = table.unique(keys) + assert np.all(np.isnan(unique)) and len(unique) == 1 + + +def test_unique_for_nan_objects_floats(): + table = ht.PyObjectHashTable() + keys = np.array([float("nan") for i in range(50)], dtype=np.object_) + unique = table.unique(keys) + assert len(unique) == 1 + + +def test_unique_for_nan_objects_complex(): + table = ht.PyObjectHashTable() + keys = np.array([complex(float("nan"), 1.0) for i in range(50)], dtype=np.object_) + unique = table.unique(keys) + assert len(unique) == 1 + + +def test_unique_for_nan_objects_tuple(): + table = ht.PyObjectHashTable() + keys = np.array( + [1] + [(1.0, (float("nan"), 1.0)) for i in range(50)], dtype=np.object_ + ) + unique = table.unique(keys) + assert len(unique) == 2 + + +@pytest.mark.parametrize( + "dtype", + [ + np.object_, + np.complex128, + np.int64, + np.uint64, + np.float64, + np.complex64, + np.int32, + np.uint32, + np.float32, + np.int16, + np.uint16, + np.int8, + np.uint8, + np.intp, + ], +) +class TestHelpFunctions: + def test_value_count(self, dtype, writable): + N = 43 + expected = (np.arange(N) + N).astype(dtype) + values = np.repeat(expected, 5) + values.flags.writeable = writable + keys, counts, _ = ht.value_count(values, False) + tm.assert_numpy_array_equal(np.sort(keys), expected) + assert np.all(counts == 5) + + def test_value_count_mask(self, dtype): + if dtype == np.object_: + pytest.skip("mask not implemented for object dtype") + values = np.array([1] * 5, dtype=dtype) + mask = np.zeros((5,), dtype=np.bool_) + mask[1] = True + mask[4] = True + keys, counts, na_counter = ht.value_count(values, False, mask=mask) + assert len(keys) == 2 + assert na_counter == 2 + + def test_value_count_stable(self, dtype, writable): + # GH12679 + values = np.array([2, 1, 5, 22, 3, -1, 8]).astype(dtype) + values.flags.writeable = writable + keys, counts, _ = ht.value_count(values, False) + tm.assert_numpy_array_equal(keys, values) + assert np.all(counts == 1) + + def test_duplicated_first(self, dtype, writable): + N = 100 + values = np.repeat(np.arange(N).astype(dtype), 5) + values.flags.writeable = writable + result = ht.duplicated(values) + expected = np.ones_like(values, dtype=np.bool_) + expected[::5] = False + tm.assert_numpy_array_equal(result, expected) + + def test_ismember_yes(self, dtype, writable): + N = 127 + arr = np.arange(N).astype(dtype) + values = np.arange(N).astype(dtype) + arr.flags.writeable = writable + values.flags.writeable = writable + result = ht.ismember(arr, values) + expected = np.ones_like(values, dtype=np.bool_) + tm.assert_numpy_array_equal(result, expected) + + def test_ismember_no(self, dtype): + N = 17 + arr = np.arange(N).astype(dtype) + values = (np.arange(N) + N).astype(dtype) + result = ht.ismember(arr, values) + expected = np.zeros_like(values, dtype=np.bool_) + tm.assert_numpy_array_equal(result, expected) + + def test_mode(self, dtype, writable): + if dtype in (np.int8, np.uint8): + N = 53 + else: + N = 11111 + values = np.repeat(np.arange(N).astype(dtype), 5) + values[0] = 42 + values.flags.writeable = writable + result = ht.mode(values, False)[0] + assert result == 42 + + def test_mode_stable(self, dtype, writable): + values = np.array([2, 1, 5, 22, 3, -1, 8]).astype(dtype) + values.flags.writeable = writable + keys = ht.mode(values, False)[0] + tm.assert_numpy_array_equal(keys, values) + + +def test_modes_with_nans(): + # GH42688, nans aren't mangled + nulls = [pd.NA, np.nan, pd.NaT, None] + values = np.array([True] + nulls * 2, dtype=np.object_) + modes = ht.mode(values, False)[0] + assert modes.size == len(nulls) + + +def test_unique_label_indices_intp(writable): + keys = np.array([1, 2, 2, 2, 1, 3], dtype=np.intp) + keys.flags.writeable = writable + result = ht.unique_label_indices(keys) + expected = np.array([0, 1, 5], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_unique_label_indices(): + a = np.random.default_rng(2).integers(1, 1 << 10, 1 << 15).astype(np.intp) + + left = ht.unique_label_indices(a) + right = np.unique(a, return_index=True)[1] + + tm.assert_numpy_array_equal(left, right, check_dtype=False) + + a[np.random.default_rng(2).choice(len(a), 10)] = -1 + left = ht.unique_label_indices(a) + right = np.unique(a, return_index=True)[1][1:] + tm.assert_numpy_array_equal(left, right, check_dtype=False) + + +@pytest.mark.parametrize( + "dtype", + [ + np.float64, + np.float32, + np.complex128, + np.complex64, + ], +) +class TestHelpFunctionsWithNans: + def test_value_count(self, dtype): + values = np.array([np.nan, np.nan, np.nan], dtype=dtype) + keys, counts, _ = ht.value_count(values, True) + assert len(keys) == 0 + keys, counts, _ = ht.value_count(values, False) + assert len(keys) == 1 and np.all(np.isnan(keys)) + assert counts[0] == 3 + + def test_duplicated_first(self, dtype): + values = np.array([np.nan, np.nan, np.nan], dtype=dtype) + result = ht.duplicated(values) + expected = np.array([False, True, True]) + tm.assert_numpy_array_equal(result, expected) + + def test_ismember_yes(self, dtype): + arr = np.array([np.nan, np.nan, np.nan], dtype=dtype) + values = np.array([np.nan, np.nan], dtype=dtype) + result = ht.ismember(arr, values) + expected = np.array([True, True, True], dtype=np.bool_) + tm.assert_numpy_array_equal(result, expected) + + def test_ismember_no(self, dtype): + arr = np.array([np.nan, np.nan, np.nan], dtype=dtype) + values = np.array([1], dtype=dtype) + result = ht.ismember(arr, values) + expected = np.array([False, False, False], dtype=np.bool_) + tm.assert_numpy_array_equal(result, expected) + + def test_mode(self, dtype): + values = np.array([42, np.nan, np.nan, np.nan], dtype=dtype) + assert ht.mode(values, True)[0] == 42 + assert np.isnan(ht.mode(values, False)[0]) + + +def test_ismember_tuple_with_nans(): + # GH-41836 + values = [("a", float("nan")), ("b", 1)] + comps = [("a", float("nan"))] + + msg = "isin with argument that is not not a Series" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = isin(values, comps) + expected = np.array([True, False], dtype=np.bool_) + tm.assert_numpy_array_equal(result, expected) + + +def test_float_complex_int_are_equal_as_objects(): + values = ["a", 5, 5.0, 5.0 + 0j] + comps = list(range(129)) + result = isin(np.array(values, dtype=object), np.asarray(comps)) + expected = np.array([False, True, True, True], dtype=np.bool_) + tm.assert_numpy_array_equal(result, expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_join.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2e6e713092916648d375a991e3cb4d9fc7828d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_join.py @@ -0,0 +1,390 @@ +import numpy as np +import pytest + +from pandas._libs import join as libjoin +from pandas._libs.join import ( + inner_join, + left_outer_join, +) + +import pandas._testing as tm + + +class TestIndexer: + @pytest.mark.parametrize( + "dtype", ["int32", "int64", "float32", "float64", "object"] + ) + def test_outer_join_indexer(self, dtype): + indexer = libjoin.outer_join_indexer + + left = np.arange(3, dtype=dtype) + right = np.arange(2, 5, dtype=dtype) + empty = np.array([], dtype=dtype) + + result, lindexer, rindexer = indexer(left, right) + assert isinstance(result, np.ndarray) + assert isinstance(lindexer, np.ndarray) + assert isinstance(rindexer, np.ndarray) + tm.assert_numpy_array_equal(result, np.arange(5, dtype=dtype)) + exp = np.array([0, 1, 2, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(lindexer, exp) + exp = np.array([-1, -1, 0, 1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(rindexer, exp) + + result, lindexer, rindexer = indexer(empty, right) + tm.assert_numpy_array_equal(result, right) + exp = np.array([-1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(lindexer, exp) + exp = np.array([0, 1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(rindexer, exp) + + result, lindexer, rindexer = indexer(left, empty) + tm.assert_numpy_array_equal(result, left) + exp = np.array([0, 1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(lindexer, exp) + exp = np.array([-1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(rindexer, exp) + + def test_cython_left_outer_join(self): + left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.intp) + right = np.array([1, 1, 0, 4, 2, 2, 1], dtype=np.intp) + max_group = 5 + + ls, rs = left_outer_join(left, right, max_group) + + exp_ls = left.argsort(kind="mergesort") + exp_rs = right.argsort(kind="mergesort") + + exp_li = np.array([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10]) + exp_ri = np.array( + [0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5, -1, -1] + ) + + exp_ls = exp_ls.take(exp_li) + exp_ls[exp_li == -1] = -1 + + exp_rs = exp_rs.take(exp_ri) + exp_rs[exp_ri == -1] = -1 + + tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False) + tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False) + + def test_cython_right_outer_join(self): + left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.intp) + right = np.array([1, 1, 0, 4, 2, 2, 1], dtype=np.intp) + max_group = 5 + + rs, ls = left_outer_join(right, left, max_group) + + exp_ls = left.argsort(kind="mergesort") + exp_rs = right.argsort(kind="mergesort") + + # 0 1 1 1 + exp_li = np.array( + [ + 0, + 1, + 2, + 3, + 4, + 5, + 3, + 4, + 5, + 3, + 4, + 5, + # 2 2 4 + 6, + 7, + 8, + 6, + 7, + 8, + -1, + ] + ) + exp_ri = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6]) + + exp_ls = exp_ls.take(exp_li) + exp_ls[exp_li == -1] = -1 + + exp_rs = exp_rs.take(exp_ri) + exp_rs[exp_ri == -1] = -1 + + tm.assert_numpy_array_equal(ls, exp_ls) + tm.assert_numpy_array_equal(rs, exp_rs) + + def test_cython_inner_join(self): + left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.intp) + right = np.array([1, 1, 0, 4, 2, 2, 1, 4], dtype=np.intp) + max_group = 5 + + ls, rs = inner_join(left, right, max_group) + + exp_ls = left.argsort(kind="mergesort") + exp_rs = right.argsort(kind="mergesort") + + exp_li = np.array([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8]) + exp_ri = np.array([0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5]) + + exp_ls = exp_ls.take(exp_li) + exp_ls[exp_li == -1] = -1 + + exp_rs = exp_rs.take(exp_ri) + exp_rs[exp_ri == -1] = -1 + + tm.assert_numpy_array_equal(ls, exp_ls) + tm.assert_numpy_array_equal(rs, exp_rs) + + +@pytest.mark.parametrize("readonly", [True, False]) +def test_left_join_indexer_unique(readonly): + a = np.array([1, 2, 3, 4, 5], dtype=np.int64) + b = np.array([2, 2, 3, 4, 4], dtype=np.int64) + if readonly: + # GH#37312, GH#37264 + a.setflags(write=False) + b.setflags(write=False) + + result = libjoin.left_join_indexer_unique(b, a) + expected = np.array([1, 1, 2, 3, 3], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +def test_left_outer_join_bug(): + left = np.array( + [ + 0, + 1, + 0, + 1, + 1, + 2, + 3, + 1, + 0, + 2, + 1, + 2, + 0, + 1, + 1, + 2, + 3, + 2, + 3, + 2, + 1, + 1, + 3, + 0, + 3, + 2, + 3, + 0, + 0, + 2, + 3, + 2, + 0, + 3, + 1, + 3, + 0, + 1, + 3, + 0, + 0, + 1, + 0, + 3, + 1, + 0, + 1, + 0, + 1, + 1, + 0, + 2, + 2, + 2, + 2, + 2, + 0, + 3, + 1, + 2, + 0, + 0, + 3, + 1, + 3, + 2, + 2, + 0, + 1, + 3, + 0, + 2, + 3, + 2, + 3, + 3, + 2, + 3, + 3, + 1, + 3, + 2, + 0, + 0, + 3, + 1, + 1, + 1, + 0, + 2, + 3, + 3, + 1, + 2, + 0, + 3, + 1, + 2, + 0, + 2, + ], + dtype=np.intp, + ) + + right = np.array([3, 1], dtype=np.intp) + max_groups = 4 + + lidx, ridx = libjoin.left_outer_join(left, right, max_groups, sort=False) + + exp_lidx = np.arange(len(left), dtype=np.intp) + exp_ridx = -np.ones(len(left), dtype=np.intp) + + exp_ridx[left == 1] = 1 + exp_ridx[left == 3] = 0 + + tm.assert_numpy_array_equal(lidx, exp_lidx) + tm.assert_numpy_array_equal(ridx, exp_ridx) + + +def test_inner_join_indexer(): + a = np.array([1, 2, 3, 4, 5], dtype=np.int64) + b = np.array([0, 3, 5, 7, 9], dtype=np.int64) + + index, ares, bres = libjoin.inner_join_indexer(a, b) + + index_exp = np.array([3, 5], dtype=np.int64) + tm.assert_almost_equal(index, index_exp) + + aexp = np.array([2, 4], dtype=np.intp) + bexp = np.array([1, 2], dtype=np.intp) + tm.assert_almost_equal(ares, aexp) + tm.assert_almost_equal(bres, bexp) + + a = np.array([5], dtype=np.int64) + b = np.array([5], dtype=np.int64) + + index, ares, bres = libjoin.inner_join_indexer(a, b) + tm.assert_numpy_array_equal(index, np.array([5], dtype=np.int64)) + tm.assert_numpy_array_equal(ares, np.array([0], dtype=np.intp)) + tm.assert_numpy_array_equal(bres, np.array([0], dtype=np.intp)) + + +def test_outer_join_indexer(): + a = np.array([1, 2, 3, 4, 5], dtype=np.int64) + b = np.array([0, 3, 5, 7, 9], dtype=np.int64) + + index, ares, bres = libjoin.outer_join_indexer(a, b) + + index_exp = np.array([0, 1, 2, 3, 4, 5, 7, 9], dtype=np.int64) + tm.assert_almost_equal(index, index_exp) + + aexp = np.array([-1, 0, 1, 2, 3, 4, -1, -1], dtype=np.intp) + bexp = np.array([0, -1, -1, 1, -1, 2, 3, 4], dtype=np.intp) + tm.assert_almost_equal(ares, aexp) + tm.assert_almost_equal(bres, bexp) + + a = np.array([5], dtype=np.int64) + b = np.array([5], dtype=np.int64) + + index, ares, bres = libjoin.outer_join_indexer(a, b) + tm.assert_numpy_array_equal(index, np.array([5], dtype=np.int64)) + tm.assert_numpy_array_equal(ares, np.array([0], dtype=np.intp)) + tm.assert_numpy_array_equal(bres, np.array([0], dtype=np.intp)) + + +def test_left_join_indexer(): + a = np.array([1, 2, 3, 4, 5], dtype=np.int64) + b = np.array([0, 3, 5, 7, 9], dtype=np.int64) + + index, ares, bres = libjoin.left_join_indexer(a, b) + + tm.assert_almost_equal(index, a) + + aexp = np.array([0, 1, 2, 3, 4], dtype=np.intp) + bexp = np.array([-1, -1, 1, -1, 2], dtype=np.intp) + tm.assert_almost_equal(ares, aexp) + tm.assert_almost_equal(bres, bexp) + + a = np.array([5], dtype=np.int64) + b = np.array([5], dtype=np.int64) + + index, ares, bres = libjoin.left_join_indexer(a, b) + tm.assert_numpy_array_equal(index, np.array([5], dtype=np.int64)) + tm.assert_numpy_array_equal(ares, np.array([0], dtype=np.intp)) + tm.assert_numpy_array_equal(bres, np.array([0], dtype=np.intp)) + + +def test_left_join_indexer2(): + idx = np.array([1, 1, 2, 5], dtype=np.int64) + idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64) + + res, lidx, ridx = libjoin.left_join_indexer(idx2, idx) + + exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) + tm.assert_almost_equal(res, exp_res) + + exp_lidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_almost_equal(lidx, exp_lidx) + + exp_ridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + tm.assert_almost_equal(ridx, exp_ridx) + + +def test_outer_join_indexer2(): + idx = np.array([1, 1, 2, 5], dtype=np.int64) + idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64) + + res, lidx, ridx = libjoin.outer_join_indexer(idx2, idx) + + exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) + tm.assert_almost_equal(res, exp_res) + + exp_lidx = np.array([0, 0, 1, 2, 3, 4], dtype=np.intp) + tm.assert_almost_equal(lidx, exp_lidx) + + exp_ridx = np.array([0, 1, 2, 3, -1, -1], dtype=np.intp) + tm.assert_almost_equal(ridx, exp_ridx) + + +def test_inner_join_indexer2(): + idx = np.array([1, 1, 2, 5], dtype=np.int64) + idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64) + + res, lidx, ridx = libjoin.inner_join_indexer(idx2, idx) + + exp_res = np.array([1, 1, 2, 5], dtype=np.int64) + tm.assert_almost_equal(res, exp_res) + + exp_lidx = np.array([0, 0, 1, 2], dtype=np.intp) + tm.assert_almost_equal(lidx, exp_lidx) + + exp_ridx = np.array([0, 1, 2, 3], dtype=np.intp) + tm.assert_almost_equal(ridx, exp_ridx) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_lib.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..17dae1879f3b818bac33f8825d0392d1c028975f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_lib.py @@ -0,0 +1,299 @@ +import pickle + +import numpy as np +import pytest + +from pandas._libs import ( + Timedelta, + lib, + writers as libwriters, +) +from pandas.compat import IS64 + +from pandas import Index +import pandas._testing as tm + + +class TestMisc: + def test_max_len_string_array(self): + arr = a = np.array(["foo", "b", np.nan], dtype="object") + assert libwriters.max_len_string_array(arr) == 3 + + # unicode + arr = a.astype("U").astype(object) + assert libwriters.max_len_string_array(arr) == 3 + + # bytes for python3 + arr = a.astype("S").astype(object) + assert libwriters.max_len_string_array(arr) == 3 + + # raises + msg = "No matching signature found" + with pytest.raises(TypeError, match=msg): + libwriters.max_len_string_array(arr.astype("U")) + + def test_fast_unique_multiple_list_gen_sort(self): + keys = [["p", "a"], ["n", "d"], ["a", "s"]] + + gen = (key for key in keys) + expected = np.array(["a", "d", "n", "p", "s"]) + out = lib.fast_unique_multiple_list_gen(gen, sort=True) + tm.assert_numpy_array_equal(np.array(out), expected) + + gen = (key for key in keys) + expected = np.array(["p", "a", "n", "d", "s"]) + out = lib.fast_unique_multiple_list_gen(gen, sort=False) + tm.assert_numpy_array_equal(np.array(out), expected) + + def test_fast_multiget_timedelta_resos(self): + # This will become relevant for test_constructor_dict_timedelta64_index + # once Timedelta constructor preserves reso when passed a + # np.timedelta64 object + td = Timedelta(days=1) + + mapping1 = {td: 1} + mapping2 = {td.as_unit("s"): 1} + + oindex = Index([td * n for n in range(3)])._values.astype(object) + + expected = lib.fast_multiget(mapping1, oindex) + result = lib.fast_multiget(mapping2, oindex) + tm.assert_numpy_array_equal(result, expected) + + # case that can't be cast to td64ns + td = Timedelta(np.timedelta64(146000, "D")) + assert hash(td) == hash(td.as_unit("ms")) + assert hash(td) == hash(td.as_unit("us")) + mapping1 = {td: 1} + mapping2 = {td.as_unit("ms"): 1} + + oindex = Index([td * n for n in range(3)])._values.astype(object) + + expected = lib.fast_multiget(mapping1, oindex) + result = lib.fast_multiget(mapping2, oindex) + tm.assert_numpy_array_equal(result, expected) + + +class TestIndexing: + def test_maybe_indices_to_slice_left_edge(self): + target = np.arange(100) + + # slice + indices = np.array([], dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + @pytest.mark.parametrize("end", [1, 2, 5, 20, 99]) + @pytest.mark.parametrize("step", [1, 2, 4]) + def test_maybe_indices_to_slice_left_edge_not_slice_end_steps(self, end, step): + target = np.arange(100) + indices = np.arange(0, end, step, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + # reverse + indices = indices[::-1] + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + @pytest.mark.parametrize( + "case", [[2, 1, 2, 0], [2, 2, 1, 0], [0, 1, 2, 1], [-2, 0, 2], [2, 0, -2]] + ) + def test_maybe_indices_to_slice_left_edge_not_slice(self, case): + # not slice + target = np.arange(100) + indices = np.array(case, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert not isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(maybe_slice, indices) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + @pytest.mark.parametrize("start", [0, 2, 5, 20, 97, 98]) + @pytest.mark.parametrize("step", [1, 2, 4]) + def test_maybe_indices_to_slice_right_edge(self, start, step): + target = np.arange(100) + + # slice + indices = np.arange(start, 99, step, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + # reverse + indices = indices[::-1] + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + def test_maybe_indices_to_slice_right_edge_not_slice(self): + # not slice + target = np.arange(100) + indices = np.array([97, 98, 99, 100], dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert not isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(maybe_slice, indices) + + msg = "index 100 is out of bounds for axis (0|1) with size 100" + + with pytest.raises(IndexError, match=msg): + target[indices] + with pytest.raises(IndexError, match=msg): + target[maybe_slice] + + indices = np.array([100, 99, 98, 97], dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert not isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(maybe_slice, indices) + + with pytest.raises(IndexError, match=msg): + target[indices] + with pytest.raises(IndexError, match=msg): + target[maybe_slice] + + @pytest.mark.parametrize( + "case", [[99, 97, 99, 96], [99, 99, 98, 97], [98, 98, 97, 96]] + ) + def test_maybe_indices_to_slice_right_edge_cases(self, case): + target = np.arange(100) + indices = np.array(case, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert not isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(maybe_slice, indices) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + @pytest.mark.parametrize("step", [1, 2, 4, 5, 8, 9]) + def test_maybe_indices_to_slice_both_edges(self, step): + target = np.arange(10) + + # slice + indices = np.arange(0, 9, step, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + # reverse + indices = indices[::-1] + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + @pytest.mark.parametrize("case", [[4, 2, 0, -2], [2, 2, 1, 0], [0, 1, 2, 1]]) + def test_maybe_indices_to_slice_both_edges_not_slice(self, case): + # not slice + target = np.arange(10) + indices = np.array(case, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + assert not isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(maybe_slice, indices) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + @pytest.mark.parametrize("start, end", [(2, 10), (5, 25), (65, 97)]) + @pytest.mark.parametrize("step", [1, 2, 4, 20]) + def test_maybe_indices_to_slice_middle(self, start, end, step): + target = np.arange(100) + + # slice + indices = np.arange(start, end, step, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + # reverse + indices = indices[::-1] + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + @pytest.mark.parametrize( + "case", [[14, 12, 10, 12], [12, 12, 11, 10], [10, 11, 12, 11]] + ) + def test_maybe_indices_to_slice_middle_not_slice(self, case): + # not slice + target = np.arange(100) + indices = np.array(case, dtype=np.intp) + maybe_slice = lib.maybe_indices_to_slice(indices, len(target)) + + assert not isinstance(maybe_slice, slice) + tm.assert_numpy_array_equal(maybe_slice, indices) + tm.assert_numpy_array_equal(target[indices], target[maybe_slice]) + + def test_maybe_booleans_to_slice(self): + arr = np.array([0, 0, 1, 1, 1, 0, 1], dtype=np.uint8) + result = lib.maybe_booleans_to_slice(arr) + assert result.dtype == np.bool_ + + result = lib.maybe_booleans_to_slice(arr[:0]) + assert result == slice(0, 0) + + def test_get_reverse_indexer(self): + indexer = np.array([-1, -1, 1, 2, 0, -1, 3, 4], dtype=np.intp) + result = lib.get_reverse_indexer(indexer, 5) + expected = np.array([4, 2, 3, 6, 7], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["int64", "int32"]) + def test_is_range_indexer(self, dtype): + # GH#50592 + left = np.arange(0, 100, dtype=dtype) + assert lib.is_range_indexer(left, 100) + + @pytest.mark.skipif( + not IS64, + reason="2**31 is too big for Py_ssize_t on 32-bit. " + "It doesn't matter though since you cannot create an array that long on 32-bit", + ) + @pytest.mark.parametrize("dtype", ["int64", "int32"]) + def test_is_range_indexer_big_n(self, dtype): + # GH53616 + left = np.arange(0, 100, dtype=dtype) + + assert not lib.is_range_indexer(left, 2**31) + + @pytest.mark.parametrize("dtype", ["int64", "int32"]) + def test_is_range_indexer_not_equal(self, dtype): + # GH#50592 + left = np.array([1, 2], dtype=dtype) + assert not lib.is_range_indexer(left, 2) + + @pytest.mark.parametrize("dtype", ["int64", "int32"]) + def test_is_range_indexer_not_equal_shape(self, dtype): + # GH#50592 + left = np.array([0, 1, 2], dtype=dtype) + assert not lib.is_range_indexer(left, 2) + + +def test_cache_readonly_preserve_docstrings(): + # GH18197 + assert Index.hasnans.__doc__ is not None + + +def test_no_default_pickle(): + # GH#40397 + obj = tm.round_trip_pickle(lib.no_default) + assert obj is lib.no_default + + +def test_ensure_string_array_copy(): + # ensure the original array is not modified in case of copy=False with + # pickle-roundtripped object dtype array + # https://github.com/pandas-dev/pandas/issues/54654 + arr = np.array(["a", None], dtype=object) + arr = pickle.loads(pickle.dumps(arr)) + result = lib.ensure_string_array(arr, copy=False) + assert not np.shares_memory(arr, result) + assert arr[1] is None + assert result[1] is np.nan diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_libalgos.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_libalgos.py new file mode 100644 index 0000000000000000000000000000000000000000..42d09c72aab2baa9636093d172d864cbe0e41b12 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/libs/test_libalgos.py @@ -0,0 +1,162 @@ +from datetime import datetime +from itertools import permutations + +import numpy as np + +from pandas._libs import algos as libalgos + +import pandas._testing as tm + + +def test_ensure_platform_int(): + arr = np.arange(100, dtype=np.intp) + + result = libalgos.ensure_platform_int(arr) + assert result is arr + + +def test_is_lexsorted(): + failure = [ + np.array( + ([3] * 32) + ([2] * 32) + ([1] * 32) + ([0] * 32), + dtype="int64", + ), + np.array( + list(range(31))[::-1] * 4, + dtype="int64", + ), + ] + + assert not libalgos.is_lexsorted(failure) + + +def test_groupsort_indexer(): + a = np.random.default_rng(2).integers(0, 1000, 100).astype(np.intp) + b = np.random.default_rng(2).integers(0, 1000, 100).astype(np.intp) + + result = libalgos.groupsort_indexer(a, 1000)[0] + + # need to use a stable sort + # np.argsort returns int, groupsort_indexer + # always returns intp + expected = np.argsort(a, kind="mergesort") + expected = expected.astype(np.intp) + + tm.assert_numpy_array_equal(result, expected) + + # compare with lexsort + # np.lexsort returns int, groupsort_indexer + # always returns intp + key = a * 1000 + b + result = libalgos.groupsort_indexer(key, 1000000)[0] + expected = np.lexsort((b, a)) + expected = expected.astype(np.intp) + + tm.assert_numpy_array_equal(result, expected) + + +class TestPadBackfill: + def test_backfill(self): + old = np.array([1, 5, 10], dtype=np.int64) + new = np.array(list(range(12)), dtype=np.int64) + + filler = libalgos.backfill["int64_t"](old, new) + + expect_filler = np.array([0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + # corner case + old = np.array([1, 4], dtype=np.int64) + new = np.array(list(range(5, 10)), dtype=np.int64) + filler = libalgos.backfill["int64_t"](old, new) + + expect_filler = np.array([-1, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + def test_pad(self): + old = np.array([1, 5, 10], dtype=np.int64) + new = np.array(list(range(12)), dtype=np.int64) + + filler = libalgos.pad["int64_t"](old, new) + + expect_filler = np.array([-1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + # corner case + old = np.array([5, 10], dtype=np.int64) + new = np.arange(5, dtype=np.int64) + filler = libalgos.pad["int64_t"](old, new) + expect_filler = np.array([-1, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + def test_pad_backfill_object_segfault(self): + old = np.array([], dtype="O") + new = np.array([datetime(2010, 12, 31)], dtype="O") + + result = libalgos.pad["object"](old, new) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = libalgos.pad["object"](new, old) + expected = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = libalgos.backfill["object"](old, new) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = libalgos.backfill["object"](new, old) + expected = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +class TestInfinity: + def test_infinity_sort(self): + # GH#13445 + # numpy's argsort can be unhappy if something is less than + # itself. Instead, let's give our infinities a self-consistent + # ordering, but outside the float extended real line. + + Inf = libalgos.Infinity() + NegInf = libalgos.NegInfinity() + + ref_nums = [NegInf, float("-inf"), -1e100, 0, 1e100, float("inf"), Inf] + + assert all(Inf >= x for x in ref_nums) + assert all(Inf > x or x is Inf for x in ref_nums) + assert Inf >= Inf and Inf == Inf + assert not Inf < Inf and not Inf > Inf + assert libalgos.Infinity() == libalgos.Infinity() + assert not libalgos.Infinity() != libalgos.Infinity() + + assert all(NegInf <= x for x in ref_nums) + assert all(NegInf < x or x is NegInf for x in ref_nums) + assert NegInf <= NegInf and NegInf == NegInf + assert not NegInf < NegInf and not NegInf > NegInf + assert libalgos.NegInfinity() == libalgos.NegInfinity() + assert not libalgos.NegInfinity() != libalgos.NegInfinity() + + for perm in permutations(ref_nums): + assert sorted(perm) == ref_nums + + # smoke tests + np.array([libalgos.Infinity()] * 32).argsort() + np.array([libalgos.NegInfinity()] * 32).argsort() + + def test_infinity_against_nan(self): + Inf = libalgos.Infinity() + NegInf = libalgos.NegInfinity() + + assert not Inf > np.nan + assert not Inf >= np.nan + assert not Inf < np.nan + assert not Inf <= np.nan + assert not Inf == np.nan + assert Inf != np.nan + + assert not NegInf > np.nan + assert not NegInf >= np.nan + assert not NegInf < np.nan + assert not NegInf <= np.nan + assert not NegInf == np.nan + assert NegInf != np.nan diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/__init__.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/common.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/common.py new file mode 100644 index 0000000000000000000000000000000000000000..69120160699c24cc86670522f84ec6c7014c20ee --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/common.py @@ -0,0 +1,563 @@ +""" +Module consolidating common testing functions for checking plotting. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +from pandas.core.dtypes.api import is_list_like + +import pandas as pd +from pandas import Series +import pandas._testing as tm + +if TYPE_CHECKING: + from collections.abc import Sequence + + from matplotlib.axes import Axes + + +def _check_legend_labels(axes, labels=None, visible=True): + """ + Check each axes has expected legend labels + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + labels : list-like + expected legend labels + visible : bool + expected legend visibility. labels are checked only when visible is + True + """ + if visible and (labels is None): + raise ValueError("labels must be specified when visible is True") + axes = _flatten_visible(axes) + for ax in axes: + if visible: + assert ax.get_legend() is not None + _check_text_labels(ax.get_legend().get_texts(), labels) + else: + assert ax.get_legend() is None + + +def _check_legend_marker(ax, expected_markers=None, visible=True): + """ + Check ax has expected legend markers + + Parameters + ---------- + ax : matplotlib Axes object + expected_markers : list-like + expected legend markers + visible : bool + expected legend visibility. labels are checked only when visible is + True + """ + if visible and (expected_markers is None): + raise ValueError("Markers must be specified when visible is True") + if visible: + handles, _ = ax.get_legend_handles_labels() + markers = [handle.get_marker() for handle in handles] + assert markers == expected_markers + else: + assert ax.get_legend() is None + + +def _check_data(xp, rs): + """ + Check each axes has identical lines + + Parameters + ---------- + xp : matplotlib Axes object + rs : matplotlib Axes object + """ + import matplotlib.pyplot as plt + + xp_lines = xp.get_lines() + rs_lines = rs.get_lines() + + assert len(xp_lines) == len(rs_lines) + for xpl, rsl in zip(xp_lines, rs_lines): + xpdata = xpl.get_xydata() + rsdata = rsl.get_xydata() + tm.assert_almost_equal(xpdata, rsdata) + + plt.close("all") + + +def _check_visible(collections, visible=True): + """ + Check each artist is visible or not + + Parameters + ---------- + collections : matplotlib Artist or its list-like + target Artist or its list or collection + visible : bool + expected visibility + """ + from matplotlib.collections import Collection + + if not isinstance(collections, Collection) and not is_list_like(collections): + collections = [collections] + + for patch in collections: + assert patch.get_visible() == visible + + +def _check_patches_all_filled(axes: Axes | Sequence[Axes], filled: bool = True) -> None: + """ + Check for each artist whether it is filled or not + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + filled : bool + expected filling + """ + + axes = _flatten_visible(axes) + for ax in axes: + for patch in ax.patches: + assert patch.fill == filled + + +def _get_colors_mapped(series, colors): + unique = series.unique() + # unique and colors length can be differed + # depending on slice value + mapped = dict(zip(unique, colors)) + return [mapped[v] for v in series.values] + + +def _check_colors(collections, linecolors=None, facecolors=None, mapping=None): + """ + Check each artist has expected line colors and face colors + + Parameters + ---------- + collections : list-like + list or collection of target artist + linecolors : list-like which has the same length as collections + list of expected line colors + facecolors : list-like which has the same length as collections + list of expected face colors + mapping : Series + Series used for color grouping key + used for andrew_curves, parallel_coordinates, radviz test + """ + from matplotlib import colors + from matplotlib.collections import ( + Collection, + LineCollection, + PolyCollection, + ) + from matplotlib.lines import Line2D + + conv = colors.ColorConverter + if linecolors is not None: + if mapping is not None: + linecolors = _get_colors_mapped(mapping, linecolors) + linecolors = linecolors[: len(collections)] + + assert len(collections) == len(linecolors) + for patch, color in zip(collections, linecolors): + if isinstance(patch, Line2D): + result = patch.get_color() + # Line2D may contains string color expression + result = conv.to_rgba(result) + elif isinstance(patch, (PolyCollection, LineCollection)): + result = tuple(patch.get_edgecolor()[0]) + else: + result = patch.get_edgecolor() + + expected = conv.to_rgba(color) + assert result == expected + + if facecolors is not None: + if mapping is not None: + facecolors = _get_colors_mapped(mapping, facecolors) + facecolors = facecolors[: len(collections)] + + assert len(collections) == len(facecolors) + for patch, color in zip(collections, facecolors): + if isinstance(patch, Collection): + # returned as list of np.array + result = patch.get_facecolor()[0] + else: + result = patch.get_facecolor() + + if isinstance(result, np.ndarray): + result = tuple(result) + + expected = conv.to_rgba(color) + assert result == expected + + +def _check_text_labels(texts, expected): + """ + Check each text has expected labels + + Parameters + ---------- + texts : matplotlib Text object, or its list-like + target text, or its list + expected : str or list-like which has the same length as texts + expected text label, or its list + """ + if not is_list_like(texts): + assert texts.get_text() == expected + else: + labels = [t.get_text() for t in texts] + assert len(labels) == len(expected) + for label, e in zip(labels, expected): + assert label == e + + +def _check_ticks_props(axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None): + """ + Check each axes has expected tick properties + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + xlabelsize : number + expected xticks font size + xrot : number + expected xticks rotation + ylabelsize : number + expected yticks font size + yrot : number + expected yticks rotation + """ + from matplotlib.ticker import NullFormatter + + axes = _flatten_visible(axes) + for ax in axes: + if xlabelsize is not None or xrot is not None: + if isinstance(ax.xaxis.get_minor_formatter(), NullFormatter): + # If minor ticks has NullFormatter, rot / fontsize are not + # retained + labels = ax.get_xticklabels() + else: + labels = ax.get_xticklabels() + ax.get_xticklabels(minor=True) + + for label in labels: + if xlabelsize is not None: + tm.assert_almost_equal(label.get_fontsize(), xlabelsize) + if xrot is not None: + tm.assert_almost_equal(label.get_rotation(), xrot) + + if ylabelsize is not None or yrot is not None: + if isinstance(ax.yaxis.get_minor_formatter(), NullFormatter): + labels = ax.get_yticklabels() + else: + labels = ax.get_yticklabels() + ax.get_yticklabels(minor=True) + + for label in labels: + if ylabelsize is not None: + tm.assert_almost_equal(label.get_fontsize(), ylabelsize) + if yrot is not None: + tm.assert_almost_equal(label.get_rotation(), yrot) + + +def _check_ax_scales(axes, xaxis="linear", yaxis="linear"): + """ + Check each axes has expected scales + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + xaxis : {'linear', 'log'} + expected xaxis scale + yaxis : {'linear', 'log'} + expected yaxis scale + """ + axes = _flatten_visible(axes) + for ax in axes: + assert ax.xaxis.get_scale() == xaxis + assert ax.yaxis.get_scale() == yaxis + + +def _check_axes_shape(axes, axes_num=None, layout=None, figsize=None): + """ + Check expected number of axes is drawn in expected layout + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + axes_num : number + expected number of axes. Unnecessary axes should be set to + invisible. + layout : tuple + expected layout, (expected number of rows , columns) + figsize : tuple + expected figsize. default is matplotlib default + """ + from pandas.plotting._matplotlib.tools import flatten_axes + + if figsize is None: + figsize = (6.4, 4.8) + visible_axes = _flatten_visible(axes) + + if axes_num is not None: + assert len(visible_axes) == axes_num + for ax in visible_axes: + # check something drawn on visible axes + assert len(ax.get_children()) > 0 + + if layout is not None: + x_set = set() + y_set = set() + for ax in flatten_axes(axes): + # check axes coordinates to estimate layout + points = ax.get_position().get_points() + x_set.add(points[0][0]) + y_set.add(points[0][1]) + result = (len(y_set), len(x_set)) + assert result == layout + + tm.assert_numpy_array_equal( + visible_axes[0].figure.get_size_inches(), + np.array(figsize, dtype=np.float64), + ) + + +def _flatten_visible(axes: Axes | Sequence[Axes]) -> Sequence[Axes]: + """ + Flatten axes, and filter only visible + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + + """ + from pandas.plotting._matplotlib.tools import flatten_axes + + axes_ndarray = flatten_axes(axes) + axes = [ax for ax in axes_ndarray if ax.get_visible()] + return axes + + +def _check_has_errorbars(axes, xerr=0, yerr=0): + """ + Check axes has expected number of errorbars + + Parameters + ---------- + axes : matplotlib Axes object, or its list-like + xerr : number + expected number of x errorbar + yerr : number + expected number of y errorbar + """ + axes = _flatten_visible(axes) + for ax in axes: + containers = ax.containers + xerr_count = 0 + yerr_count = 0 + for c in containers: + has_xerr = getattr(c, "has_xerr", False) + has_yerr = getattr(c, "has_yerr", False) + if has_xerr: + xerr_count += 1 + if has_yerr: + yerr_count += 1 + assert xerr == xerr_count + assert yerr == yerr_count + + +def _check_box_return_type( + returned, return_type, expected_keys=None, check_ax_title=True +): + """ + Check box returned type is correct + + Parameters + ---------- + returned : object to be tested, returned from boxplot + return_type : str + return_type passed to boxplot + expected_keys : list-like, optional + group labels in subplot case. If not passed, + the function checks assuming boxplot uses single ax + check_ax_title : bool + Whether to check the ax.title is the same as expected_key + Intended to be checked by calling from ``boxplot``. + Normal ``plot`` doesn't attach ``ax.title``, it must be disabled. + """ + from matplotlib.axes import Axes + + types = {"dict": dict, "axes": Axes, "both": tuple} + if expected_keys is None: + # should be fixed when the returning default is changed + if return_type is None: + return_type = "dict" + + assert isinstance(returned, types[return_type]) + if return_type == "both": + assert isinstance(returned.ax, Axes) + assert isinstance(returned.lines, dict) + else: + # should be fixed when the returning default is changed + if return_type is None: + for r in _flatten_visible(returned): + assert isinstance(r, Axes) + return + + assert isinstance(returned, Series) + + assert sorted(returned.keys()) == sorted(expected_keys) + for key, value in returned.items(): + assert isinstance(value, types[return_type]) + # check returned dict has correct mapping + if return_type == "axes": + if check_ax_title: + assert value.get_title() == key + elif return_type == "both": + if check_ax_title: + assert value.ax.get_title() == key + assert isinstance(value.ax, Axes) + assert isinstance(value.lines, dict) + elif return_type == "dict": + line = value["medians"][0] + axes = line.axes + if check_ax_title: + assert axes.get_title() == key + else: + raise AssertionError + + +def _check_grid_settings(obj, kinds, kws={}): + # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792 + + import matplotlib as mpl + + def is_grid_on(): + xticks = mpl.pyplot.gca().xaxis.get_major_ticks() + yticks = mpl.pyplot.gca().yaxis.get_major_ticks() + xoff = all(not g.gridline.get_visible() for g in xticks) + yoff = all(not g.gridline.get_visible() for g in yticks) + + return not (xoff and yoff) + + spndx = 1 + for kind in kinds: + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) + spndx += 1 + mpl.rc("axes", grid=False) + obj.plot(kind=kind, **kws) + assert not is_grid_on() + mpl.pyplot.clf() + + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) + spndx += 1 + mpl.rc("axes", grid=True) + obj.plot(kind=kind, grid=False, **kws) + assert not is_grid_on() + mpl.pyplot.clf() + + if kind not in ["pie", "hexbin", "scatter"]: + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) + spndx += 1 + mpl.rc("axes", grid=True) + obj.plot(kind=kind, **kws) + assert is_grid_on() + mpl.pyplot.clf() + + mpl.pyplot.subplot(1, 4 * len(kinds), spndx) + spndx += 1 + mpl.rc("axes", grid=False) + obj.plot(kind=kind, grid=True, **kws) + assert is_grid_on() + mpl.pyplot.clf() + + +def _unpack_cycler(rcParams, field="color"): + """ + Auxiliary function for correctly unpacking cycler after MPL >= 1.5 + """ + return [v[field] for v in rcParams["axes.prop_cycle"]] + + +def get_x_axis(ax): + return ax._shared_axes["x"] + + +def get_y_axis(ax): + return ax._shared_axes["y"] + + +def _check_plot_works(f, default_axes=False, **kwargs): + """ + Create plot and ensure that plot return object is valid. + + Parameters + ---------- + f : func + Plotting function. + default_axes : bool, optional + If False (default): + - If `ax` not in `kwargs`, then create subplot(211) and plot there + - Create new subplot(212) and plot there as well + - Mind special corner case for bootstrap_plot (see `_gen_two_subplots`) + If True: + - Simply run plotting function with kwargs provided + - All required axes instances will be created automatically + - It is recommended to use it when the plotting function + creates multiple axes itself. It helps avoid warnings like + 'UserWarning: To output multiple subplots, + the figure containing the passed axes is being cleared' + **kwargs + Keyword arguments passed to the plotting function. + + Returns + ------- + Plot object returned by the last plotting. + """ + import matplotlib.pyplot as plt + + if default_axes: + gen_plots = _gen_default_plot + else: + gen_plots = _gen_two_subplots + + ret = None + try: + fig = kwargs.get("figure", plt.gcf()) + plt.clf() + + for ret in gen_plots(f, fig, **kwargs): + tm.assert_is_valid_plot_return_object(ret) + + finally: + plt.close(fig) + + return ret + + +def _gen_default_plot(f, fig, **kwargs): + """ + Create plot in a default way. + """ + yield f(**kwargs) + + +def _gen_two_subplots(f, fig, **kwargs): + """ + Create plot on two subplots forcefully created. + """ + if "ax" not in kwargs: + fig.add_subplot(211) + yield f(**kwargs) + + if f is pd.plotting.bootstrap_plot: + assert "ax" not in kwargs + else: + kwargs["ax"] = fig.add_subplot(212) + yield f(**kwargs) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/conftest.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..d688bbd47595c2ec6451bd9ddf7c916275013384 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/conftest.py @@ -0,0 +1,56 @@ +import gc + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + to_datetime, +) + + +@pytest.fixture(autouse=True) +def mpl_cleanup(): + # matplotlib/testing/decorators.py#L24 + # 1) Resets units registry + # 2) Resets rc_context + # 3) Closes all figures + mpl = pytest.importorskip("matplotlib") + mpl_units = pytest.importorskip("matplotlib.units") + plt = pytest.importorskip("matplotlib.pyplot") + orig_units_registry = mpl_units.registry.copy() + with mpl.rc_context(): + mpl.use("template") + yield + mpl_units.registry.clear() + mpl_units.registry.update(orig_units_registry) + plt.close("all") + # https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#garbage-collection-is-no-longer-run-on-figure-close # noqa: E501 + gc.collect(1) + + +@pytest.fixture +def hist_df(): + n = 50 + rng = np.random.default_rng(10) + gender = rng.choice(["Male", "Female"], size=n) + classroom = rng.choice(["A", "B", "C"], size=n) + + hist_df = DataFrame( + { + "gender": gender, + "classroom": classroom, + "height": rng.normal(66, 4, size=n), + "weight": rng.normal(161, 32, size=n), + "category": rng.integers(4, size=n), + "datetime": to_datetime( + rng.integers( + 812419200000000000, + 819331200000000000, + size=n, + dtype=np.int64, + ) + ), + } + ) + return hist_df diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_backend.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..8a8643415ae12f96bbbd87ed85ff74f8813b07e4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_backend.py @@ -0,0 +1,98 @@ +import sys +import types + +import pytest + +import pandas.util._test_decorators as td + +import pandas + + +@pytest.fixture +def dummy_backend(): + db = types.ModuleType("pandas_dummy_backend") + setattr(db, "plot", lambda *args, **kwargs: "used_dummy") + return db + + +@pytest.fixture +def restore_backend(): + """Restore the plotting backend to matplotlib""" + with pandas.option_context("plotting.backend", "matplotlib"): + yield + + +def test_backend_is_not_module(): + msg = "Could not find plotting backend 'not_an_existing_module'." + with pytest.raises(ValueError, match=msg): + pandas.set_option("plotting.backend", "not_an_existing_module") + + assert pandas.options.plotting.backend == "matplotlib" + + +def test_backend_is_correct(monkeypatch, restore_backend, dummy_backend): + monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) + + pandas.set_option("plotting.backend", "pandas_dummy_backend") + assert pandas.get_option("plotting.backend") == "pandas_dummy_backend" + assert ( + pandas.plotting._core._get_plot_backend("pandas_dummy_backend") is dummy_backend + ) + + +def test_backend_can_be_set_in_plot_call(monkeypatch, restore_backend, dummy_backend): + monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) + df = pandas.DataFrame([1, 2, 3]) + + assert pandas.get_option("plotting.backend") == "matplotlib" + assert df.plot(backend="pandas_dummy_backend") == "used_dummy" + + +def test_register_entrypoint(restore_backend, tmp_path, monkeypatch, dummy_backend): + monkeypatch.syspath_prepend(tmp_path) + monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) + + dist_info = tmp_path / "my_backend-0.0.0.dist-info" + dist_info.mkdir() + # entry_point name should not match module name - otherwise pandas will + # fall back to backend lookup by module name + (dist_info / "entry_points.txt").write_bytes( + b"[pandas_plotting_backends]\nmy_ep_backend = pandas_dummy_backend\n" + ) + + assert pandas.plotting._core._get_plot_backend("my_ep_backend") is dummy_backend + + with pandas.option_context("plotting.backend", "my_ep_backend"): + assert pandas.plotting._core._get_plot_backend() is dummy_backend + + +def test_setting_backend_without_plot_raises(monkeypatch): + # GH-28163 + module = types.ModuleType("pandas_plot_backend") + monkeypatch.setitem(sys.modules, "pandas_plot_backend", module) + + assert pandas.options.plotting.backend == "matplotlib" + with pytest.raises( + ValueError, match="Could not find plotting backend 'pandas_plot_backend'." + ): + pandas.set_option("plotting.backend", "pandas_plot_backend") + + assert pandas.options.plotting.backend == "matplotlib" + + +@td.skip_if_installed("matplotlib") +def test_no_matplotlib_ok(): + msg = ( + 'matplotlib is required for plotting when the default backend "matplotlib" is ' + "selected." + ) + with pytest.raises(ImportError, match=msg): + pandas.plotting._core._get_plot_backend("matplotlib") + + +def test_extra_kinds_ok(monkeypatch, restore_backend, dummy_backend): + # https://github.com/pandas-dev/pandas/pull/28647 + monkeypatch.setitem(sys.modules, "pandas_dummy_backend", dummy_backend) + pandas.set_option("plotting.backend", "pandas_dummy_backend") + df = pandas.DataFrame({"A": [1, 2, 3]}) + df.plot(kind="not a real kind") diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_boxplot_method.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_boxplot_method.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b03a34086c03c01d7fa6cd4b3158a444d17e09 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_boxplot_method.py @@ -0,0 +1,786 @@ +""" Test cases for .boxplot method """ + +from __future__ import annotations + +import itertools +import string + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + MultiIndex, + Series, + date_range, + plotting, + timedelta_range, +) +import pandas._testing as tm +from pandas.tests.plotting.common import ( + _check_axes_shape, + _check_box_return_type, + _check_plot_works, + _check_ticks_props, + _check_visible, +) +from pandas.util.version import Version + +from pandas.io.formats.printing import pprint_thing + +mpl = pytest.importorskip("matplotlib") +plt = pytest.importorskip("matplotlib.pyplot") + + +def _check_ax_limits(col, ax): + y_min, y_max = ax.get_ylim() + assert y_min <= col.min() + assert y_max >= col.max() + + +if Version(mpl.__version__) < Version("3.10"): + verts: list[dict[str, bool | str]] = [{"vert": False}, {"vert": True}] +else: + verts = [{"orientation": "horizontal"}, {"orientation": "vertical"}] + + +@pytest.fixture(params=verts) +def vert(request): + return request.param + + +class TestDataFramePlots: + def test_stacked_boxplot_set_axis(self): + # GH2980 + import matplotlib.pyplot as plt + + n = 80 + df = DataFrame( + { + "Clinical": np.random.default_rng(2).choice([0, 1, 2, 3], n), + "Confirmed": np.random.default_rng(2).choice([0, 1, 2, 3], n), + "Discarded": np.random.default_rng(2).choice([0, 1, 2, 3], n), + }, + index=np.arange(0, n), + ) + ax = df.plot(kind="bar", stacked=True) + assert [int(x.get_text()) for x in ax.get_xticklabels()] == df.index.to_list() + ax.set_xticks(np.arange(0, 80, 10)) + plt.draw() # Update changes + assert [int(x.get_text()) for x in ax.get_xticklabels()] == list( + np.arange(0, 80, 10) + ) + + @pytest.mark.slow + @pytest.mark.parametrize( + "kwargs, warn", + [ + [{"return_type": "dict"}, None], + [{"column": ["one", "two"]}, None], + [{"column": ["one", "two"], "by": "indic"}, UserWarning], + [{"column": ["one"], "by": ["indic", "indic2"]}, None], + [{"by": "indic"}, UserWarning], + [{"by": ["indic", "indic2"]}, UserWarning], + [{"notch": 1}, None], + [{"by": "indic", "notch": 1}, UserWarning], + ], + ) + def test_boxplot_legacy1(self, kwargs, warn): + df = DataFrame( + np.random.default_rng(2).standard_normal((6, 4)), + index=list(string.ascii_letters[:6]), + columns=["one", "two", "three", "four"], + ) + df["indic"] = ["foo", "bar"] * 3 + df["indic2"] = ["foo", "bar", "foo"] * 2 + + # _check_plot_works can add an ax so catch warning. see GH #13188 + with tm.assert_produces_warning(warn, check_stacklevel=False): + _check_plot_works(df.boxplot, **kwargs) + + def test_boxplot_legacy1_series(self): + ser = Series(np.random.default_rng(2).standard_normal(6)) + _check_plot_works(plotting._core.boxplot, data=ser, return_type="dict") + + def test_boxplot_legacy2(self): + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"] + ) + df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) + df["Y"] = Series(["A"] * 10) + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + _check_plot_works(df.boxplot, by="X") + + def test_boxplot_legacy2_with_ax(self): + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"] + ) + df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) + df["Y"] = Series(["A"] * 10) + # When ax is supplied and required number of axes is 1, + # passed ax should be used: + _, ax = mpl.pyplot.subplots() + axes = df.boxplot("Col1", by="X", ax=ax) + ax_axes = ax.axes + assert ax_axes is axes + + def test_boxplot_legacy2_with_ax_return_type(self): + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"] + ) + df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) + df["Y"] = Series(["A"] * 10) + fig, ax = mpl.pyplot.subplots() + axes = df.groupby("Y").boxplot(ax=ax, return_type="axes") + ax_axes = ax.axes + assert ax_axes is axes["A"] + + def test_boxplot_legacy2_with_multi_col(self): + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"] + ) + df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) + df["Y"] = Series(["A"] * 10) + # Multiple columns with an ax argument should use same figure + fig, ax = mpl.pyplot.subplots() + with tm.assert_produces_warning(UserWarning): + axes = df.boxplot( + column=["Col1", "Col2"], by="X", ax=ax, return_type="axes" + ) + assert axes["Col1"].get_figure() is fig + + def test_boxplot_legacy2_by_none(self): + df = DataFrame( + np.random.default_rng(2).random((10, 2)), columns=["Col1", "Col2"] + ) + df["X"] = Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"]) + df["Y"] = Series(["A"] * 10) + # When by is None, check that all relevant lines are present in the + # dict + _, ax = mpl.pyplot.subplots() + d = df.boxplot(ax=ax, return_type="dict") + lines = list(itertools.chain.from_iterable(d.values())) + assert len(ax.get_lines()) == len(lines) + + def test_boxplot_return_type_none(self, hist_df): + # GH 12216; return_type=None & by=None -> axes + result = hist_df.boxplot() + assert isinstance(result, mpl.pyplot.Axes) + + def test_boxplot_return_type_legacy(self): + # API change in https://github.com/pandas-dev/pandas/pull/7096 + + df = DataFrame( + np.random.default_rng(2).standard_normal((6, 4)), + index=list(string.ascii_letters[:6]), + columns=["one", "two", "three", "four"], + ) + msg = "return_type must be {'axes', 'dict', 'both'}" + with pytest.raises(ValueError, match=msg): + df.boxplot(return_type="NOT_A_TYPE") + + result = df.boxplot() + _check_box_return_type(result, "axes") + + @pytest.mark.parametrize("return_type", ["dict", "axes", "both"]) + def test_boxplot_return_type_legacy_return_type(self, return_type): + # API change in https://github.com/pandas-dev/pandas/pull/7096 + + df = DataFrame( + np.random.default_rng(2).standard_normal((6, 4)), + index=list(string.ascii_letters[:6]), + columns=["one", "two", "three", "four"], + ) + with tm.assert_produces_warning(False): + result = df.boxplot(return_type=return_type) + _check_box_return_type(result, return_type) + + def test_boxplot_axis_limits(self, hist_df): + df = hist_df.copy() + df["age"] = np.random.default_rng(2).integers(1, 20, df.shape[0]) + # One full row + height_ax, weight_ax = df.boxplot(["height", "weight"], by="category") + _check_ax_limits(df["height"], height_ax) + _check_ax_limits(df["weight"], weight_ax) + assert weight_ax._sharey == height_ax + + def test_boxplot_axis_limits_two_rows(self, hist_df): + df = hist_df.copy() + df["age"] = np.random.default_rng(2).integers(1, 20, df.shape[0]) + # Two rows, one partial + p = df.boxplot(["height", "weight", "age"], by="category") + height_ax, weight_ax, age_ax = p[0, 0], p[0, 1], p[1, 0] + dummy_ax = p[1, 1] + + _check_ax_limits(df["height"], height_ax) + _check_ax_limits(df["weight"], weight_ax) + _check_ax_limits(df["age"], age_ax) + assert weight_ax._sharey == height_ax + assert age_ax._sharey == height_ax + assert dummy_ax._sharey is None + + def test_boxplot_empty_column(self): + df = DataFrame(np.random.default_rng(2).standard_normal((20, 4))) + df.loc[:, 0] = np.nan + _check_plot_works(df.boxplot, return_type="axes") + + def test_figsize(self): + df = DataFrame( + np.random.default_rng(2).random((10, 5)), columns=["A", "B", "C", "D", "E"] + ) + result = df.boxplot(return_type="axes", figsize=(12, 8)) + assert result.figure.bbox_inches.width == 12 + assert result.figure.bbox_inches.height == 8 + + def test_fontsize(self): + df = DataFrame({"a": [1, 2, 3, 4, 5, 6]}) + _check_ticks_props(df.boxplot("a", fontsize=16), xlabelsize=16, ylabelsize=16) + + def test_boxplot_numeric_data(self): + # GH 22799 + df = DataFrame( + { + "a": date_range("2012-01-01", periods=100), + "b": np.random.default_rng(2).standard_normal(100), + "c": np.random.default_rng(2).standard_normal(100) + 2, + "d": date_range("2012-01-01", periods=100).astype(str), + "e": date_range("2012-01-01", periods=100, tz="UTC"), + "f": timedelta_range("1 days", periods=100), + } + ) + ax = df.plot(kind="box") + assert [x.get_text() for x in ax.get_xticklabels()] == ["b", "c"] + + @pytest.mark.parametrize( + "colors_kwd, expected", + [ + ( + {"boxes": "r", "whiskers": "b", "medians": "g", "caps": "c"}, + {"boxes": "r", "whiskers": "b", "medians": "g", "caps": "c"}, + ), + ({"boxes": "r"}, {"boxes": "r"}), + ("r", {"boxes": "r", "whiskers": "r", "medians": "r", "caps": "r"}), + ], + ) + def test_color_kwd(self, colors_kwd, expected): + # GH: 26214 + df = DataFrame(np.random.default_rng(2).random((10, 2))) + result = df.boxplot(color=colors_kwd, return_type="dict") + for k, v in expected.items(): + assert result[k][0].get_color() == v + + @pytest.mark.parametrize( + "scheme,expected", + [ + ( + "dark_background", + { + "boxes": "#8dd3c7", + "whiskers": "#8dd3c7", + "medians": "#bfbbd9", + "caps": "#8dd3c7", + }, + ), + ( + "default", + { + "boxes": "#1f77b4", + "whiskers": "#1f77b4", + "medians": "#2ca02c", + "caps": "#1f77b4", + }, + ), + ], + ) + def test_colors_in_theme(self, scheme, expected): + # GH: 40769 + df = DataFrame(np.random.default_rng(2).random((10, 2))) + import matplotlib.pyplot as plt + + plt.style.use(scheme) + result = df.plot.box(return_type="dict") + for k, v in expected.items(): + assert result[k][0].get_color() == v + + @pytest.mark.parametrize( + "dict_colors, msg", + [({"boxes": "r", "invalid_key": "r"}, "invalid key 'invalid_key'")], + ) + def test_color_kwd_errors(self, dict_colors, msg): + # GH: 26214 + df = DataFrame(np.random.default_rng(2).random((10, 2))) + with pytest.raises(ValueError, match=msg): + df.boxplot(color=dict_colors, return_type="dict") + + @pytest.mark.parametrize( + "props, expected", + [ + ("boxprops", "boxes"), + ("whiskerprops", "whiskers"), + ("capprops", "caps"), + ("medianprops", "medians"), + ], + ) + def test_specified_props_kwd(self, props, expected): + # GH 30346 + df = DataFrame({k: np.random.default_rng(2).random(10) for k in "ABC"}) + kwd = {props: {"color": "C1"}} + result = df.boxplot(return_type="dict", **kwd) + + assert result[expected][0].get_color() == "C1" + + @pytest.mark.filterwarnings("ignore:set_ticklabels:UserWarning") + def test_plot_xlabel_ylabel(self, vert): + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(10), + "b": np.random.default_rng(2).standard_normal(10), + "group": np.random.default_rng(2).choice(["group1", "group2"], 10), + } + ) + xlabel, ylabel = "x", "y" + ax = df.plot(kind="box", xlabel=xlabel, ylabel=ylabel, **vert) + assert ax.get_xlabel() == xlabel + assert ax.get_ylabel() == ylabel + + @pytest.mark.filterwarnings("ignore:set_ticklabels:UserWarning") + def test_plot_box(self, vert): + # GH 54941 + rng = np.random.default_rng(2) + df1 = DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list("ABCD")) + df2 = DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list("ABCD")) + + xlabel, ylabel = "x", "y" + _, axs = plt.subplots(ncols=2, figsize=(10, 7), sharey=True) + df1.plot.box(ax=axs[0], xlabel=xlabel, ylabel=ylabel, **vert) + df2.plot.box(ax=axs[1], xlabel=xlabel, ylabel=ylabel, **vert) + for ax in axs: + assert ax.get_xlabel() == xlabel + assert ax.get_ylabel() == ylabel + mpl.pyplot.close() + + @pytest.mark.filterwarnings("ignore:set_ticklabels:UserWarning") + def test_boxplot_xlabel_ylabel(self, vert): + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(10), + "b": np.random.default_rng(2).standard_normal(10), + "group": np.random.default_rng(2).choice(["group1", "group2"], 10), + } + ) + xlabel, ylabel = "x", "y" + ax = df.boxplot(xlabel=xlabel, ylabel=ylabel, **vert) + assert ax.get_xlabel() == xlabel + assert ax.get_ylabel() == ylabel + + @pytest.mark.filterwarnings("ignore:set_ticklabels:UserWarning") + def test_boxplot_group_xlabel_ylabel(self, vert): + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(10), + "b": np.random.default_rng(2).standard_normal(10), + "group": np.random.default_rng(2).choice(["group1", "group2"], 10), + } + ) + xlabel, ylabel = "x", "y" + ax = df.boxplot(by="group", xlabel=xlabel, ylabel=ylabel, **vert) + for subplot in ax: + assert subplot.get_xlabel() == xlabel + assert subplot.get_ylabel() == ylabel + mpl.pyplot.close() + + @pytest.mark.filterwarnings("ignore:set_ticklabels:UserWarning") + def test_boxplot_group_no_xlabel_ylabel(self, vert, request): + if Version(mpl.__version__) >= Version("3.10") and vert == { + "orientation": "horizontal" + }: + request.applymarker( + pytest.mark.xfail(reason=f"{vert} fails starting with matplotlib 3.10") + ) + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(10), + "b": np.random.default_rng(2).standard_normal(10), + "group": np.random.default_rng(2).choice(["group1", "group2"], 10), + } + ) + ax = df.boxplot(by="group", **vert) + for subplot in ax: + target_label = ( + subplot.get_xlabel() + if vert == {"vert": True} # noqa: PLR1714 + or vert == {"orientation": "vertical"} + else subplot.get_ylabel() + ) + assert target_label == pprint_thing(["group"]) + mpl.pyplot.close() + + +class TestDataFrameGroupByPlots: + def test_boxplot_legacy1(self, hist_df): + grouped = hist_df.groupby(by="gender") + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works(grouped.boxplot, return_type="axes") + _check_axes_shape(list(axes.values), axes_num=2, layout=(1, 2)) + + def test_boxplot_legacy1_return_type(self, hist_df): + grouped = hist_df.groupby(by="gender") + axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes") + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) + + @pytest.mark.slow + def test_boxplot_legacy2(self): + tuples = zip(string.ascii_letters[:10], range(10)) + df = DataFrame( + np.random.default_rng(2).random((10, 3)), + index=MultiIndex.from_tuples(tuples), + ) + grouped = df.groupby(level=1) + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works(grouped.boxplot, return_type="axes") + _check_axes_shape(list(axes.values), axes_num=10, layout=(4, 3)) + + @pytest.mark.slow + def test_boxplot_legacy2_return_type(self): + tuples = zip(string.ascii_letters[:10], range(10)) + df = DataFrame( + np.random.default_rng(2).random((10, 3)), + index=MultiIndex.from_tuples(tuples), + ) + grouped = df.groupby(level=1) + axes = _check_plot_works(grouped.boxplot, subplots=False, return_type="axes") + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) + + @pytest.mark.parametrize( + "subplots, warn, axes_num, layout", + [[True, UserWarning, 3, (2, 2)], [False, None, 1, (1, 1)]], + ) + def test_boxplot_legacy3(self, subplots, warn, axes_num, layout): + tuples = zip(string.ascii_letters[:10], range(10)) + df = DataFrame( + np.random.default_rng(2).random((10, 3)), + index=MultiIndex.from_tuples(tuples), + ) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = df.unstack(level=1).groupby(level=0, axis=1) + with tm.assert_produces_warning(warn, check_stacklevel=False): + axes = _check_plot_works( + grouped.boxplot, subplots=subplots, return_type="axes" + ) + _check_axes_shape(axes, axes_num=axes_num, layout=layout) + + def test_grouped_plot_fignums(self): + n = 10 + weight = Series(np.random.default_rng(2).normal(166, 20, size=n)) + height = Series(np.random.default_rng(2).normal(60, 10, size=n)) + gender = np.random.default_rng(2).choice(["male", "female"], size=n) + df = DataFrame({"height": height, "weight": weight, "gender": gender}) + gb = df.groupby("gender") + + res = gb.plot() + assert len(mpl.pyplot.get_fignums()) == 2 + assert len(res) == 2 + plt.close("all") + + res = gb.boxplot(return_type="axes") + assert len(mpl.pyplot.get_fignums()) == 1 + assert len(res) == 2 + + def test_grouped_plot_fignums_excluded_col(self): + n = 10 + weight = Series(np.random.default_rng(2).normal(166, 20, size=n)) + height = Series(np.random.default_rng(2).normal(60, 10, size=n)) + gender = np.random.default_rng(2).choice(["male", "female"], size=n) + df = DataFrame({"height": height, "weight": weight, "gender": gender}) + # now works with GH 5610 as gender is excluded + df.groupby("gender").hist() + + @pytest.mark.slow + def test_grouped_box_return_type(self, hist_df): + df = hist_df + + # old style: return_type=None + result = df.boxplot(by="gender") + assert isinstance(result, np.ndarray) + _check_box_return_type( + result, None, expected_keys=["height", "weight", "category"] + ) + + @pytest.mark.slow + def test_grouped_box_return_type_groupby(self, hist_df): + df = hist_df + # now for groupby + result = df.groupby("gender").boxplot(return_type="dict") + _check_box_return_type(result, "dict", expected_keys=["Male", "Female"]) + + @pytest.mark.slow + @pytest.mark.parametrize("return_type", ["dict", "axes", "both"]) + def test_grouped_box_return_type_arg(self, hist_df, return_type): + df = hist_df + + returned = df.groupby("classroom").boxplot(return_type=return_type) + _check_box_return_type(returned, return_type, expected_keys=["A", "B", "C"]) + + returned = df.boxplot(by="classroom", return_type=return_type) + _check_box_return_type( + returned, return_type, expected_keys=["height", "weight", "category"] + ) + + @pytest.mark.slow + @pytest.mark.parametrize("return_type", ["dict", "axes", "both"]) + def test_grouped_box_return_type_arg_duplcate_cats(self, return_type): + columns2 = "X B C D A".split() + df2 = DataFrame( + np.random.default_rng(2).standard_normal((6, 5)), columns=columns2 + ) + categories2 = "A B".split() + df2["category"] = categories2 * 3 + + returned = df2.groupby("category").boxplot(return_type=return_type) + _check_box_return_type(returned, return_type, expected_keys=categories2) + + returned = df2.boxplot(by="category", return_type=return_type) + _check_box_return_type(returned, return_type, expected_keys=columns2) + + @pytest.mark.slow + def test_grouped_box_layout_too_small(self, hist_df): + df = hist_df + + msg = "Layout of 1x1 must be larger than required size 2" + with pytest.raises(ValueError, match=msg): + df.boxplot(column=["weight", "height"], by=df.gender, layout=(1, 1)) + + @pytest.mark.slow + def test_grouped_box_layout_needs_by(self, hist_df): + df = hist_df + msg = "The 'layout' keyword is not supported when 'by' is None" + with pytest.raises(ValueError, match=msg): + df.boxplot( + column=["height", "weight", "category"], + layout=(2, 1), + return_type="dict", + ) + + @pytest.mark.slow + def test_grouped_box_layout_positive_layout(self, hist_df): + df = hist_df + msg = "At least one dimension of layout must be positive" + with pytest.raises(ValueError, match=msg): + df.boxplot(column=["weight", "height"], by=df.gender, layout=(-1, -1)) + + @pytest.mark.slow + @pytest.mark.parametrize( + "gb_key, axes_num, rows", + [["gender", 2, 1], ["category", 4, 2], ["classroom", 3, 2]], + ) + def test_grouped_box_layout_positive_layout_axes( + self, hist_df, gb_key, axes_num, rows + ): + df = hist_df + # _check_plot_works adds an ax so catch warning. see GH #13188 GH 6769 + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + _check_plot_works( + df.groupby(gb_key).boxplot, column="height", return_type="dict" + ) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=axes_num, layout=(rows, 2)) + + @pytest.mark.slow + @pytest.mark.parametrize( + "col, visible", [["height", False], ["weight", True], ["category", True]] + ) + def test_grouped_box_layout_visible(self, hist_df, col, visible): + df = hist_df + # GH 5897 + axes = df.boxplot( + column=["height", "weight", "category"], by="gender", return_type="axes" + ) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(2, 2)) + ax = axes[col] + _check_visible(ax.get_xticklabels(), visible=visible) + _check_visible([ax.xaxis.get_label()], visible=visible) + + @pytest.mark.slow + def test_grouped_box_layout_shape(self, hist_df): + df = hist_df + df.groupby("classroom").boxplot( + column=["height", "weight", "category"], return_type="dict" + ) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(2, 2)) + + @pytest.mark.slow + @pytest.mark.parametrize("cols", [2, -1]) + def test_grouped_box_layout_works(self, hist_df, cols): + df = hist_df + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + _check_plot_works( + df.groupby("category").boxplot, + column="height", + layout=(3, cols), + return_type="dict", + ) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(3, 2)) + + @pytest.mark.slow + @pytest.mark.parametrize("rows, res", [[4, 4], [-1, 3]]) + def test_grouped_box_layout_axes_shape_rows(self, hist_df, rows, res): + df = hist_df + df.boxplot( + column=["height", "weight", "category"], by="gender", layout=(rows, 1) + ) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(res, 1)) + + @pytest.mark.slow + @pytest.mark.parametrize("cols, res", [[4, 4], [-1, 3]]) + def test_grouped_box_layout_axes_shape_cols_groupby(self, hist_df, cols, res): + df = hist_df + df.groupby("classroom").boxplot( + column=["height", "weight", "category"], + layout=(1, cols), + return_type="dict", + ) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=3, layout=(1, res)) + + @pytest.mark.slow + def test_grouped_box_multiple_axes(self, hist_df): + # GH 6970, GH 7069 + df = hist_df + + # check warning to ignore sharex / sharey + # this check should be done in the first function which + # passes multiple axes to plot, hist or boxplot + # location should be changed if other test is added + # which has earlier alphabetical order + with tm.assert_produces_warning(UserWarning): + _, axes = mpl.pyplot.subplots(2, 2) + df.groupby("category").boxplot(column="height", return_type="axes", ax=axes) + _check_axes_shape(mpl.pyplot.gcf().axes, axes_num=4, layout=(2, 2)) + + @pytest.mark.slow + def test_grouped_box_multiple_axes_on_fig(self, hist_df): + # GH 6970, GH 7069 + df = hist_df + fig, axes = mpl.pyplot.subplots(2, 3) + with tm.assert_produces_warning(UserWarning): + returned = df.boxplot( + column=["height", "weight", "category"], + by="gender", + return_type="axes", + ax=axes[0], + ) + returned = np.array(list(returned.values)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) + tm.assert_numpy_array_equal(returned, axes[0]) + assert returned[0].figure is fig + + # draw on second row + with tm.assert_produces_warning(UserWarning): + returned = df.groupby("classroom").boxplot( + column=["height", "weight", "category"], return_type="axes", ax=axes[1] + ) + returned = np.array(list(returned.values)) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) + tm.assert_numpy_array_equal(returned, axes[1]) + assert returned[0].figure is fig + + @pytest.mark.slow + def test_grouped_box_multiple_axes_ax_error(self, hist_df): + # GH 6970, GH 7069 + df = hist_df + msg = "The number of passed axes must be 3, the same as the output plot" + with pytest.raises(ValueError, match=msg): + fig, axes = mpl.pyplot.subplots(2, 3) + # pass different number of axes from required + with tm.assert_produces_warning(UserWarning): + axes = df.groupby("classroom").boxplot(ax=axes) + + def test_fontsize(self): + df = DataFrame({"a": [1, 2, 3, 4, 5, 6], "b": [0, 0, 0, 1, 1, 1]}) + _check_ticks_props( + df.boxplot("a", by="b", fontsize=16), xlabelsize=16, ylabelsize=16 + ) + + @pytest.mark.parametrize( + "col, expected_xticklabel", + [ + ("v", ["(a, v)", "(b, v)", "(c, v)", "(d, v)", "(e, v)"]), + (["v"], ["(a, v)", "(b, v)", "(c, v)", "(d, v)", "(e, v)"]), + ("v1", ["(a, v1)", "(b, v1)", "(c, v1)", "(d, v1)", "(e, v1)"]), + ( + ["v", "v1"], + [ + "(a, v)", + "(a, v1)", + "(b, v)", + "(b, v1)", + "(c, v)", + "(c, v1)", + "(d, v)", + "(d, v1)", + "(e, v)", + "(e, v1)", + ], + ), + ( + None, + [ + "(a, v)", + "(a, v1)", + "(b, v)", + "(b, v1)", + "(c, v)", + "(c, v1)", + "(d, v)", + "(d, v1)", + "(e, v)", + "(e, v1)", + ], + ), + ], + ) + def test_groupby_boxplot_subplots_false(self, col, expected_xticklabel): + # GH 16748 + df = DataFrame( + { + "cat": np.random.default_rng(2).choice(list("abcde"), 100), + "v": np.random.default_rng(2).random(100), + "v1": np.random.default_rng(2).random(100), + } + ) + grouped = df.groupby("cat") + + axes = _check_plot_works( + grouped.boxplot, subplots=False, column=col, return_type="axes" + ) + + result_xticklabel = [x.get_text() for x in axes.get_xticklabels()] + assert expected_xticklabel == result_xticklabel + + def test_groupby_boxplot_object(self, hist_df): + # GH 43480 + df = hist_df.astype("object") + grouped = df.groupby("gender") + msg = "boxplot method requires numerical columns, nothing to plot" + with pytest.raises(ValueError, match=msg): + _check_plot_works(grouped.boxplot, subplots=False) + + def test_boxplot_multiindex_column(self): + # GH 16748 + arrays = [ + ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + tuples = list(zip(*arrays)) + index = MultiIndex.from_tuples(tuples, names=["first", "second"]) + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 8)), + index=["A", "B", "C"], + columns=index, + ) + + col = [("bar", "one"), ("bar", "two")] + axes = _check_plot_works(df.boxplot, column=col, return_type="axes") + + expected_xticklabel = ["(bar, one)", "(bar, two)"] + result_xticklabel = [x.get_text() for x in axes.get_xticklabels()] + assert expected_xticklabel == result_xticklabel diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_common.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..20daf5935624843af3224f991497f84fa6639a0d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_common.py @@ -0,0 +1,60 @@ +import pytest + +from pandas import DataFrame +from pandas.tests.plotting.common import ( + _check_plot_works, + _check_ticks_props, + _gen_two_subplots, +) + +plt = pytest.importorskip("matplotlib.pyplot") + + +class TestCommon: + def test__check_ticks_props(self): + # GH 34768 + df = DataFrame({"b": [0, 1, 0], "a": [1, 2, 3]}) + ax = _check_plot_works(df.plot, rot=30) + ax.yaxis.set_tick_params(rotation=30) + msg = "expected 0.00000 but got " + with pytest.raises(AssertionError, match=msg): + _check_ticks_props(ax, xrot=0) + with pytest.raises(AssertionError, match=msg): + _check_ticks_props(ax, xlabelsize=0) + with pytest.raises(AssertionError, match=msg): + _check_ticks_props(ax, yrot=0) + with pytest.raises(AssertionError, match=msg): + _check_ticks_props(ax, ylabelsize=0) + + def test__gen_two_subplots_with_ax(self): + fig = plt.gcf() + gen = _gen_two_subplots(f=lambda **kwargs: None, fig=fig, ax="test") + # On the first yield, no subplot should be added since ax was passed + next(gen) + assert fig.get_axes() == [] + # On the second, the one axis should match fig.subplot(2, 1, 2) + next(gen) + axes = fig.get_axes() + assert len(axes) == 1 + subplot_geometry = list(axes[0].get_subplotspec().get_geometry()[:-1]) + subplot_geometry[-1] += 1 + assert subplot_geometry == [2, 1, 2] + + def test_colorbar_layout(self): + fig = plt.figure() + + axes = fig.subplot_mosaic( + """ + AB + CC + """ + ) + + x = [1, 2, 3] + y = [1, 2, 3] + + cs0 = axes["A"].scatter(x, y) + axes["B"].scatter(x, y) + + fig.colorbar(cs0, ax=[axes["A"], axes["B"]], location="right") + DataFrame(x).plot(ax=axes["C"]) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_datetimelike.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_datetimelike.py new file mode 100644 index 0000000000000000000000000000000000000000..6c318402ea226a09fbd4b9278343ef914f8fc83a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_datetimelike.py @@ -0,0 +1,1760 @@ +""" Test cases for time series specific (freq conversion, etc) """ +from datetime import ( + date, + datetime, + time, + timedelta, +) +import pickle + +import numpy as np +import pytest + +from pandas._libs.tslibs import ( + BaseOffset, + to_offset, +) +from pandas._libs.tslibs.dtypes import freq_to_period_freqstr + +from pandas import ( + DataFrame, + Index, + NaT, + Series, + concat, + isna, + to_datetime, +) +import pandas._testing as tm +from pandas.core.indexes.datetimes import ( + DatetimeIndex, + bdate_range, + date_range, +) +from pandas.core.indexes.period import ( + Period, + PeriodIndex, + period_range, +) +from pandas.core.indexes.timedeltas import timedelta_range +from pandas.tests.plotting.common import _check_ticks_props + +from pandas.tseries.offsets import WeekOfMonth + +mpl = pytest.importorskip("matplotlib") + + +class TestTSPlot: + @pytest.mark.filterwarnings("ignore::UserWarning") + def test_ts_plot_with_tz(self, tz_aware_fixture): + # GH2877, GH17173, GH31205, GH31580 + tz = tz_aware_fixture + index = date_range("1/1/2011", periods=2, freq="h", tz=tz) + ts = Series([188.5, 328.25], index=index) + _check_plot_works(ts.plot) + ax = ts.plot() + xdata = next(iter(ax.get_lines())).get_xdata() + # Check first and last points' labels are correct + assert (xdata[0].hour, xdata[0].minute) == (0, 0) + assert (xdata[-1].hour, xdata[-1].minute) == (1, 0) + + def test_fontsize_set_correctly(self): + # For issue #8765 + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 9)), index=range(10) + ) + _, ax = mpl.pyplot.subplots() + df.plot(fontsize=2, ax=ax) + for label in ax.get_xticklabels() + ax.get_yticklabels(): + assert label.get_fontsize() == 2 + + def test_frame_inferred(self): + # inferred freq + idx = date_range("1/1/1987", freq="MS", periods=100) + idx = DatetimeIndex(idx.values, freq=None) + + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx + ) + _check_plot_works(df.plot) + + # axes freq + idx = idx[0:40].union(idx[45:99]) + df2 = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx + ) + _check_plot_works(df2.plot) + + def test_frame_inferred_n_gt_1(self): + # N > 1 + idx = date_range("2008-1-1 00:15:00", freq="15min", periods=10) + idx = DatetimeIndex(idx.values, freq=None) + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx + ) + _check_plot_works(df.plot) + + def test_is_error_nozeroindex(self): + # GH11858 + i = np.array([1, 2, 3]) + a = DataFrame(i, index=i) + _check_plot_works(a.plot, xerr=a) + _check_plot_works(a.plot, yerr=a) + + def test_nonnumeric_exclude(self): + idx = date_range("1/1/1987", freq="YE", periods=3) + df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]}, idx) + + fig, ax = mpl.pyplot.subplots() + df.plot(ax=ax) # it works + assert len(ax.get_lines()) == 1 # B was plotted + mpl.pyplot.close(fig) + + def test_nonnumeric_exclude_error(self): + idx = date_range("1/1/1987", freq="YE", periods=3) + df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]}, idx) + msg = "no numeric data to plot" + with pytest.raises(TypeError, match=msg): + df["A"].plot() + + @pytest.mark.parametrize("freq", ["s", "min", "h", "D", "W", "M", "Q", "Y"]) + def test_tsplot_period(self, freq): + idx = period_range("12/31/1999", freq=freq, periods=100) + ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) + _, ax = mpl.pyplot.subplots() + _check_plot_works(ser.plot, ax=ax) + + @pytest.mark.parametrize( + "freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"] + ) + def test_tsplot_datetime(self, freq): + idx = date_range("12/31/1999", freq=freq, periods=100) + ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) + _, ax = mpl.pyplot.subplots() + _check_plot_works(ser.plot, ax=ax) + + def test_tsplot(self): + ts = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + _, ax = mpl.pyplot.subplots() + ts.plot(style="k", ax=ax) + color = (0.0, 0.0, 0.0, 1) + assert color == ax.get_lines()[0].get_color() + + def test_both_style_and_color(self): + ts = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + msg = ( + "Cannot pass 'style' string with a color symbol and 'color' " + "keyword argument. Please use one or the other or pass 'style' " + "without a color symbol" + ) + with pytest.raises(ValueError, match=msg): + ts.plot(style="b-", color="#000099") + + s = ts.reset_index(drop=True) + with pytest.raises(ValueError, match=msg): + s.plot(style="b-", color="#000099") + + @pytest.mark.parametrize("freq", ["ms", "us"]) + def test_high_freq(self, freq): + _, ax = mpl.pyplot.subplots() + rng = date_range("1/1/2012", periods=100, freq=freq) + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _check_plot_works(ser.plot, ax=ax) + + def test_get_datevalue(self): + from pandas.plotting._matplotlib.converter import get_datevalue + + assert get_datevalue(None, "D") is None + assert get_datevalue(1987, "Y") == 1987 + assert get_datevalue(Period(1987, "Y"), "M") == Period("1987-12", "M").ordinal + assert get_datevalue("1/1/1987", "D") == Period("1987-1-1", "D").ordinal + + def test_ts_plot_format_coord(self): + def check_format_of_first_point(ax, expected_string): + first_line = ax.get_lines()[0] + first_x = first_line.get_xdata()[0].ordinal + first_y = first_line.get_ydata()[0] + assert expected_string == ax.format_coord(first_x, first_y) + + annual = Series(1, index=date_range("2014-01-01", periods=3, freq="YE-DEC")) + _, ax = mpl.pyplot.subplots() + annual.plot(ax=ax) + check_format_of_first_point(ax, "t = 2014 y = 1.000000") + + # note this is added to the annual plot already in existence, and + # changes its freq field + daily = Series(1, index=date_range("2014-01-01", periods=3, freq="D")) + daily.plot(ax=ax) + check_format_of_first_point(ax, "t = 2014-01-01 y = 1.000000") + + @pytest.mark.parametrize("freq", ["s", "min", "h", "D", "W", "M", "Q", "Y"]) + def test_line_plot_period_series(self, freq): + idx = period_range("12/31/1999", freq=freq, periods=100) + ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) + _check_plot_works(ser.plot, ser.index.freq) + + @pytest.mark.parametrize( + "frqncy", ["1s", "3s", "5min", "7h", "4D", "8W", "11M", "3Y"] + ) + def test_line_plot_period_mlt_series(self, frqncy): + # test period index line plot for series with multiples (`mlt`) of the + # frequency (`frqncy`) rule code. tests resolution of issue #14763 + idx = period_range("12/31/1999", freq=frqncy, periods=100) + s = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) + _check_plot_works(s.plot, s.index.freq.rule_code) + + @pytest.mark.parametrize( + "freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"] + ) + def test_line_plot_datetime_series(self, freq): + idx = date_range("12/31/1999", freq=freq, periods=100) + ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) + _check_plot_works(ser.plot, ser.index.freq.rule_code) + + @pytest.mark.parametrize("freq", ["s", "min", "h", "D", "W", "ME", "QE", "YE"]) + def test_line_plot_period_frame(self, freq): + idx = date_range("12/31/1999", freq=freq, periods=100) + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 3)), + index=idx, + columns=["A", "B", "C"], + ) + _check_plot_works(df.plot, df.index.freq) + + @pytest.mark.parametrize( + "frqncy", ["1s", "3s", "5min", "7h", "4D", "8W", "11M", "3Y"] + ) + def test_line_plot_period_mlt_frame(self, frqncy): + # test period index line plot for DataFrames with multiples (`mlt`) + # of the frequency (`frqncy`) rule code. tests resolution of issue + # #14763 + idx = period_range("12/31/1999", freq=frqncy, periods=100) + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 3)), + index=idx, + columns=["A", "B", "C"], + ) + freq = freq_to_period_freqstr(1, df.index.freq.rule_code) + freq = df.index.asfreq(freq).freq + _check_plot_works(df.plot, freq) + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + @pytest.mark.parametrize( + "freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"] + ) + def test_line_plot_datetime_frame(self, freq): + idx = date_range("12/31/1999", freq=freq, periods=100) + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 3)), + index=idx, + columns=["A", "B", "C"], + ) + freq = freq_to_period_freqstr(1, df.index.freq.rule_code) + freq = df.index.to_period(freq).freq + _check_plot_works(df.plot, freq) + + @pytest.mark.parametrize( + "freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"] + ) + def test_line_plot_inferred_freq(self, freq): + idx = date_range("12/31/1999", freq=freq, periods=100) + ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) + ser = Series(ser.values, Index(np.asarray(ser.index))) + _check_plot_works(ser.plot, ser.index.inferred_freq) + + ser = ser.iloc[[0, 3, 5, 6]] + _check_plot_works(ser.plot) + + def test_fake_inferred_business(self): + _, ax = mpl.pyplot.subplots() + rng = date_range("2001-1-1", "2001-1-10") + ts = Series(range(len(rng)), index=rng) + ts = concat([ts[:3], ts[5:]]) + ts.plot(ax=ax) + assert not hasattr(ax, "freq") + + def test_plot_offset_freq(self): + ser = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + _check_plot_works(ser.plot) + + def test_plot_offset_freq_business(self): + dr = date_range("2023-01-01", freq="BQS", periods=10) + ser = Series(np.random.default_rng(2).standard_normal(len(dr)), index=dr) + _check_plot_works(ser.plot) + + def test_plot_multiple_inferred_freq(self): + dr = Index([datetime(2000, 1, 1), datetime(2000, 1, 6), datetime(2000, 1, 11)]) + ser = Series(np.random.default_rng(2).standard_normal(len(dr)), index=dr) + _check_plot_works(ser.plot) + + @pytest.mark.xfail(reason="Api changed in 3.6.0") + def test_uhf(self): + import pandas.plotting._matplotlib.converter as conv + + idx = date_range("2012-6-22 21:59:51.960928", freq="ms", periods=500) + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx + ) + + _, ax = mpl.pyplot.subplots() + df.plot(ax=ax) + axis = ax.get_xaxis() + + tlocs = axis.get_ticklocs() + tlabels = axis.get_ticklabels() + for loc, label in zip(tlocs, tlabels): + xp = conv._from_ordinal(loc).strftime("%H:%M:%S.%f") + rs = str(label.get_text()) + if len(rs): + assert xp == rs + + def test_irreg_hf(self): + idx = date_range("2012-6-22 21:59:51", freq="s", periods=10) + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx + ) + + irreg = df.iloc[[0, 1, 3, 4]] + _, ax = mpl.pyplot.subplots() + irreg.plot(ax=ax) + diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff() + + sec = 1.0 / 24 / 60 / 60 + assert (np.fabs(diffs[1:] - [sec, sec * 2, sec]) < 1e-8).all() + + def test_irreg_hf_object(self): + idx = date_range("2012-6-22 21:59:51", freq="s", periods=10) + df2 = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx + ) + _, ax = mpl.pyplot.subplots() + df2.index = df2.index.astype(object) + df2.plot(ax=ax) + diffs = Series(ax.get_lines()[0].get_xydata()[:, 0]).diff() + sec = 1.0 / 24 / 60 / 60 + assert (np.fabs(diffs[1:] - sec) < 1e-8).all() + + def test_irregular_datetime64_repr_bug(self): + ser = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ) + ser = ser.iloc[[0, 1, 2, 7]] + + _, ax = mpl.pyplot.subplots() + + ret = ser.plot(ax=ax) + assert ret is not None + + for rs, xp in zip(ax.get_lines()[0].get_xdata(), ser.index): + assert rs == xp + + def test_business_freq(self): + bts = Series(range(5), period_range("2020-01-01", periods=5)) + msg = r"PeriodDtype\[B\] is deprecated" + dt = bts.index[0].to_timestamp() + with tm.assert_produces_warning(FutureWarning, match=msg): + bts.index = period_range(start=dt, periods=len(bts), freq="B") + _, ax = mpl.pyplot.subplots() + bts.plot(ax=ax) + assert ax.get_lines()[0].get_xydata()[0, 0] == bts.index[0].ordinal + idx = ax.get_lines()[0].get_xdata() + with tm.assert_produces_warning(FutureWarning, match=msg): + assert PeriodIndex(data=idx).freqstr == "B" + + def test_business_freq_convert(self): + bts = Series( + np.arange(300, dtype=np.float64), + index=date_range("2020-01-01", periods=300, freq="B"), + ).asfreq("BME") + ts = bts.to_period("M") + _, ax = mpl.pyplot.subplots() + bts.plot(ax=ax) + assert ax.get_lines()[0].get_xydata()[0, 0] == ts.index[0].ordinal + idx = ax.get_lines()[0].get_xdata() + assert PeriodIndex(data=idx).freqstr == "M" + + def test_freq_with_no_period_alias(self): + # GH34487 + freq = WeekOfMonth() + bts = Series( + np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10) + ).asfreq(freq) + _, ax = mpl.pyplot.subplots() + bts.plot(ax=ax) + + idx = ax.get_lines()[0].get_xdata() + msg = "freq not specified and cannot be inferred" + with pytest.raises(ValueError, match=msg): + PeriodIndex(data=idx) + + def test_nonzero_base(self): + # GH2571 + idx = date_range("2012-12-20", periods=24, freq="h") + timedelta(minutes=30) + df = DataFrame(np.arange(24), index=idx) + _, ax = mpl.pyplot.subplots() + df.plot(ax=ax) + rs = ax.get_lines()[0].get_xdata() + assert not Index(rs).is_normalized + + def test_dataframe(self): + bts = DataFrame( + { + "a": Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + ) + } + ) + _, ax = mpl.pyplot.subplots() + bts.plot(ax=ax) + idx = ax.get_lines()[0].get_xdata() + tm.assert_index_equal(bts.index.to_period(), PeriodIndex(idx)) + + @pytest.mark.filterwarnings( + "ignore:Period with BDay freq is deprecated:FutureWarning" + ) + @pytest.mark.parametrize( + "obj", + [ + Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + ), + DataFrame( + { + "a": Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + ), + "b": Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + ) + + 1, + } + ), + ], + ) + def test_axis_limits(self, obj): + _, ax = mpl.pyplot.subplots() + obj.plot(ax=ax) + xlim = ax.get_xlim() + ax.set_xlim(xlim[0] - 5, xlim[1] + 10) + result = ax.get_xlim() + assert result[0] == xlim[0] - 5 + assert result[1] == xlim[1] + 10 + + # string + expected = (Period("1/1/2000", ax.freq), Period("4/1/2000", ax.freq)) + ax.set_xlim("1/1/2000", "4/1/2000") + result = ax.get_xlim() + assert int(result[0]) == expected[0].ordinal + assert int(result[1]) == expected[1].ordinal + + # datetime + expected = (Period("1/1/2000", ax.freq), Period("4/1/2000", ax.freq)) + ax.set_xlim(datetime(2000, 1, 1), datetime(2000, 4, 1)) + result = ax.get_xlim() + assert int(result[0]) == expected[0].ordinal + assert int(result[1]) == expected[1].ordinal + fig = ax.get_figure() + mpl.pyplot.close(fig) + + def test_get_finder(self): + import pandas.plotting._matplotlib.converter as conv + + assert conv.get_finder(to_offset("B")) == conv._daily_finder + assert conv.get_finder(to_offset("D")) == conv._daily_finder + assert conv.get_finder(to_offset("ME")) == conv._monthly_finder + assert conv.get_finder(to_offset("QE")) == conv._quarterly_finder + assert conv.get_finder(to_offset("YE")) == conv._annual_finder + assert conv.get_finder(to_offset("W")) == conv._daily_finder + + def test_finder_daily(self): + day_lst = [10, 40, 252, 400, 950, 2750, 10000] + + msg = "Period with BDay freq is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + xpl1 = xpl2 = [Period("1999-1-1", freq="B").ordinal] * len(day_lst) + rs1 = [] + rs2 = [] + for n in day_lst: + rng = bdate_range("1999-1-1", periods=n) + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + xaxis = ax.get_xaxis() + rs1.append(xaxis.get_majorticklocs()[0]) + + vmin, vmax = ax.get_xlim() + ax.set_xlim(vmin + 0.9, vmax) + rs2.append(xaxis.get_majorticklocs()[0]) + mpl.pyplot.close(ax.get_figure()) + + assert rs1 == xpl1 + assert rs2 == xpl2 + + def test_finder_quarterly(self): + yrs = [3.5, 11] + + xpl1 = xpl2 = [Period("1988Q1").ordinal] * len(yrs) + rs1 = [] + rs2 = [] + for n in yrs: + rng = period_range("1987Q2", periods=int(n * 4), freq="Q") + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + xaxis = ax.get_xaxis() + rs1.append(xaxis.get_majorticklocs()[0]) + + (vmin, vmax) = ax.get_xlim() + ax.set_xlim(vmin + 0.9, vmax) + rs2.append(xaxis.get_majorticklocs()[0]) + mpl.pyplot.close(ax.get_figure()) + + assert rs1 == xpl1 + assert rs2 == xpl2 + + def test_finder_monthly(self): + yrs = [1.15, 2.5, 4, 11] + + xpl1 = xpl2 = [Period("Jan 1988").ordinal] * len(yrs) + rs1 = [] + rs2 = [] + for n in yrs: + rng = period_range("1987Q2", periods=int(n * 12), freq="M") + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + xaxis = ax.get_xaxis() + rs1.append(xaxis.get_majorticklocs()[0]) + + vmin, vmax = ax.get_xlim() + ax.set_xlim(vmin + 0.9, vmax) + rs2.append(xaxis.get_majorticklocs()[0]) + mpl.pyplot.close(ax.get_figure()) + + assert rs1 == xpl1 + assert rs2 == xpl2 + + def test_finder_monthly_long(self): + rng = period_range("1988Q1", periods=24 * 12, freq="M") + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + xaxis = ax.get_xaxis() + rs = xaxis.get_majorticklocs()[0] + xp = Period("1989Q1", "M").ordinal + assert rs == xp + + def test_finder_annual(self): + xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170] + xp = [Period(x, freq="Y").ordinal for x in xp] + rs = [] + for nyears in [5, 10, 19, 49, 99, 199, 599, 1001]: + rng = period_range("1987", periods=nyears, freq="Y") + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + xaxis = ax.get_xaxis() + rs.append(xaxis.get_majorticklocs()[0]) + mpl.pyplot.close(ax.get_figure()) + + assert rs == xp + + @pytest.mark.slow + def test_finder_minutely(self): + nminutes = 50 * 24 * 60 + rng = date_range("1/1/1999", freq="Min", periods=nminutes) + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + xaxis = ax.get_xaxis() + rs = xaxis.get_majorticklocs()[0] + xp = Period("1/1/1999", freq="Min").ordinal + + assert rs == xp + + def test_finder_hourly(self): + nhours = 23 + rng = date_range("1/1/1999", freq="h", periods=nhours) + ser = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + xaxis = ax.get_xaxis() + rs = xaxis.get_majorticklocs()[0] + xp = Period("1/1/1999", freq="h").ordinal + + assert rs == xp + + def test_gaps(self): + ts = Series( + np.arange(30, dtype=np.float64), index=date_range("2020-01-01", periods=30) + ) + ts.iloc[5:25] = np.nan + _, ax = mpl.pyplot.subplots() + ts.plot(ax=ax) + lines = ax.get_lines() + assert len(lines) == 1 + line = lines[0] + data = line.get_xydata() + + data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan) + + assert isinstance(data, np.ma.core.MaskedArray) + mask = data.mask + assert mask[5:25, 1].all() + mpl.pyplot.close(ax.get_figure()) + + def test_gaps_irregular(self): + # irregular + ts = Series( + np.arange(30, dtype=np.float64), index=date_range("2020-01-01", periods=30) + ) + ts = ts.iloc[[0, 1, 2, 5, 7, 9, 12, 15, 20]] + ts.iloc[2:5] = np.nan + _, ax = mpl.pyplot.subplots() + ax = ts.plot(ax=ax) + lines = ax.get_lines() + assert len(lines) == 1 + line = lines[0] + data = line.get_xydata() + + data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan) + + assert isinstance(data, np.ma.core.MaskedArray) + mask = data.mask + assert mask[2:5, 1].all() + mpl.pyplot.close(ax.get_figure()) + + def test_gaps_non_ts(self): + # non-ts + idx = [0, 1, 2, 5, 7, 9, 12, 15, 20] + ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) + ser.iloc[2:5] = np.nan + _, ax = mpl.pyplot.subplots() + ser.plot(ax=ax) + lines = ax.get_lines() + assert len(lines) == 1 + line = lines[0] + data = line.get_xydata() + data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan) + + assert isinstance(data, np.ma.core.MaskedArray) + mask = data.mask + assert mask[2:5, 1].all() + + def test_gap_upsample(self): + low = Series( + np.arange(30, dtype=np.float64), index=date_range("2020-01-01", periods=30) + ) + low.iloc[5:25] = np.nan + _, ax = mpl.pyplot.subplots() + low.plot(ax=ax) + + idxh = date_range(low.index[0], low.index[-1], freq="12h") + s = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + s.plot(secondary_y=True) + lines = ax.get_lines() + assert len(lines) == 1 + assert len(ax.right_ax.get_lines()) == 1 + + line = lines[0] + data = line.get_xydata() + data = np.ma.MaskedArray(data, mask=isna(data), fill_value=np.nan) + + assert isinstance(data, np.ma.core.MaskedArray) + mask = data.mask + assert mask[5:25, 1].all() + + def test_secondary_y(self): + ser = Series(np.random.default_rng(2).standard_normal(10)) + fig, _ = mpl.pyplot.subplots() + ax = ser.plot(secondary_y=True) + assert hasattr(ax, "left_ax") + assert not hasattr(ax, "right_ax") + axes = fig.get_axes() + line = ax.get_lines()[0] + xp = Series(line.get_ydata(), line.get_xdata()) + tm.assert_series_equal(ser, xp) + assert ax.get_yaxis().get_ticks_position() == "right" + assert not axes[0].get_yaxis().get_visible() + mpl.pyplot.close(fig) + + def test_secondary_y_yaxis(self): + Series(np.random.default_rng(2).standard_normal(10)) + ser2 = Series(np.random.default_rng(2).standard_normal(10)) + _, ax2 = mpl.pyplot.subplots() + ser2.plot(ax=ax2) + assert ax2.get_yaxis().get_ticks_position() == "left" + mpl.pyplot.close(ax2.get_figure()) + + def test_secondary_both(self): + ser = Series(np.random.default_rng(2).standard_normal(10)) + ser2 = Series(np.random.default_rng(2).standard_normal(10)) + ax = ser2.plot() + ax2 = ser.plot(secondary_y=True) + assert ax.get_yaxis().get_visible() + assert not hasattr(ax, "left_ax") + assert hasattr(ax, "right_ax") + assert hasattr(ax2, "left_ax") + assert not hasattr(ax2, "right_ax") + + def test_secondary_y_ts(self): + idx = date_range("1/1/2000", periods=10) + ser = Series(np.random.default_rng(2).standard_normal(10), idx) + fig, _ = mpl.pyplot.subplots() + ax = ser.plot(secondary_y=True) + assert hasattr(ax, "left_ax") + assert not hasattr(ax, "right_ax") + axes = fig.get_axes() + line = ax.get_lines()[0] + xp = Series(line.get_ydata(), line.get_xdata()).to_timestamp() + tm.assert_series_equal(ser, xp) + assert ax.get_yaxis().get_ticks_position() == "right" + assert not axes[0].get_yaxis().get_visible() + mpl.pyplot.close(fig) + + def test_secondary_y_ts_yaxis(self): + idx = date_range("1/1/2000", periods=10) + ser2 = Series(np.random.default_rng(2).standard_normal(10), idx) + _, ax2 = mpl.pyplot.subplots() + ser2.plot(ax=ax2) + assert ax2.get_yaxis().get_ticks_position() == "left" + mpl.pyplot.close(ax2.get_figure()) + + def test_secondary_y_ts_visible(self): + idx = date_range("1/1/2000", periods=10) + ser2 = Series(np.random.default_rng(2).standard_normal(10), idx) + ax = ser2.plot() + assert ax.get_yaxis().get_visible() + + def test_secondary_kde(self): + pytest.importorskip("scipy") + ser = Series(np.random.default_rng(2).standard_normal(10)) + fig, ax = mpl.pyplot.subplots() + ax = ser.plot(secondary_y=True, kind="density", ax=ax) + assert hasattr(ax, "left_ax") + assert not hasattr(ax, "right_ax") + axes = fig.get_axes() + assert axes[1].get_yaxis().get_ticks_position() == "right" + + def test_secondary_bar(self): + ser = Series(np.random.default_rng(2).standard_normal(10)) + fig, ax = mpl.pyplot.subplots() + ser.plot(secondary_y=True, kind="bar", ax=ax) + axes = fig.get_axes() + assert axes[1].get_yaxis().get_ticks_position() == "right" + + def test_secondary_frame(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), columns=["a", "b", "c"] + ) + axes = df.plot(secondary_y=["a", "c"], subplots=True) + assert axes[0].get_yaxis().get_ticks_position() == "right" + assert axes[1].get_yaxis().get_ticks_position() == "left" + assert axes[2].get_yaxis().get_ticks_position() == "right" + + def test_secondary_bar_frame(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 3)), columns=["a", "b", "c"] + ) + axes = df.plot(kind="bar", secondary_y=["a", "c"], subplots=True) + assert axes[0].get_yaxis().get_ticks_position() == "right" + assert axes[1].get_yaxis().get_ticks_position() == "left" + assert axes[2].get_yaxis().get_ticks_position() == "right" + + def test_mixed_freq_regular_first(self): + # TODO + s1 = Series( + np.arange(20, dtype=np.float64), + index=date_range("2020-01-01", periods=20, freq="B"), + ) + s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]] + + # it works! + _, ax = mpl.pyplot.subplots() + s1.plot(ax=ax) + + ax2 = s2.plot(style="g", ax=ax) + lines = ax2.get_lines() + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx1 = PeriodIndex(lines[0].get_xdata()) + idx2 = PeriodIndex(lines[1].get_xdata()) + + tm.assert_index_equal(idx1, s1.index.to_period("B")) + tm.assert_index_equal(idx2, s2.index.to_period("B")) + + left, right = ax2.get_xlim() + pidx = s1.index.to_period() + assert left <= pidx[0].ordinal + assert right >= pidx[-1].ordinal + + def test_mixed_freq_irregular_first(self): + s1 = Series( + np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20) + ) + s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]] + _, ax = mpl.pyplot.subplots() + s2.plot(style="g", ax=ax) + s1.plot(ax=ax) + assert not hasattr(ax, "freq") + lines = ax.get_lines() + x1 = lines[0].get_xdata() + tm.assert_numpy_array_equal(x1, s2.index.astype(object).values) + x2 = lines[1].get_xdata() + tm.assert_numpy_array_equal(x2, s1.index.astype(object).values) + + def test_mixed_freq_regular_first_df(self): + # GH 9852 + s1 = Series( + np.arange(20, dtype=np.float64), + index=date_range("2020-01-01", periods=20, freq="B"), + ).to_frame() + s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :] + _, ax = mpl.pyplot.subplots() + s1.plot(ax=ax) + ax2 = s2.plot(style="g", ax=ax) + lines = ax2.get_lines() + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx1 = PeriodIndex(lines[0].get_xdata()) + idx2 = PeriodIndex(lines[1].get_xdata()) + assert idx1.equals(s1.index.to_period("B")) + assert idx2.equals(s2.index.to_period("B")) + left, right = ax2.get_xlim() + pidx = s1.index.to_period() + assert left <= pidx[0].ordinal + assert right >= pidx[-1].ordinal + + def test_mixed_freq_irregular_first_df(self): + # GH 9852 + s1 = Series( + np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20) + ).to_frame() + s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :] + _, ax = mpl.pyplot.subplots() + s2.plot(style="g", ax=ax) + s1.plot(ax=ax) + assert not hasattr(ax, "freq") + lines = ax.get_lines() + x1 = lines[0].get_xdata() + tm.assert_numpy_array_equal(x1, s2.index.astype(object).values) + x2 = lines[1].get_xdata() + tm.assert_numpy_array_equal(x2, s1.index.astype(object).values) + + def test_mixed_freq_hf_first(self): + idxh = date_range("1/1/1999", periods=365, freq="D") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + high.plot(ax=ax) + low.plot(ax=ax) + for line in ax.get_lines(): + assert PeriodIndex(data=line.get_xdata()).freq == "D" + + def test_mixed_freq_alignment(self): + ts_ind = date_range("2012-01-01 13:00", "2012-01-02", freq="h") + ts_data = np.random.default_rng(2).standard_normal(12) + + ts = Series(ts_data, index=ts_ind) + ts2 = ts.asfreq("min").interpolate() + + _, ax = mpl.pyplot.subplots() + ax = ts.plot(ax=ax) + ts2.plot(style="r", ax=ax) + + assert ax.lines[0].get_xdata()[0] == ax.lines[1].get_xdata()[0] + + def test_mixed_freq_lf_first(self): + idxh = date_range("1/1/1999", periods=365, freq="D") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + low.plot(legend=True, ax=ax) + high.plot(legend=True, ax=ax) + for line in ax.get_lines(): + assert PeriodIndex(data=line.get_xdata()).freq == "D" + leg = ax.get_legend() + assert len(leg.texts) == 2 + mpl.pyplot.close(ax.get_figure()) + + def test_mixed_freq_lf_first_hourly(self): + idxh = date_range("1/1/1999", periods=240, freq="min") + idxl = date_range("1/1/1999", periods=4, freq="h") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + low.plot(ax=ax) + high.plot(ax=ax) + for line in ax.get_lines(): + assert PeriodIndex(data=line.get_xdata()).freq == "min" + + @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") + def test_mixed_freq_irreg_period(self): + ts = Series( + np.arange(30, dtype=np.float64), index=date_range("2020-01-01", periods=30) + ) + irreg = ts.iloc[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]] + msg = r"PeriodDtype\[B\] is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rng = period_range("1/3/2000", periods=30, freq="B") + ps = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) + _, ax = mpl.pyplot.subplots() + irreg.plot(ax=ax) + ps.plot(ax=ax) + + def test_mixed_freq_shared_ax(self): + # GH13341, using sharex=True + idx1 = date_range("2015-01-01", periods=3, freq="ME") + idx2 = idx1[:1].union(idx1[2:]) + s1 = Series(range(len(idx1)), idx1) + s2 = Series(range(len(idx2)), idx2) + + _, (ax1, ax2) = mpl.pyplot.subplots(nrows=2, sharex=True) + s1.plot(ax=ax1) + s2.plot(ax=ax2) + + assert ax1.freq == "M" + assert ax2.freq == "M" + assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0] + + def test_mixed_freq_shared_ax_twin_x(self): + # GH13341, using sharex=True + idx1 = date_range("2015-01-01", periods=3, freq="ME") + idx2 = idx1[:1].union(idx1[2:]) + s1 = Series(range(len(idx1)), idx1) + s2 = Series(range(len(idx2)), idx2) + # using twinx + _, ax1 = mpl.pyplot.subplots() + ax2 = ax1.twinx() + s1.plot(ax=ax1) + s2.plot(ax=ax2) + + assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0] + + @pytest.mark.xfail(reason="TODO (GH14330, GH14322)") + def test_mixed_freq_shared_ax_twin_x_irregular_first(self): + # GH13341, using sharex=True + idx1 = date_range("2015-01-01", periods=3, freq="M") + idx2 = idx1[:1].union(idx1[2:]) + s1 = Series(range(len(idx1)), idx1) + s2 = Series(range(len(idx2)), idx2) + _, ax1 = mpl.pyplot.subplots() + ax2 = ax1.twinx() + s2.plot(ax=ax1) + s1.plot(ax=ax2) + assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0] + + def test_nat_handling(self): + _, ax = mpl.pyplot.subplots() + + dti = DatetimeIndex(["2015-01-01", NaT, "2015-01-03"]) + s = Series(range(len(dti)), dti) + s.plot(ax=ax) + xdata = ax.get_lines()[0].get_xdata() + # plot x data is bounded by index values + assert s.index.min() <= Series(xdata).min() + assert Series(xdata).max() <= s.index.max() + + def test_to_weekly_resampling_disallow_how_kwd(self): + idxh = date_range("1/1/1999", periods=52, freq="W") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + high.plot(ax=ax) + + msg = ( + "'how' is not a valid keyword for plotting functions. If plotting " + "multiple objects on shared axes, resample manually first." + ) + with pytest.raises(ValueError, match=msg): + low.plot(ax=ax, how="foo") + + def test_to_weekly_resampling(self): + idxh = date_range("1/1/1999", periods=52, freq="W") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + high.plot(ax=ax) + low.plot(ax=ax) + for line in ax.get_lines(): + assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq + + def test_from_weekly_resampling(self): + idxh = date_range("1/1/1999", periods=52, freq="W") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + low.plot(ax=ax) + high.plot(ax=ax) + + expected_h = idxh.to_period().asi8.astype(np.float64) + expected_l = np.array( + [1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549, 1553, 1558, 1562], + dtype=np.float64, + ) + for line in ax.get_lines(): + assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq + xdata = line.get_xdata(orig=False) + if len(xdata) == 12: # idxl lines + tm.assert_numpy_array_equal(xdata, expected_l) + else: + tm.assert_numpy_array_equal(xdata, expected_h) + + @pytest.mark.parametrize("kind1, kind2", [("line", "area"), ("area", "line")]) + def test_from_resampling_area_line_mixed(self, kind1, kind2): + idxh = date_range("1/1/1999", periods=52, freq="W") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = DataFrame( + np.random.default_rng(2).random((len(idxh), 3)), + index=idxh, + columns=[0, 1, 2], + ) + low = DataFrame( + np.random.default_rng(2).random((len(idxl), 3)), + index=idxl, + columns=[0, 1, 2], + ) + + _, ax = mpl.pyplot.subplots() + low.plot(kind=kind1, stacked=True, ax=ax) + high.plot(kind=kind2, stacked=True, ax=ax) + + # check low dataframe result + expected_x = np.array( + [ + 1514, + 1519, + 1523, + 1527, + 1531, + 1536, + 1540, + 1544, + 1549, + 1553, + 1558, + 1562, + ], + dtype=np.float64, + ) + expected_y = np.zeros(len(expected_x), dtype=np.float64) + for i in range(3): + line = ax.lines[i] + assert PeriodIndex(line.get_xdata()).freq == idxh.freq + tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x) + # check stacked values are correct + expected_y += low[i].values + tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y) + + # check high dataframe result + expected_x = idxh.to_period().asi8.astype(np.float64) + expected_y = np.zeros(len(expected_x), dtype=np.float64) + for i in range(3): + line = ax.lines[3 + i] + assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq + tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x) + expected_y += high[i].values + tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y) + + @pytest.mark.parametrize("kind1, kind2", [("line", "area"), ("area", "line")]) + def test_from_resampling_area_line_mixed_high_to_low(self, kind1, kind2): + idxh = date_range("1/1/1999", periods=52, freq="W") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = DataFrame( + np.random.default_rng(2).random((len(idxh), 3)), + index=idxh, + columns=[0, 1, 2], + ) + low = DataFrame( + np.random.default_rng(2).random((len(idxl), 3)), + index=idxl, + columns=[0, 1, 2], + ) + _, ax = mpl.pyplot.subplots() + high.plot(kind=kind1, stacked=True, ax=ax) + low.plot(kind=kind2, stacked=True, ax=ax) + + # check high dataframe result + expected_x = idxh.to_period().asi8.astype(np.float64) + expected_y = np.zeros(len(expected_x), dtype=np.float64) + for i in range(3): + line = ax.lines[i] + assert PeriodIndex(data=line.get_xdata()).freq == idxh.freq + tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x) + expected_y += high[i].values + tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y) + + # check low dataframe result + expected_x = np.array( + [ + 1514, + 1519, + 1523, + 1527, + 1531, + 1536, + 1540, + 1544, + 1549, + 1553, + 1558, + 1562, + ], + dtype=np.float64, + ) + expected_y = np.zeros(len(expected_x), dtype=np.float64) + for i in range(3): + lines = ax.lines[3 + i] + assert PeriodIndex(data=lines.get_xdata()).freq == idxh.freq + tm.assert_numpy_array_equal(lines.get_xdata(orig=False), expected_x) + expected_y += low[i].values + tm.assert_numpy_array_equal(lines.get_ydata(orig=False), expected_y) + + def test_mixed_freq_second_millisecond(self): + # GH 7772, GH 7760 + idxh = date_range("2014-07-01 09:00", freq="s", periods=50) + idxl = date_range("2014-07-01 09:00", freq="100ms", periods=500) + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + # high to low + _, ax = mpl.pyplot.subplots() + high.plot(ax=ax) + low.plot(ax=ax) + assert len(ax.get_lines()) == 2 + for line in ax.get_lines(): + assert PeriodIndex(data=line.get_xdata()).freq == "ms" + + def test_mixed_freq_second_millisecond_low_to_high(self): + # GH 7772, GH 7760 + idxh = date_range("2014-07-01 09:00", freq="s", periods=50) + idxl = date_range("2014-07-01 09:00", freq="100ms", periods=500) + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + # low to high + _, ax = mpl.pyplot.subplots() + low.plot(ax=ax) + high.plot(ax=ax) + assert len(ax.get_lines()) == 2 + for line in ax.get_lines(): + assert PeriodIndex(data=line.get_xdata()).freq == "ms" + + def test_irreg_dtypes(self): + # date + idx = [date(2000, 1, 1), date(2000, 1, 5), date(2000, 1, 20)] + df = DataFrame( + np.random.default_rng(2).standard_normal((len(idx), 3)), + Index(idx, dtype=object), + ) + _check_plot_works(df.plot) + + def test_irreg_dtypes_dt64(self): + # np.datetime64 + idx = date_range("1/1/2000", periods=10) + idx = idx[[0, 2, 5, 9]].astype(object) + df = DataFrame(np.random.default_rng(2).standard_normal((len(idx), 3)), idx) + _, ax = mpl.pyplot.subplots() + _check_plot_works(df.plot, ax=ax) + + def test_time(self): + t = datetime(1, 1, 1, 3, 30, 0) + deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum() + ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas]) + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(len(ts)), + "b": np.random.default_rng(2).standard_normal(len(ts)), + }, + index=ts, + ) + _, ax = mpl.pyplot.subplots() + df.plot(ax=ax) + + # verify tick labels + ticks = ax.get_xticks() + labels = ax.get_xticklabels() + for _tick, _label in zip(ticks, labels): + m, s = divmod(int(_tick), 60) + h, m = divmod(m, 60) + rs = _label.get_text() + if len(rs) > 0: + if s != 0: + xp = time(h, m, s).strftime("%H:%M:%S") + else: + xp = time(h, m, s).strftime("%H:%M") + assert xp == rs + + def test_time_change_xlim(self): + t = datetime(1, 1, 1, 3, 30, 0) + deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum() + ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas]) + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(len(ts)), + "b": np.random.default_rng(2).standard_normal(len(ts)), + }, + index=ts, + ) + _, ax = mpl.pyplot.subplots() + df.plot(ax=ax) + + # verify tick labels + ticks = ax.get_xticks() + labels = ax.get_xticklabels() + for _tick, _label in zip(ticks, labels): + m, s = divmod(int(_tick), 60) + h, m = divmod(m, 60) + rs = _label.get_text() + if len(rs) > 0: + if s != 0: + xp = time(h, m, s).strftime("%H:%M:%S") + else: + xp = time(h, m, s).strftime("%H:%M") + assert xp == rs + + # change xlim + ax.set_xlim("1:30", "5:00") + + # check tick labels again + ticks = ax.get_xticks() + labels = ax.get_xticklabels() + for _tick, _label in zip(ticks, labels): + m, s = divmod(int(_tick), 60) + h, m = divmod(m, 60) + rs = _label.get_text() + if len(rs) > 0: + if s != 0: + xp = time(h, m, s).strftime("%H:%M:%S") + else: + xp = time(h, m, s).strftime("%H:%M") + assert xp == rs + + def test_time_musec(self): + t = datetime(1, 1, 1, 3, 30, 0) + deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum() + ts = np.array([(t + timedelta(microseconds=int(x))).time() for x in deltas]) + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(len(ts)), + "b": np.random.default_rng(2).standard_normal(len(ts)), + }, + index=ts, + ) + _, ax = mpl.pyplot.subplots() + ax = df.plot(ax=ax) + + # verify tick labels + ticks = ax.get_xticks() + labels = ax.get_xticklabels() + for _tick, _label in zip(ticks, labels): + m, s = divmod(int(_tick), 60) + + us = round((_tick - int(_tick)) * 1e6) + + h, m = divmod(m, 60) + rs = _label.get_text() + if len(rs) > 0: + if (us % 1000) != 0: + xp = time(h, m, s, us).strftime("%H:%M:%S.%f") + elif (us // 1000) != 0: + xp = time(h, m, s, us).strftime("%H:%M:%S.%f")[:-3] + elif s != 0: + xp = time(h, m, s, us).strftime("%H:%M:%S") + else: + xp = time(h, m, s, us).strftime("%H:%M") + assert xp == rs + + def test_secondary_upsample(self): + idxh = date_range("1/1/1999", periods=365, freq="D") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + low.plot(ax=ax) + ax = high.plot(secondary_y=True, ax=ax) + for line in ax.get_lines(): + assert PeriodIndex(line.get_xdata()).freq == "D" + assert hasattr(ax, "left_ax") + assert not hasattr(ax, "right_ax") + for line in ax.left_ax.get_lines(): + assert PeriodIndex(line.get_xdata()).freq == "D" + + def test_secondary_legend(self): + fig = mpl.pyplot.figure() + ax = fig.add_subplot(211) + + # ts + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df.plot(secondary_y=["A", "B"], ax=ax) + leg = ax.get_legend() + assert len(leg.get_lines()) == 4 + assert leg.get_texts()[0].get_text() == "A (right)" + assert leg.get_texts()[1].get_text() == "B (right)" + assert leg.get_texts()[2].get_text() == "C" + assert leg.get_texts()[3].get_text() == "D" + assert ax.right_ax.get_legend() is None + colors = set() + for line in leg.get_lines(): + colors.add(line.get_color()) + + # TODO: color cycle problems + assert len(colors) == 4 + mpl.pyplot.close(fig) + + def test_secondary_legend_right(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + fig = mpl.pyplot.figure() + ax = fig.add_subplot(211) + df.plot(secondary_y=["A", "C"], mark_right=False, ax=ax) + leg = ax.get_legend() + assert len(leg.get_lines()) == 4 + assert leg.get_texts()[0].get_text() == "A" + assert leg.get_texts()[1].get_text() == "B" + assert leg.get_texts()[2].get_text() == "C" + assert leg.get_texts()[3].get_text() == "D" + mpl.pyplot.close(fig) + + def test_secondary_legend_bar(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + fig, ax = mpl.pyplot.subplots() + df.plot(kind="bar", secondary_y=["A"], ax=ax) + leg = ax.get_legend() + assert leg.get_texts()[0].get_text() == "A (right)" + assert leg.get_texts()[1].get_text() == "B" + mpl.pyplot.close(fig) + + def test_secondary_legend_bar_right(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + fig, ax = mpl.pyplot.subplots() + df.plot(kind="bar", secondary_y=["A"], mark_right=False, ax=ax) + leg = ax.get_legend() + assert leg.get_texts()[0].get_text() == "A" + assert leg.get_texts()[1].get_text() == "B" + mpl.pyplot.close(fig) + + def test_secondary_legend_multi_col(self): + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + fig = mpl.pyplot.figure() + ax = fig.add_subplot(211) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + ax = df.plot(secondary_y=["C", "D"], ax=ax) + leg = ax.get_legend() + assert len(leg.get_lines()) == 4 + assert ax.right_ax.get_legend() is None + colors = set() + for line in leg.get_lines(): + colors.add(line.get_color()) + + # TODO: color cycle problems + assert len(colors) == 4 + mpl.pyplot.close(fig) + + def test_secondary_legend_nonts(self): + # non-ts + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + fig = mpl.pyplot.figure() + ax = fig.add_subplot(211) + ax = df.plot(secondary_y=["A", "B"], ax=ax) + leg = ax.get_legend() + assert len(leg.get_lines()) == 4 + assert ax.right_ax.get_legend() is None + colors = set() + for line in leg.get_lines(): + colors.add(line.get_color()) + + # TODO: color cycle problems + assert len(colors) == 4 + mpl.pyplot.close() + + def test_secondary_legend_nonts_multi_col(self): + # non-ts + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + fig = mpl.pyplot.figure() + ax = fig.add_subplot(211) + ax = df.plot(secondary_y=["C", "D"], ax=ax) + leg = ax.get_legend() + assert len(leg.get_lines()) == 4 + assert ax.right_ax.get_legend() is None + colors = set() + for line in leg.get_lines(): + colors.add(line.get_color()) + + # TODO: color cycle problems + assert len(colors) == 4 + + @pytest.mark.xfail(reason="Api changed in 3.6.0") + def test_format_date_axis(self): + rng = date_range("1/1/2012", periods=12, freq="ME") + df = DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng) + _, ax = mpl.pyplot.subplots() + ax = df.plot(ax=ax) + xaxis = ax.get_xaxis() + for line in xaxis.get_ticklabels(): + if len(line.get_text()) > 0: + assert line.get_rotation() == 30 + + def test_ax_plot(self): + x = date_range(start="2012-01-02", periods=10, freq="D") + y = list(range(len(x))) + _, ax = mpl.pyplot.subplots() + lines = ax.plot(x, y, label="Y") + tm.assert_index_equal(DatetimeIndex(lines[0].get_xdata()), x) + + def test_mpl_nopandas(self): + dates = [date(2008, 12, 31), date(2009, 1, 31)] + values1 = np.arange(10.0, 11.0, 0.5) + values2 = np.arange(11.0, 12.0, 0.5) + + _, ax = mpl.pyplot.subplots() + ( + line1, + line2, + ) = ax.plot( + [x.toordinal() for x in dates], + values1, + "-", + [x.toordinal() for x in dates], + values2, + "-", + linewidth=4, + ) + + exp = np.array([x.toordinal() for x in dates], dtype=np.float64) + tm.assert_numpy_array_equal(line1.get_xydata()[:, 0], exp) + exp = np.array([x.toordinal() for x in dates], dtype=np.float64) + tm.assert_numpy_array_equal(line2.get_xydata()[:, 0], exp) + + def test_irregular_ts_shared_ax_xlim(self): + # GH 2960 + from pandas.plotting._matplotlib.converter import DatetimeConverter + + ts = Series( + np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20) + ) + ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]] + + # plot the left section of the irregular series, then the right section + _, ax = mpl.pyplot.subplots() + ts_irregular[:5].plot(ax=ax) + ts_irregular[5:].plot(ax=ax) + + # check that axis limits are correct + left, right = ax.get_xlim() + assert left <= DatetimeConverter.convert(ts_irregular.index.min(), "", ax) + assert right >= DatetimeConverter.convert(ts_irregular.index.max(), "", ax) + + def test_secondary_y_non_ts_xlim(self): + # GH 3490 - non-timeseries with secondary y + index_1 = [1, 2, 3, 4] + index_2 = [5, 6, 7, 8] + s1 = Series(1, index=index_1) + s2 = Series(2, index=index_2) + + _, ax = mpl.pyplot.subplots() + s1.plot(ax=ax) + left_before, right_before = ax.get_xlim() + s2.plot(secondary_y=True, ax=ax) + left_after, right_after = ax.get_xlim() + + assert left_before >= left_after + assert right_before < right_after + + def test_secondary_y_regular_ts_xlim(self): + # GH 3490 - regular-timeseries with secondary y + index_1 = date_range(start="2000-01-01", periods=4, freq="D") + index_2 = date_range(start="2000-01-05", periods=4, freq="D") + s1 = Series(1, index=index_1) + s2 = Series(2, index=index_2) + + _, ax = mpl.pyplot.subplots() + s1.plot(ax=ax) + left_before, right_before = ax.get_xlim() + s2.plot(secondary_y=True, ax=ax) + left_after, right_after = ax.get_xlim() + + assert left_before >= left_after + assert right_before < right_after + + def test_secondary_y_mixed_freq_ts_xlim(self): + # GH 3490 - mixed frequency timeseries with secondary y + rng = date_range("2000-01-01", periods=10000, freq="min") + ts = Series(1, index=rng) + + _, ax = mpl.pyplot.subplots() + ts.plot(ax=ax) + left_before, right_before = ax.get_xlim() + ts.resample("D").mean().plot(secondary_y=True, ax=ax) + left_after, right_after = ax.get_xlim() + + # a downsample should not have changed either limit + assert left_before == left_after + assert right_before == right_after + + def test_secondary_y_irregular_ts_xlim(self): + # GH 3490 - irregular-timeseries with secondary y + from pandas.plotting._matplotlib.converter import DatetimeConverter + + ts = Series( + np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20) + ) + ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]] + + _, ax = mpl.pyplot.subplots() + ts_irregular[:5].plot(ax=ax) + # plot higher-x values on secondary axis + ts_irregular[5:].plot(secondary_y=True, ax=ax) + # ensure secondary limits aren't overwritten by plot on primary + ts_irregular[:5].plot(ax=ax) + + left, right = ax.get_xlim() + assert left <= DatetimeConverter.convert(ts_irregular.index.min(), "", ax) + assert right >= DatetimeConverter.convert(ts_irregular.index.max(), "", ax) + + def test_plot_outofbounds_datetime(self): + # 2579 - checking this does not raise + values = [date(1677, 1, 1), date(1677, 1, 2)] + _, ax = mpl.pyplot.subplots() + ax.plot(values) + + values = [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)] + ax.plot(values) + + def test_format_timedelta_ticks_narrow(self): + expected_labels = [f"00:00:00.0000000{i:0>2d}" for i in np.arange(10)] + + rng = timedelta_range("0", periods=10, freq="ns") + df = DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng) + _, ax = mpl.pyplot.subplots() + df.plot(fontsize=2, ax=ax) + mpl.pyplot.draw() + labels = ax.get_xticklabels() + + result_labels = [x.get_text() for x in labels] + assert len(result_labels) == len(expected_labels) + assert result_labels == expected_labels + + def test_format_timedelta_ticks_wide(self): + expected_labels = [ + "00:00:00", + "1 days 03:46:40", + "2 days 07:33:20", + "3 days 11:20:00", + "4 days 15:06:40", + "5 days 18:53:20", + "6 days 22:40:00", + "8 days 02:26:40", + "9 days 06:13:20", + ] + + rng = timedelta_range("0", periods=10, freq="1 d") + df = DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng) + _, ax = mpl.pyplot.subplots() + ax = df.plot(fontsize=2, ax=ax) + mpl.pyplot.draw() + labels = ax.get_xticklabels() + + result_labels = [x.get_text() for x in labels] + assert len(result_labels) == len(expected_labels) + assert result_labels == expected_labels + + def test_timedelta_plot(self): + # test issue #8711 + s = Series(range(5), timedelta_range("1day", periods=5)) + _, ax = mpl.pyplot.subplots() + _check_plot_works(s.plot, ax=ax) + + def test_timedelta_long_period(self): + # test long period + index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 d") + s = Series(np.random.default_rng(2).standard_normal(len(index)), index) + _, ax = mpl.pyplot.subplots() + _check_plot_works(s.plot, ax=ax) + + def test_timedelta_short_period(self): + # test short period + index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 ns") + s = Series(np.random.default_rng(2).standard_normal(len(index)), index) + _, ax = mpl.pyplot.subplots() + _check_plot_works(s.plot, ax=ax) + + def test_hist(self): + # https://github.com/matplotlib/matplotlib/issues/8459 + rng = date_range("1/1/2011", periods=10, freq="h") + x = rng + w1 = np.arange(0, 1, 0.1) + w2 = np.arange(0, 1, 0.1)[::-1] + _, ax = mpl.pyplot.subplots() + ax.hist([x, x], weights=[w1, w2]) + + def test_overlapping_datetime(self): + # GB 6608 + s1 = Series( + [1, 2, 3], + index=[ + datetime(1995, 12, 31), + datetime(2000, 12, 31), + datetime(2005, 12, 31), + ], + ) + s2 = Series( + [1, 2, 3], + index=[ + datetime(1997, 12, 31), + datetime(2003, 12, 31), + datetime(2008, 12, 31), + ], + ) + + # plot first series, then add the second series to those axes, + # then try adding the first series again + _, ax = mpl.pyplot.subplots() + s1.plot(ax=ax) + s2.plot(ax=ax) + s1.plot(ax=ax) + + @pytest.mark.xfail(reason="GH9053 matplotlib does not use ax.xaxis.converter") + def test_add_matplotlib_datetime64(self): + # GH9053 - ensure that a plot with PeriodConverter still understands + # datetime64 data. This still fails because matplotlib overrides the + # ax.xaxis.converter with a DatetimeConverter + s = Series( + np.random.default_rng(2).standard_normal(10), + index=date_range("1970-01-02", periods=10), + ) + ax = s.plot() + with tm.assert_produces_warning(DeprecationWarning): + # multi-dimensional indexing + ax.plot(s.index, s.values, color="g") + l1, l2 = ax.lines + tm.assert_numpy_array_equal(l1.get_xydata(), l2.get_xydata()) + + def test_matplotlib_scatter_datetime64(self): + # https://github.com/matplotlib/matplotlib/issues/11391 + df = DataFrame(np.random.default_rng(2).random((10, 2)), columns=["x", "y"]) + df["time"] = date_range("2018-01-01", periods=10, freq="D") + _, ax = mpl.pyplot.subplots() + ax.scatter(x="time", y="y", data=df) + mpl.pyplot.draw() + label = ax.get_xticklabels()[0] + expected = "2018-01-01" + assert label.get_text() == expected + + def test_check_xticks_rot(self): + # https://github.com/pandas-dev/pandas/issues/29460 + # regular time series + x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-03"]) + df = DataFrame({"x": x, "y": [1, 2, 3]}) + axes = df.plot(x="x", y="y") + _check_ticks_props(axes, xrot=0) + + def test_check_xticks_rot_irregular(self): + # irregular time series + x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"]) + df = DataFrame({"x": x, "y": [1, 2, 3]}) + axes = df.plot(x="x", y="y") + _check_ticks_props(axes, xrot=30) + + def test_check_xticks_rot_use_idx(self): + # irregular time series + x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"]) + df = DataFrame({"x": x, "y": [1, 2, 3]}) + # use timeseries index or not + axes = df.set_index("x").plot(y="y", use_index=True) + _check_ticks_props(axes, xrot=30) + axes = df.set_index("x").plot(y="y", use_index=False) + _check_ticks_props(axes, xrot=0) + + def test_check_xticks_rot_sharex(self): + # irregular time series + x = to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"]) + df = DataFrame({"x": x, "y": [1, 2, 3]}) + # separate subplots + axes = df.plot(x="x", y="y", subplots=True, sharex=True) + _check_ticks_props(axes, xrot=30) + axes = df.plot(x="x", y="y", subplots=True, sharex=False) + _check_ticks_props(axes, xrot=0) + + +def _check_plot_works(f, freq=None, series=None, *args, **kwargs): + import matplotlib.pyplot as plt + + fig = plt.gcf() + + try: + plt.clf() + ax = fig.add_subplot(211) + orig_ax = kwargs.pop("ax", plt.gca()) + orig_axfreq = getattr(orig_ax, "freq", None) + + ret = f(*args, **kwargs) + assert ret is not None # do something more intelligent + + ax = kwargs.pop("ax", plt.gca()) + if series is not None: + dfreq = series.index.freq + if isinstance(dfreq, BaseOffset): + dfreq = dfreq.rule_code + if orig_axfreq is None: + assert ax.freq == dfreq + + if freq is not None: + ax_freq = to_offset(ax.freq, is_period=True) + if freq is not None and orig_axfreq is None: + assert ax_freq == freq + + ax = fig.add_subplot(212) + kwargs["ax"] = ax + ret = f(*args, **kwargs) + assert ret is not None # TODO: do something more intelligent + + # GH18439, GH#24088, statsmodels#4772 + with tm.ensure_clean(return_filelike=True) as path: + pickle.dump(fig, path) + finally: + plt.close(fig) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_hist_method.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_hist_method.py new file mode 100644 index 0000000000000000000000000000000000000000..4d17f87fdc7bc1456a118c84b76c631544572fd4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_hist_method.py @@ -0,0 +1,971 @@ +""" Test cases for .hist method """ +import re + +import numpy as np +import pytest + +from pandas import ( + DataFrame, + Index, + Series, + date_range, + to_datetime, +) +import pandas._testing as tm +from pandas.tests.plotting.common import ( + _check_ax_scales, + _check_axes_shape, + _check_colors, + _check_legend_labels, + _check_patches_all_filled, + _check_plot_works, + _check_text_labels, + _check_ticks_props, + get_x_axis, + get_y_axis, +) + +mpl = pytest.importorskip("matplotlib") + + +@pytest.fixture +def ts(): + return Series( + np.arange(30, dtype=np.float64), + index=date_range("2020-01-01", periods=30, freq="B"), + name="ts", + ) + + +class TestSeriesPlots: + @pytest.mark.parametrize("kwargs", [{}, {"grid": False}, {"figsize": (8, 10)}]) + def test_hist_legacy_kwargs(self, ts, kwargs): + _check_plot_works(ts.hist, **kwargs) + + @pytest.mark.parametrize("kwargs", [{}, {"bins": 5}]) + def test_hist_legacy_kwargs_warning(self, ts, kwargs): + # _check_plot_works adds an ax so catch warning. see GH #13188 + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + _check_plot_works(ts.hist, by=ts.index.month, **kwargs) + + def test_hist_legacy_ax(self, ts): + fig, ax = mpl.pyplot.subplots(1, 1) + _check_plot_works(ts.hist, ax=ax, default_axes=True) + + def test_hist_legacy_ax_and_fig(self, ts): + fig, ax = mpl.pyplot.subplots(1, 1) + _check_plot_works(ts.hist, ax=ax, figure=fig, default_axes=True) + + def test_hist_legacy_fig(self, ts): + fig, _ = mpl.pyplot.subplots(1, 1) + _check_plot_works(ts.hist, figure=fig, default_axes=True) + + def test_hist_legacy_multi_ax(self, ts): + fig, (ax1, ax2) = mpl.pyplot.subplots(1, 2) + _check_plot_works(ts.hist, figure=fig, ax=ax1, default_axes=True) + _check_plot_works(ts.hist, figure=fig, ax=ax2, default_axes=True) + + def test_hist_legacy_by_fig_error(self, ts): + fig, _ = mpl.pyplot.subplots(1, 1) + msg = ( + "Cannot pass 'figure' when using the 'by' argument, since a new 'Figure' " + "instance will be created" + ) + with pytest.raises(ValueError, match=msg): + ts.hist(by=ts.index, figure=fig) + + def test_hist_bins_legacy(self): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) + ax = df.hist(bins=2)[0][0] + assert len(ax.patches) == 2 + + def test_hist_layout(self, hist_df): + df = hist_df + msg = "The 'layout' keyword is not supported when 'by' is None" + with pytest.raises(ValueError, match=msg): + df.height.hist(layout=(1, 1)) + + with pytest.raises(ValueError, match=msg): + df.height.hist(layout=[1, 1]) + + @pytest.mark.slow + @pytest.mark.parametrize( + "by, layout, axes_num, res_layout", + [ + ["gender", (2, 1), 2, (2, 1)], + ["gender", (3, -1), 2, (3, 1)], + ["category", (4, 1), 4, (4, 1)], + ["category", (2, -1), 4, (2, 2)], + ["category", (3, -1), 4, (3, 2)], + ["category", (-1, 4), 4, (1, 4)], + ["classroom", (2, 2), 3, (2, 2)], + ], + ) + def test_hist_layout_with_by(self, hist_df, by, layout, axes_num, res_layout): + df = hist_df + + # _check_plot_works adds an `ax` kwarg to the method call + # so we get a warning about an axis being cleared, even + # though we don't explicing pass one, see GH #13188 + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works(df.height.hist, by=getattr(df, by), layout=layout) + _check_axes_shape(axes, axes_num=axes_num, layout=res_layout) + + def test_hist_layout_with_by_shape(self, hist_df): + df = hist_df + + axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7)) + _check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 7)) + + def test_hist_no_overlap(self): + from matplotlib.pyplot import ( + gcf, + subplot, + ) + + x = Series(np.random.default_rng(2).standard_normal(2)) + y = Series(np.random.default_rng(2).standard_normal(2)) + subplot(121) + x.hist() + subplot(122) + y.hist() + fig = gcf() + axes = fig.axes + assert len(axes) == 2 + + def test_hist_by_no_extra_plots(self, hist_df): + df = hist_df + df.height.hist(by=df.gender) + assert len(mpl.pyplot.get_fignums()) == 1 + + def test_plot_fails_when_ax_differs_from_figure(self, ts): + from pylab import figure + + fig1 = figure() + fig2 = figure() + ax1 = fig1.add_subplot(111) + msg = "passed axis not bound to passed figure" + with pytest.raises(AssertionError, match=msg): + ts.hist(ax=ax1, figure=fig2) + + @pytest.mark.parametrize( + "histtype, expected", + [ + ("bar", True), + ("barstacked", True), + ("step", False), + ("stepfilled", True), + ], + ) + def test_histtype_argument(self, histtype, expected): + # GH23992 Verify functioning of histtype argument + ser = Series(np.random.default_rng(2).integers(1, 10)) + ax = ser.hist(histtype=histtype) + _check_patches_all_filled(ax, filled=expected) + + @pytest.mark.parametrize( + "by, expected_axes_num, expected_layout", [(None, 1, (1, 1)), ("b", 2, (1, 2))] + ) + def test_hist_with_legend(self, by, expected_axes_num, expected_layout): + # GH 6279 - Series histogram can have a legend + index = 15 * ["1"] + 15 * ["2"] + s = Series(np.random.default_rng(2).standard_normal(30), index=index, name="a") + s.index.name = "b" + + # Use default_axes=True when plotting method generate subplots itself + axes = _check_plot_works(s.hist, default_axes=True, legend=True, by=by) + _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) + _check_legend_labels(axes, "a") + + @pytest.mark.parametrize("by", [None, "b"]) + def test_hist_with_legend_raises(self, by): + # GH 6279 - Series histogram with legend and label raises + index = 15 * ["1"] + 15 * ["2"] + s = Series(np.random.default_rng(2).standard_normal(30), index=index, name="a") + s.index.name = "b" + + with pytest.raises(ValueError, match="Cannot use both legend and label"): + s.hist(legend=True, by=by, label="c") + + def test_hist_kwargs(self, ts): + _, ax = mpl.pyplot.subplots() + ax = ts.plot.hist(bins=5, ax=ax) + assert len(ax.patches) == 5 + _check_text_labels(ax.yaxis.get_label(), "Frequency") + + def test_hist_kwargs_horizontal(self, ts): + _, ax = mpl.pyplot.subplots() + ax = ts.plot.hist(bins=5, ax=ax) + ax = ts.plot.hist(orientation="horizontal", ax=ax) + _check_text_labels(ax.xaxis.get_label(), "Frequency") + + def test_hist_kwargs_align(self, ts): + _, ax = mpl.pyplot.subplots() + ax = ts.plot.hist(bins=5, ax=ax) + ax = ts.plot.hist(align="left", stacked=True, ax=ax) + + @pytest.mark.xfail(reason="Api changed in 3.6.0") + def test_hist_kde(self, ts): + pytest.importorskip("scipy") + _, ax = mpl.pyplot.subplots() + ax = ts.plot.hist(logy=True, ax=ax) + _check_ax_scales(ax, yaxis="log") + xlabels = ax.get_xticklabels() + # ticks are values, thus ticklabels are blank + _check_text_labels(xlabels, [""] * len(xlabels)) + ylabels = ax.get_yticklabels() + _check_text_labels(ylabels, [""] * len(ylabels)) + + def test_hist_kde_plot_works(self, ts): + pytest.importorskip("scipy") + _check_plot_works(ts.plot.kde) + + def test_hist_kde_density_works(self, ts): + pytest.importorskip("scipy") + _check_plot_works(ts.plot.density) + + @pytest.mark.xfail(reason="Api changed in 3.6.0") + def test_hist_kde_logy(self, ts): + pytest.importorskip("scipy") + _, ax = mpl.pyplot.subplots() + ax = ts.plot.kde(logy=True, ax=ax) + _check_ax_scales(ax, yaxis="log") + xlabels = ax.get_xticklabels() + _check_text_labels(xlabels, [""] * len(xlabels)) + ylabels = ax.get_yticklabels() + _check_text_labels(ylabels, [""] * len(ylabels)) + + def test_hist_kde_color_bins(self, ts): + pytest.importorskip("scipy") + _, ax = mpl.pyplot.subplots() + ax = ts.plot.hist(logy=True, bins=10, color="b", ax=ax) + _check_ax_scales(ax, yaxis="log") + assert len(ax.patches) == 10 + _check_colors(ax.patches, facecolors=["b"] * 10) + + def test_hist_kde_color(self, ts): + pytest.importorskip("scipy") + _, ax = mpl.pyplot.subplots() + ax = ts.plot.kde(logy=True, color="r", ax=ax) + _check_ax_scales(ax, yaxis="log") + lines = ax.get_lines() + assert len(lines) == 1 + _check_colors(lines, ["r"]) + + +class TestDataFramePlots: + @pytest.mark.slow + def test_hist_df_legacy(self, hist_df): + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + _check_plot_works(hist_df.hist) + + @pytest.mark.slow + def test_hist_df_legacy_layout(self): + # make sure layout is handled + df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) + df[2] = to_datetime( + np.random.default_rng(2).integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works(df.hist, grid=False) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) + assert not axes[1, 1].get_visible() + + _check_plot_works(df[[2]].hist) + + @pytest.mark.slow + def test_hist_df_legacy_layout2(self): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 1))) + _check_plot_works(df.hist) + + @pytest.mark.slow + def test_hist_df_legacy_layout3(self): + # make sure layout is handled + df = DataFrame(np.random.default_rng(2).standard_normal((10, 5))) + df[5] = to_datetime( + np.random.default_rng(2).integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works(df.hist, layout=(4, 2)) + _check_axes_shape(axes, axes_num=6, layout=(4, 2)) + + @pytest.mark.slow + @pytest.mark.parametrize( + "kwargs", [{"sharex": True, "sharey": True}, {"figsize": (8, 10)}, {"bins": 5}] + ) + def test_hist_df_legacy_layout_kwargs(self, kwargs): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 5))) + df[5] = to_datetime( + np.random.default_rng(2).integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + # make sure sharex, sharey is handled + # handle figsize arg + # check bins argument + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + _check_plot_works(df.hist, **kwargs) + + @pytest.mark.slow + def test_hist_df_legacy_layout_labelsize_rot(self, frame_or_series): + # make sure xlabelsize and xrot are handled + obj = frame_or_series(range(10)) + xf, yf = 20, 18 + xrot, yrot = 30, 40 + axes = obj.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) + _check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) + + @pytest.mark.slow + def test_hist_df_legacy_rectangles(self): + from matplotlib.patches import Rectangle + + ser = Series(range(10)) + ax = ser.hist(cumulative=True, bins=4, density=True) + # height of last bin (index 5) must be 1.0 + rects = [x for x in ax.get_children() if isinstance(x, Rectangle)] + tm.assert_almost_equal(rects[-1].get_height(), 1.0) + + @pytest.mark.slow + def test_hist_df_legacy_scale(self): + ser = Series(range(10)) + ax = ser.hist(log=True) + # scale of y must be 'log' + _check_ax_scales(ax, yaxis="log") + + @pytest.mark.slow + def test_hist_df_legacy_external_error(self): + ser = Series(range(10)) + # propagate attr exception from matplotlib.Axes.hist + with tm.external_error_raised(AttributeError): + ser.hist(foo="bar") + + def test_hist_non_numerical_or_datetime_raises(self): + # gh-10444, GH32590 + df = DataFrame( + { + "a": np.random.default_rng(2).random(10), + "b": np.random.default_rng(2).integers(0, 10, 10), + "c": to_datetime( + np.random.default_rng(2).integers( + 1582800000000000000, 1583500000000000000, 10, dtype=np.int64 + ) + ), + "d": to_datetime( + np.random.default_rng(2).integers( + 1582800000000000000, 1583500000000000000, 10, dtype=np.int64 + ), + utc=True, + ), + } + ) + df_o = df.astype(object) + + msg = "hist method requires numerical or datetime columns, nothing to plot." + with pytest.raises(ValueError, match=msg): + df_o.hist() + + @pytest.mark.parametrize( + "layout_test", + ( + {"layout": None, "expected_size": (2, 2)}, # default is 2x2 + {"layout": (2, 2), "expected_size": (2, 2)}, + {"layout": (4, 1), "expected_size": (4, 1)}, + {"layout": (1, 4), "expected_size": (1, 4)}, + {"layout": (3, 3), "expected_size": (3, 3)}, + {"layout": (-1, 4), "expected_size": (1, 4)}, + {"layout": (4, -1), "expected_size": (4, 1)}, + {"layout": (-1, 2), "expected_size": (2, 2)}, + {"layout": (2, -1), "expected_size": (2, 2)}, + ), + ) + def test_hist_layout(self, layout_test): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) + df[2] = to_datetime( + np.random.default_rng(2).integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + axes = df.hist(layout=layout_test["layout"]) + expected = layout_test["expected_size"] + _check_axes_shape(axes, axes_num=3, layout=expected) + + def test_hist_layout_error(self): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) + df[2] = to_datetime( + np.random.default_rng(2).integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + # layout too small for all 4 plots + msg = "Layout of 1x1 must be larger than required size 3" + with pytest.raises(ValueError, match=msg): + df.hist(layout=(1, 1)) + + # invalid format for layout + msg = re.escape("Layout must be a tuple of (rows, columns)") + with pytest.raises(ValueError, match=msg): + df.hist(layout=(1,)) + msg = "At least one dimension of layout must be positive" + with pytest.raises(ValueError, match=msg): + df.hist(layout=(-1, -1)) + + # GH 9351 + def test_tight_layout(self): + df = DataFrame(np.random.default_rng(2).standard_normal((100, 2))) + df[2] = to_datetime( + np.random.default_rng(2).integers( + 812419200000000000, + 819331200000000000, + size=100, + dtype=np.int64, + ) + ) + # Use default_axes=True when plotting method generate subplots itself + _check_plot_works(df.hist, default_axes=True) + mpl.pyplot.tight_layout() + + def test_hist_subplot_xrot(self): + # GH 30288 + df = DataFrame( + { + "length": [1.5, 0.5, 1.2, 0.9, 3], + "animal": ["pig", "rabbit", "pig", "pig", "rabbit"], + } + ) + # Use default_axes=True when plotting method generate subplots itself + axes = _check_plot_works( + df.hist, + default_axes=True, + column="length", + by="animal", + bins=5, + xrot=0, + ) + _check_ticks_props(axes, xrot=0) + + @pytest.mark.parametrize( + "column, expected", + [ + (None, ["width", "length", "height"]), + (["length", "width", "height"], ["length", "width", "height"]), + ], + ) + def test_hist_column_order_unchanged(self, column, expected): + # GH29235 + + df = DataFrame( + { + "width": [0.7, 0.2, 0.15, 0.2, 1.1], + "length": [1.5, 0.5, 1.2, 0.9, 3], + "height": [3, 0.5, 3.4, 2, 1], + }, + index=["pig", "rabbit", "duck", "chicken", "horse"], + ) + + # Use default_axes=True when plotting method generate subplots itself + axes = _check_plot_works( + df.hist, + default_axes=True, + column=column, + layout=(1, 3), + ) + result = [axes[0, i].get_title() for i in range(3)] + assert result == expected + + @pytest.mark.parametrize( + "histtype, expected", + [ + ("bar", True), + ("barstacked", True), + ("step", False), + ("stepfilled", True), + ], + ) + def test_histtype_argument(self, histtype, expected): + # GH23992 Verify functioning of histtype argument + df = DataFrame( + np.random.default_rng(2).integers(1, 10, size=(100, 2)), columns=["a", "b"] + ) + ax = df.hist(histtype=histtype) + _check_patches_all_filled(ax, filled=expected) + + @pytest.mark.parametrize("by", [None, "c"]) + @pytest.mark.parametrize("column", [None, "b"]) + def test_hist_with_legend(self, by, column): + # GH 6279 - DataFrame histogram can have a legend + expected_axes_num = 1 if by is None and column is not None else 2 + expected_layout = (1, expected_axes_num) + expected_labels = column or ["a", "b"] + if by is not None: + expected_labels = [expected_labels] * 2 + + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 2)), + index=index, + columns=["a", "b"], + ) + + # Use default_axes=True when plotting method generate subplots itself + axes = _check_plot_works( + df.hist, + default_axes=True, + legend=True, + by=by, + column=column, + ) + + _check_axes_shape(axes, axes_num=expected_axes_num, layout=expected_layout) + if by is None and column is None: + axes = axes[0] + for expected_label, ax in zip(expected_labels, axes): + _check_legend_labels(ax, expected_label) + + @pytest.mark.parametrize("by", [None, "c"]) + @pytest.mark.parametrize("column", [None, "b"]) + def test_hist_with_legend_raises(self, by, column): + # GH 6279 - DataFrame histogram with legend and label raises + index = Index(15 * ["1"] + 15 * ["2"], name="c") + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 2)), + index=index, + columns=["a", "b"], + ) + + with pytest.raises(ValueError, match="Cannot use both legend and label"): + df.hist(legend=True, by=by, column=column, label="d") + + def test_hist_df_kwargs(self): + df = DataFrame(np.random.default_rng(2).standard_normal((10, 2))) + _, ax = mpl.pyplot.subplots() + ax = df.plot.hist(bins=5, ax=ax) + assert len(ax.patches) == 10 + + def test_hist_df_with_nonnumerics(self): + # GH 9853 + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=["A", "B", "C", "D"], + ) + df["E"] = ["x", "y"] * 5 + _, ax = mpl.pyplot.subplots() + ax = df.plot.hist(bins=5, ax=ax) + assert len(ax.patches) == 20 + + def test_hist_df_with_nonnumerics_no_bins(self): + # GH 9853 + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=["A", "B", "C", "D"], + ) + df["E"] = ["x", "y"] * 5 + _, ax = mpl.pyplot.subplots() + ax = df.plot.hist(ax=ax) # bins=10 + assert len(ax.patches) == 40 + + def test_hist_secondary_legend(self): + # GH 9610 + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd") + ) + + # primary -> secondary + _, ax = mpl.pyplot.subplots() + ax = df["a"].plot.hist(legend=True, ax=ax) + df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) + # both legends are drawn on left ax + # left and right axis must be visible + _check_legend_labels(ax, labels=["a", "b (right)"]) + assert ax.get_yaxis().get_visible() + assert ax.right_ax.get_yaxis().get_visible() + + def test_hist_secondary_secondary(self): + # GH 9610 + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd") + ) + # secondary -> secondary + _, ax = mpl.pyplot.subplots() + ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) + df["b"].plot.hist(ax=ax, legend=True, secondary_y=True) + # both legends are draw on left ax + # left axis must be invisible, right axis must be visible + _check_legend_labels(ax.left_ax, labels=["a (right)", "b (right)"]) + assert not ax.left_ax.get_yaxis().get_visible() + assert ax.get_yaxis().get_visible() + + def test_hist_secondary_primary(self): + # GH 9610 + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), columns=list("abcd") + ) + # secondary -> primary + _, ax = mpl.pyplot.subplots() + ax = df["a"].plot.hist(legend=True, secondary_y=True, ax=ax) + # right axes is returned + df["b"].plot.hist(ax=ax, legend=True) + # both legends are draw on left ax + # left and right axis must be visible + _check_legend_labels(ax.left_ax, labels=["a (right)", "b"]) + assert ax.left_ax.get_yaxis().get_visible() + assert ax.get_yaxis().get_visible() + + def test_hist_with_nans_and_weights(self): + # GH 48884 + mpl_patches = pytest.importorskip("matplotlib.patches") + df = DataFrame( + [[np.nan, 0.2, 0.3], [0.4, np.nan, np.nan], [0.7, 0.8, 0.9]], + columns=list("abc"), + ) + weights = np.array([0.25, 0.3, 0.45]) + no_nan_df = DataFrame([[0.4, 0.2, 0.3], [0.7, 0.8, 0.9]], columns=list("abc")) + no_nan_weights = np.array([[0.3, 0.25, 0.25], [0.45, 0.45, 0.45]]) + + _, ax0 = mpl.pyplot.subplots() + df.plot.hist(ax=ax0, weights=weights) + rects = [x for x in ax0.get_children() if isinstance(x, mpl_patches.Rectangle)] + heights = [rect.get_height() for rect in rects] + _, ax1 = mpl.pyplot.subplots() + no_nan_df.plot.hist(ax=ax1, weights=no_nan_weights) + no_nan_rects = [ + x for x in ax1.get_children() if isinstance(x, mpl_patches.Rectangle) + ] + no_nan_heights = [rect.get_height() for rect in no_nan_rects] + assert all(h0 == h1 for h0, h1 in zip(heights, no_nan_heights)) + + idxerror_weights = np.array([[0.3, 0.25], [0.45, 0.45]]) + + msg = "weights must have the same shape as data, or be a single column" + with pytest.raises(ValueError, match=msg): + _, ax2 = mpl.pyplot.subplots() + no_nan_df.plot.hist(ax=ax2, weights=idxerror_weights) + + +class TestDataFrameGroupByPlots: + def test_grouped_hist_legacy(self): + from pandas.plotting._matplotlib.hist import _grouped_hist + + rs = np.random.default_rng(10) + df = DataFrame(rs.standard_normal((10, 1)), columns=["A"]) + df["B"] = to_datetime( + rs.integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + df["C"] = rs.integers(0, 4, 10) + df["D"] = ["X"] * 10 + + axes = _grouped_hist(df.A, by=df.C) + _check_axes_shape(axes, axes_num=4, layout=(2, 2)) + + def test_grouped_hist_legacy_axes_shape_no_col(self): + rs = np.random.default_rng(10) + df = DataFrame(rs.standard_normal((10, 1)), columns=["A"]) + df["B"] = to_datetime( + rs.integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + df["C"] = rs.integers(0, 4, 10) + df["D"] = ["X"] * 10 + axes = df.hist(by=df.C) + _check_axes_shape(axes, axes_num=4, layout=(2, 2)) + + def test_grouped_hist_legacy_single_key(self): + rs = np.random.default_rng(2) + df = DataFrame(rs.standard_normal((10, 1)), columns=["A"]) + df["B"] = to_datetime( + rs.integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + df["C"] = rs.integers(0, 4, 10) + df["D"] = ["X"] * 10 + # group by a key with single value + axes = df.hist(by="D", rot=30) + _check_axes_shape(axes, axes_num=1, layout=(1, 1)) + _check_ticks_props(axes, xrot=30) + + def test_grouped_hist_legacy_grouped_hist_kwargs(self): + from matplotlib.patches import Rectangle + + from pandas.plotting._matplotlib.hist import _grouped_hist + + rs = np.random.default_rng(2) + df = DataFrame(rs.standard_normal((10, 1)), columns=["A"]) + df["B"] = to_datetime( + rs.integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + df["C"] = rs.integers(0, 4, 10) + # make sure kwargs to hist are handled + xf, yf = 20, 18 + xrot, yrot = 30, 40 + + axes = _grouped_hist( + df.A, + by=df.C, + cumulative=True, + bins=4, + xlabelsize=xf, + xrot=xrot, + ylabelsize=yf, + yrot=yrot, + density=True, + ) + # height of last bin (index 5) must be 1.0 + for ax in axes.ravel(): + rects = [x for x in ax.get_children() if isinstance(x, Rectangle)] + height = rects[-1].get_height() + tm.assert_almost_equal(height, 1.0) + _check_ticks_props(axes, xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot) + + def test_grouped_hist_legacy_grouped_hist(self): + from pandas.plotting._matplotlib.hist import _grouped_hist + + rs = np.random.default_rng(2) + df = DataFrame(rs.standard_normal((10, 1)), columns=["A"]) + df["B"] = to_datetime( + rs.integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + df["C"] = rs.integers(0, 4, 10) + df["D"] = ["X"] * 10 + axes = _grouped_hist(df.A, by=df.C, log=True) + # scale of y must be 'log' + _check_ax_scales(axes, yaxis="log") + + def test_grouped_hist_legacy_external_err(self): + from pandas.plotting._matplotlib.hist import _grouped_hist + + rs = np.random.default_rng(2) + df = DataFrame(rs.standard_normal((10, 1)), columns=["A"]) + df["B"] = to_datetime( + rs.integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + df["C"] = rs.integers(0, 4, 10) + df["D"] = ["X"] * 10 + # propagate attr exception from matplotlib.Axes.hist + with tm.external_error_raised(AttributeError): + _grouped_hist(df.A, by=df.C, foo="bar") + + def test_grouped_hist_legacy_figsize_err(self): + rs = np.random.default_rng(2) + df = DataFrame(rs.standard_normal((10, 1)), columns=["A"]) + df["B"] = to_datetime( + rs.integers( + 812419200000000000, + 819331200000000000, + size=10, + dtype=np.int64, + ) + ) + df["C"] = rs.integers(0, 4, 10) + df["D"] = ["X"] * 10 + msg = "Specify figure size by tuple instead" + with pytest.raises(ValueError, match=msg): + df.hist(by="C", figsize="default") + + def test_grouped_hist_legacy2(self): + n = 10 + weight = Series(np.random.default_rng(2).normal(166, 20, size=n)) + height = Series(np.random.default_rng(2).normal(60, 10, size=n)) + gender_int = np.random.default_rng(2).choice([0, 1], size=n) + df_int = DataFrame({"height": height, "weight": weight, "gender": gender_int}) + gb = df_int.groupby("gender") + axes = gb.hist() + assert len(axes) == 2 + assert len(mpl.pyplot.get_fignums()) == 2 + + @pytest.mark.slow + @pytest.mark.parametrize( + "msg, plot_col, by_col, layout", + [ + [ + "Layout of 1x1 must be larger than required size 2", + "weight", + "gender", + (1, 1), + ], + [ + "Layout of 1x3 must be larger than required size 4", + "height", + "category", + (1, 3), + ], + [ + "At least one dimension of layout must be positive", + "height", + "category", + (-1, -1), + ], + ], + ) + def test_grouped_hist_layout_error(self, hist_df, msg, plot_col, by_col, layout): + df = hist_df + with pytest.raises(ValueError, match=msg): + df.hist(column=plot_col, by=getattr(df, by_col), layout=layout) + + @pytest.mark.slow + def test_grouped_hist_layout_warning(self, hist_df): + df = hist_df + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works( + df.hist, column="height", by=df.gender, layout=(2, 1) + ) + _check_axes_shape(axes, axes_num=2, layout=(2, 1)) + + @pytest.mark.slow + @pytest.mark.parametrize( + "layout, check_layout, figsize", + [[(4, 1), (4, 1), None], [(-1, 1), (4, 1), None], [(4, 2), (4, 2), (12, 8)]], + ) + def test_grouped_hist_layout_figsize(self, hist_df, layout, check_layout, figsize): + df = hist_df + axes = df.hist(column="height", by=df.category, layout=layout, figsize=figsize) + _check_axes_shape(axes, axes_num=4, layout=check_layout, figsize=figsize) + + @pytest.mark.slow + @pytest.mark.parametrize("kwargs", [{}, {"column": "height", "layout": (2, 2)}]) + def test_grouped_hist_layout_by_warning(self, hist_df, kwargs): + df = hist_df + # GH 6769 + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works(df.hist, by="classroom", **kwargs) + _check_axes_shape(axes, axes_num=3, layout=(2, 2)) + + @pytest.mark.slow + @pytest.mark.parametrize( + "kwargs, axes_num, layout", + [ + [{"by": "gender", "layout": (3, 5)}, 2, (3, 5)], + [{"column": ["height", "weight", "category"]}, 3, (2, 2)], + ], + ) + def test_grouped_hist_layout_axes(self, hist_df, kwargs, axes_num, layout): + df = hist_df + axes = df.hist(**kwargs) + _check_axes_shape(axes, axes_num=axes_num, layout=layout) + + def test_grouped_hist_multiple_axes(self, hist_df): + # GH 6970, GH 7069 + df = hist_df + + fig, axes = mpl.pyplot.subplots(2, 3) + returned = df.hist(column=["height", "weight", "category"], ax=axes[0]) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) + tm.assert_numpy_array_equal(returned, axes[0]) + assert returned[0].figure is fig + + def test_grouped_hist_multiple_axes_no_cols(self, hist_df): + # GH 6970, GH 7069 + df = hist_df + + fig, axes = mpl.pyplot.subplots(2, 3) + returned = df.hist(by="classroom", ax=axes[1]) + _check_axes_shape(returned, axes_num=3, layout=(1, 3)) + tm.assert_numpy_array_equal(returned, axes[1]) + assert returned[0].figure is fig + + def test_grouped_hist_multiple_axes_error(self, hist_df): + # GH 6970, GH 7069 + df = hist_df + fig, axes = mpl.pyplot.subplots(2, 3) + # pass different number of axes from required + msg = "The number of passed axes must be 1, the same as the output plot" + with pytest.raises(ValueError, match=msg): + axes = df.hist(column="height", ax=axes) + + def test_axis_share_x(self, hist_df): + df = hist_df + # GH4089 + ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True) + + # share x + assert get_x_axis(ax1).joined(ax1, ax2) + assert get_x_axis(ax2).joined(ax1, ax2) + + # don't share y + assert not get_y_axis(ax1).joined(ax1, ax2) + assert not get_y_axis(ax2).joined(ax1, ax2) + + def test_axis_share_y(self, hist_df): + df = hist_df + ax1, ax2 = df.hist(column="height", by=df.gender, sharey=True) + + # share y + assert get_y_axis(ax1).joined(ax1, ax2) + assert get_y_axis(ax2).joined(ax1, ax2) + + # don't share x + assert not get_x_axis(ax1).joined(ax1, ax2) + assert not get_x_axis(ax2).joined(ax1, ax2) + + def test_axis_share_xy(self, hist_df): + df = hist_df + ax1, ax2 = df.hist(column="height", by=df.gender, sharex=True, sharey=True) + + # share both x and y + assert get_x_axis(ax1).joined(ax1, ax2) + assert get_x_axis(ax2).joined(ax1, ax2) + + assert get_y_axis(ax1).joined(ax1, ax2) + assert get_y_axis(ax2).joined(ax1, ax2) + + @pytest.mark.parametrize( + "histtype, expected", + [ + ("bar", True), + ("barstacked", True), + ("step", False), + ("stepfilled", True), + ], + ) + def test_histtype_argument(self, histtype, expected): + # GH23992 Verify functioning of histtype argument + df = DataFrame( + np.random.default_rng(2).integers(1, 10, size=(10, 2)), columns=["a", "b"] + ) + ax = df.hist(by="a", histtype=histtype) + _check_patches_all_filled(ax, filled=expected) diff --git a/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_misc.py b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..cfb657c2a800fefe2d509ddfb398399af4ce8649 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pandas/tests/plotting/test_misc.py @@ -0,0 +1,720 @@ +""" Test cases for misc plot functions """ +import os + +import numpy as np +import pytest + +import pandas.util._test_decorators as td + +from pandas import ( + DataFrame, + Index, + Series, + Timestamp, + date_range, + interval_range, + period_range, + plotting, + read_csv, +) +import pandas._testing as tm +from pandas.tests.plotting.common import ( + _check_colors, + _check_legend_labels, + _check_plot_works, + _check_text_labels, + _check_ticks_props, +) + +mpl = pytest.importorskip("matplotlib") +plt = pytest.importorskip("matplotlib.pyplot") +cm = pytest.importorskip("matplotlib.cm") + + +@pytest.fixture +def iris(datapath) -> DataFrame: + """ + The iris dataset as a DataFrame. + """ + return read_csv(datapath("io", "data", "csv", "iris.csv")) + + +@td.skip_if_installed("matplotlib") +def test_import_error_message(): + # GH-19810 + df = DataFrame({"A": [1, 2]}) + + with pytest.raises(ImportError, match="matplotlib is required for plotting"): + df.plot() + + +def test_get_accessor_args(): + func = plotting._core.PlotAccessor._get_call_args + + msg = "Called plot accessor for type list, expected Series or DataFrame" + with pytest.raises(TypeError, match=msg): + func(backend_name="", data=[], args=[], kwargs={}) + + msg = "should not be called with positional arguments" + with pytest.raises(TypeError, match=msg): + func(backend_name="", data=Series(dtype=object), args=["line", None], kwargs={}) + + x, y, kind, kwargs = func( + backend_name="", + data=DataFrame(), + args=["x"], + kwargs={"y": "y", "kind": "bar", "grid": False}, + ) + assert x == "x" + assert y == "y" + assert kind == "bar" + assert kwargs == {"grid": False} + + x, y, kind, kwargs = func( + backend_name="pandas.plotting._matplotlib", + data=Series(dtype=object), + args=[], + kwargs={}, + ) + assert x is None + assert y is None + assert kind == "line" + assert len(kwargs) == 24 + + +@pytest.mark.parametrize("kind", plotting.PlotAccessor._all_kinds) +@pytest.mark.parametrize( + "data", [DataFrame(np.arange(15).reshape(5, 3)), Series(range(5))] +) +@pytest.mark.parametrize( + "index", + [ + Index(range(5)), + date_range("2020-01-01", periods=5), + period_range("2020-01-01", periods=5), + ], +) +def test_savefig(kind, data, index): + fig, ax = plt.subplots() + data.index = index + kwargs = {} + if kind in ["hexbin", "scatter", "pie"]: + if isinstance(data, Series): + pytest.skip(f"{kind} not supported with Series") + kwargs = {"x": 0, "y": 1} + data.plot(kind=kind, ax=ax, **kwargs) + fig.savefig(os.devnull) + + +class TestSeriesPlots: + def test_autocorrelation_plot(self): + from pandas.plotting import autocorrelation_plot + + ser = Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + name="ts", + ) + # Ensure no UserWarning when making plot + with tm.assert_produces_warning(None): + _check_plot_works(autocorrelation_plot, series=ser) + _check_plot_works(autocorrelation_plot, series=ser.values) + + ax = autocorrelation_plot(ser, label="Test") + _check_legend_labels(ax, labels=["Test"]) + + @pytest.mark.parametrize("kwargs", [{}, {"lag": 5}]) + def test_lag_plot(self, kwargs): + from pandas.plotting import lag_plot + + ser = Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + name="ts", + ) + _check_plot_works(lag_plot, series=ser, **kwargs) + + def test_bootstrap_plot(self): + from pandas.plotting import bootstrap_plot + + ser = Series( + np.arange(10, dtype=np.float64), + index=date_range("2020-01-01", periods=10), + name="ts", + ) + _check_plot_works(bootstrap_plot, series=ser, size=10) + + +class TestDataFramePlots: + @pytest.mark.parametrize("pass_axis", [False, True]) + def test_scatter_matrix_axis(self, pass_axis): + pytest.importorskip("scipy") + scatter_matrix = plotting.scatter_matrix + + ax = None + if pass_axis: + _, ax = mpl.pyplot.subplots(3, 3) + + df = DataFrame(np.random.default_rng(2).standard_normal((100, 3))) + + # we are plotting multiples on a sub-plot + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works( + scatter_matrix, + frame=df, + range_padding=0.1, + ax=ax, + ) + axes0_labels = axes[0][0].yaxis.get_majorticklabels() + # GH 5662 + expected = ["-2", "0", "2"] + _check_text_labels(axes0_labels, expected) + _check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) + + @pytest.mark.parametrize("pass_axis", [False, True]) + def test_scatter_matrix_axis_smaller(self, pass_axis): + pytest.importorskip("scipy") + scatter_matrix = plotting.scatter_matrix + + ax = None + if pass_axis: + _, ax = mpl.pyplot.subplots(3, 3) + + df = DataFrame(np.random.default_rng(11).standard_normal((100, 3))) + df[0] = (df[0] - 2) / 3 + + # we are plotting multiples on a sub-plot + with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + axes = _check_plot_works( + scatter_matrix, + frame=df, + range_padding=0.1, + ax=ax, + ) + axes0_labels = axes[0][0].yaxis.get_majorticklabels() + expected = ["-1.0", "-0.5", "0.0"] + _check_text_labels(axes0_labels, expected) + _check_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) + + @pytest.mark.slow + def test_andrews_curves_no_warning(self, iris): + from pandas.plotting import andrews_curves + + df = iris + # Ensure no UserWarning when making plot + with tm.assert_produces_warning(None): + _check_plot_works(andrews_curves, frame=df, class_column="Name") + + @pytest.mark.slow + @pytest.mark.parametrize( + "linecolors", + [ + ("#556270", "#4ECDC4", "#C7F464"), + ["dodgerblue", "aquamarine", "seagreen"], + ], + ) + @pytest.mark.parametrize( + "df", + [ + "iris", + DataFrame( + { + "A": np.random.default_rng(2).standard_normal(10), + "B": np.random.default_rng(2).standard_normal(10), + "C": np.random.default_rng(2).standard_normal(10), + "Name": ["A"] * 10, + } + ), + ], + ) + def test_andrews_curves_linecolors(self, request, df, linecolors): + from pandas.plotting import andrews_curves + + if isinstance(df, str): + df = request.getfixturevalue(df) + ax = _check_plot_works( + andrews_curves, frame=df, class_column="Name", color=linecolors + ) + _check_colors( + ax.get_lines()[:10], linecolors=linecolors, mapping=df["Name"][:10] + ) + + @pytest.mark.slow + @pytest.mark.parametrize( + "df", + [ + "iris", + DataFrame( + { + "A": np.random.default_rng(2).standard_normal(10), + "B": np.random.default_rng(2).standard_normal(10), + "C": np.random.default_rng(2).standard_normal(10), + "Name": ["A"] * 10, + } + ), + ], + ) + def test_andrews_curves_cmap(self, request, df): + from pandas.plotting import andrews_curves + + if isinstance(df, str): + df = request.getfixturevalue(df) + cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())] + ax = _check_plot_works( + andrews_curves, frame=df, class_column="Name", color=cmaps + ) + _check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10]) + + @pytest.mark.slow + def test_andrews_curves_handle(self): + from pandas.plotting import andrews_curves + + colors = ["b", "g", "r"] + df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3], "Name": colors}) + ax = andrews_curves(df, "Name", color=colors) + handles, _ = ax.get_legend_handles_labels() + _check_colors(handles, linecolors=colors) + + @pytest.mark.slow + @pytest.mark.parametrize( + "color", + [("#556270", "#4ECDC4", "#C7F464"), ["dodgerblue", "aquamarine", "seagreen"]], + ) + def test_parallel_coordinates_colors(self, iris, color): + from pandas.plotting import parallel_coordinates + + df = iris + + ax = _check_plot_works( + parallel_coordinates, frame=df, class_column="Name", color=color + ) + _check_colors(ax.get_lines()[:10], linecolors=color, mapping=df["Name"][:10]) + + @pytest.mark.slow + def test_parallel_coordinates_cmap(self, iris): + from matplotlib import cm + + from pandas.plotting import parallel_coordinates + + df = iris + + ax = _check_plot_works( + parallel_coordinates, frame=df, class_column="Name", colormap=cm.jet + ) + cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())] + _check_colors(ax.get_lines()[:10], linecolors=cmaps, mapping=df["Name"][:10]) + + @pytest.mark.slow + def test_parallel_coordinates_line_diff(self, iris): + from pandas.plotting import parallel_coordinates + + df = iris + + ax = _check_plot_works(parallel_coordinates, frame=df, class_column="Name") + nlines = len(ax.get_lines()) + nxticks = len(ax.xaxis.get_ticklabels()) + + ax = _check_plot_works( + parallel_coordinates, frame=df, class_column="Name", axvlines=False + ) + assert len(ax.get_lines()) == (nlines - nxticks) + + @pytest.mark.slow + def test_parallel_coordinates_handles(self, iris): + from pandas.plotting import parallel_coordinates + + df = iris + colors = ["b", "g", "r"] + df = DataFrame({"A": [1, 2, 3], "B": [1, 2, 3], "C": [1, 2, 3], "Name": colors}) + ax = parallel_coordinates(df, "Name", color=colors) + handles, _ = ax.get_legend_handles_labels() + _check_colors(handles, linecolors=colors) + + # not sure if this is indicative of a problem + @pytest.mark.filterwarnings("ignore:Attempting to set:UserWarning") + def test_parallel_coordinates_with_sorted_labels(self): + """For #15908""" + from pandas.plotting import parallel_coordinates + + df = DataFrame( + { + "feat": list(range(30)), + "class": [2 for _ in range(10)] + + [3 for _ in range(10)] + + [1 for _ in range(10)], + } + ) + ax = parallel_coordinates(df, "class", sort_labels=True) + polylines, labels = ax.get_legend_handles_labels() + color_label_tuples = zip( + [polyline.get_color() for polyline in polylines], labels + ) + ordered_color_label_tuples = sorted(color_label_tuples, key=lambda x: x[1]) + prev_next_tupels = zip( + list(ordered_color_label_tuples[0:-1]), list(ordered_color_label_tuples[1:]) + ) + for prev, nxt in prev_next_tupels: + # labels and colors are ordered strictly increasing + assert prev[1] < nxt[1] and prev[0] < nxt[0] + + def test_radviz_no_warning(self, iris): + from pandas.plotting import radviz + + df = iris + # Ensure no UserWarning when making plot + with tm.assert_produces_warning(None): + _check_plot_works(radviz, frame=df, class_column="Name") + + @pytest.mark.parametrize( + "color", + [("#556270", "#4ECDC4", "#C7F464"), ["dodgerblue", "aquamarine", "seagreen"]], + ) + def test_radviz_color(self, iris, color): + from pandas.plotting import radviz + + df = iris + ax = _check_plot_works(radviz, frame=df, class_column="Name", color=color) + # skip Circle drawn as ticks + patches = [p for p in ax.patches[:20] if p.get_label() != ""] + _check_colors(patches[:10], facecolors=color, mapping=df["Name"][:10]) + + def test_radviz_color_cmap(self, iris): + from matplotlib import cm + + from pandas.plotting import radviz + + df = iris + ax = _check_plot_works(radviz, frame=df, class_column="Name", colormap=cm.jet) + cmaps = [cm.jet(n) for n in np.linspace(0, 1, df["Name"].nunique())] + patches = [p for p in ax.patches[:20] if p.get_label() != ""] + _check_colors(patches, facecolors=cmaps, mapping=df["Name"][:10]) + + def test_radviz_colors_handles(self): + from pandas.plotting import radviz + + colors = [[0.0, 0.0, 1.0, 1.0], [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]] + df = DataFrame( + {"A": [1, 2, 3], "B": [2, 1, 3], "C": [3, 2, 1], "Name": ["b", "g", "r"]} + ) + ax = radviz(df, "Name", color=colors) + handles, _ = ax.get_legend_handles_labels() + _check_colors(handles, facecolors=colors) + + def test_subplot_titles(self, iris): + df = iris.drop("Name", axis=1).head() + # Use the column names as the subplot titles + title = list(df.columns) + + # Case len(title) == len(df) + plot = df.plot(subplots=True, title=title) + assert [p.get_title() for p in plot] == title + + def test_subplot_titles_too_much(self, iris): + df = iris.drop("Name", axis=1).head() + # Use the column names as the subplot titles + title = list(df.columns) + # Case len(title) > len(df) + msg = ( + "The length of `title` must equal the number of columns if " + "using `title` of type `list` and `subplots=True`" + ) + with pytest.raises(ValueError, match=msg): + df.plot(subplots=True, title=title + ["kittens > puppies"]) + + def test_subplot_titles_too_little(self, iris): + df = iris.drop("Name", axis=1).head() + # Use the column names as the subplot titles + title = list(df.columns) + msg = ( + "The length of `title` must equal the number of columns if " + "using `title` of type `list` and `subplots=True`" + ) + # Case len(title) < len(df) + with pytest.raises(ValueError, match=msg): + df.plot(subplots=True, title=title[:2]) + + def test_subplot_titles_subplots_false(self, iris): + df = iris.drop("Name", axis=1).head() + # Use the column names as the subplot titles + title = list(df.columns) + # Case subplots=False and title is of type list + msg = ( + "Using `title` of type `list` is not supported unless " + "`subplots=True` is passed" + ) + with pytest.raises(ValueError, match=msg): + df.plot(subplots=False, title=title) + + def test_subplot_titles_numeric_square_layout(self, iris): + df = iris.drop("Name", axis=1).head() + # Use the column names as the subplot titles + title = list(df.columns) + # Case df with 3 numeric columns but layout of (2,2) + plot = df.drop("SepalWidth", axis=1).plot( + subplots=True, layout=(2, 2), title=title[:-1] + ) + title_list = [ax.get_title() for sublist in plot for ax in sublist] + assert title_list == title[:3] + [""] + + def test_get_standard_colors_random_seed(self): + # GH17525 + df = DataFrame(np.zeros((10, 10))) + + # Make sure that the random seed isn't reset by get_standard_colors + plotting.parallel_coordinates(df, 0) + rand1 = np.random.default_rng(None).random() + plotting.parallel_coordinates(df, 0) + rand2 = np.random.default_rng(None).random() + assert rand1 != rand2 + + def test_get_standard_colors_consistency(self): + # GH17525 + # Make sure it produces the same colors every time it's called + from pandas.plotting._matplotlib.style import get_standard_colors + + color1 = get_standard_colors(1, color_type="random") + color2 = get_standard_colors(1, color_type="random") + assert color1 == color2 + + def test_get_standard_colors_default_num_colors(self): + from pandas.plotting._matplotlib.style import get_standard_colors + + # Make sure the default color_types returns the specified amount + color1 = get_standard_colors(1, color_type="default") + color2 = get_standard_colors(9, color_type="default") + color3 = get_standard_colors(20, color_type="default") + assert len(color1) == 1 + assert len(color2) == 9 + assert len(color3) == 20 + + def test_plot_single_color(self): + # Example from #20585. All 3 bars should have the same color + df = DataFrame( + { + "account-start": ["2017-02-03", "2017-03-03", "2017-01-01"], + "client": ["Alice Anders", "Bob Baker", "Charlie Chaplin"], + "balance": [-1432.32, 10.43, 30000.00], + "db-id": [1234, 2424, 251], + "proxy-id": [525, 1525, 2542], + "rank": [52, 525, 32], + } + ) + ax = df.client.value_counts().plot.bar() + colors = [rect.get_facecolor() for rect in ax.get_children()[0:3]] + assert all(color == colors[0] for color in colors) + + def test_get_standard_colors_no_appending(self): + # GH20726 + + # Make sure not to add more colors so that matplotlib can cycle + # correctly. + from matplotlib import cm + + from pandas.plotting._matplotlib.style import get_standard_colors + + color_before = cm.gnuplot(range(5)) + color_after = get_standard_colors(1, color=color_before) + assert len(color_after) == len(color_before) + + df = DataFrame( + np.random.default_rng(2).standard_normal((48, 4)), columns=list("ABCD") + ) + + color_list = cm.gnuplot(np.linspace(0, 1, 16)) + p = df.A.plot.bar(figsize=(16, 7), color=color_list) + assert p.patches[1].get_facecolor() == p.patches[17].get_facecolor() + + @pytest.mark.parametrize("kind", ["bar", "line"]) + def test_dictionary_color(self, kind): + # issue-8193 + # Test plot color dictionary format + data_files = ["a", "b"] + + expected = [(0.5, 0.24, 0.6), (0.3, 0.7, 0.7)] + + df1 = DataFrame(np.random.default_rng(2).random((2, 2)), columns=data_files) + dic_color = {"b": (0.3, 0.7, 0.7), "a": (0.5, 0.24, 0.6)} + + ax = df1.plot(kind=kind, color=dic_color) + if kind == "bar": + colors = [rect.get_facecolor()[0:-1] for rect in ax.get_children()[0:3:2]] + else: + colors = [rect.get_color() for rect in ax.get_lines()[0:2]] + assert all(color == expected[index] for index, color in enumerate(colors)) + + def test_bar_plot(self): + # GH38947 + # Test bar plot with string and int index + from matplotlib.text import Text + + expected = [Text(0, 0, "0"), Text(1, 0, "Total")] + + df = DataFrame( + { + "a": [1, 2], + }, + index=Index([0, "Total"]), + ) + plot_bar = df.plot.bar() + assert all( + (a.get_text() == b.get_text()) + for a, b in zip(plot_bar.get_xticklabels(), expected) + ) + + def test_barh_plot_labels_mixed_integer_string(self): + # GH39126 + # Test barh plot with string and integer at the same column + from matplotlib.text import Text + + df = DataFrame([{"word": 1, "value": 0}, {"word": "knowledge", "value": 2}]) + plot_barh = df.plot.barh(x="word", legend=None) + expected_yticklabels = [Text(0, 0, "1"), Text(0, 1, "knowledge")] + assert all( + actual.get_text() == expected.get_text() + for actual, expected in zip( + plot_barh.get_yticklabels(), expected_yticklabels + ) + ) + + def test_has_externally_shared_axis_x_axis(self): + # GH33819 + # Test _has_externally_shared_axis() works for x-axis + func = plotting._matplotlib.tools._has_externally_shared_axis + + fig = mpl.pyplot.figure() + plots = fig.subplots(2, 4) + + # Create *externally* shared axes for first and third columns + plots[0][0] = fig.add_subplot(231, sharex=plots[1][0]) + plots[0][2] = fig.add_subplot(233, sharex=plots[1][2]) + + # Create *internally* shared axes for second and third columns + plots[0][1].twinx() + plots[0][2].twinx() + + # First column is only externally shared + # Second column is only internally shared + # Third column is both + # Fourth column is neither + assert func(plots[0][0], "x") + assert not func(plots[0][1], "x") + assert func(plots[0][2], "x") + assert not func(plots[0][3], "x") + + def test_has_externally_shared_axis_y_axis(self): + # GH33819 + # Test _has_externally_shared_axis() works for y-axis + func = plotting._matplotlib.tools._has_externally_shared_axis + + fig = mpl.pyplot.figure() + plots = fig.subplots(4, 2) + + # Create *externally* shared axes for first and third rows + plots[0][0] = fig.add_subplot(321, sharey=plots[0][1]) + plots[2][0] = fig.add_subplot(325, sharey=plots[2][1]) + + # Create *internally* shared axes for second and third rows + plots[1][0].twiny() + plots[2][0].twiny() + + # First row is only externally shared + # Second row is only internally shared + # Third row is both + # Fourth row is neither + assert func(plots[0][0], "y") + assert not func(plots[1][0], "y") + assert func(plots[2][0], "y") + assert not func(plots[3][0], "y") + + def test_has_externally_shared_axis_invalid_compare_axis(self): + # GH33819 + # Test _has_externally_shared_axis() raises an exception when + # passed an invalid value as compare_axis parameter + func = plotting._matplotlib.tools._has_externally_shared_axis + + fig = mpl.pyplot.figure() + plots = fig.subplots(4, 2) + + # Create arbitrary axes + plots[0][0] = fig.add_subplot(321, sharey=plots[0][1]) + + # Check that an invalid compare_axis value triggers the expected exception + msg = "needs 'x' or 'y' as a second parameter" + with pytest.raises(ValueError, match=msg): + func(plots[0][0], "z") + + def test_externally_shared_axes(self): + # Example from GH33819 + # Create data + df = DataFrame( + { + "a": np.random.default_rng(2).standard_normal(1000), + "b": np.random.default_rng(2).standard_normal(1000), + } + ) + + # Create figure + fig = mpl.pyplot.figure() + plots = fig.subplots(2, 3) + + # Create *externally* shared axes + plots[0][0] = fig.add_subplot(231, sharex=plots[1][0]) + # note: no plots[0][1] that's the twin only case + plots[0][2] = fig.add_subplot(233, sharex=plots[1][2]) + + # Create *internally* shared axes + # note: no plots[0][0] that's the external only case + twin_ax1 = plots[0][1].twinx() + twin_ax2 = plots[0][2].twinx() + + # Plot data to primary axes + df["a"].plot(ax=plots[0][0], title="External share only").set_xlabel( + "this label should never be visible" + ) + df["a"].plot(ax=plots[1][0]) + + df["a"].plot(ax=plots[0][1], title="Internal share (twin) only").set_xlabel( + "this label should always be visible" + ) + df["a"].plot(ax=plots[1][1]) + + df["a"].plot(ax=plots[0][2], title="Both").set_xlabel( + "this label should never be visible" + ) + df["a"].plot(ax=plots[1][2]) + + # Plot data to twinned axes + df["b"].plot(ax=twin_ax1, color="green") + df["b"].plot(ax=twin_ax2, color="yellow") + + assert not plots[0][0].xaxis.get_label().get_visible() + assert plots[0][1].xaxis.get_label().get_visible() + assert not plots[0][2].xaxis.get_label().get_visible() + + def test_plot_bar_axis_units_timestamp_conversion(self): + # GH 38736 + # Ensure string x-axis from the second plot will not be converted to datetime + # due to axis data from first plot + df = DataFrame( + [1.0], + index=[Timestamp("2022-02-22 22:22:22")], + ) + _check_plot_works(df.plot) + s = Series({"A": 1.0}) + _check_plot_works(s.plot.bar) + + def test_bar_plt_xaxis_intervalrange(self): + # GH 38969 + # Ensure IntervalIndex x-axis produces a bar plot as expected + from matplotlib.text import Text + + expected = [Text(0, 0, "([0, 1],)"), Text(1, 0, "([1, 2],)")] + s = Series( + [1, 2], + index=[interval_range(0, 2, closed="both")], + ) + _check_plot_works(s.plot.bar) + assert all( + (a.get_text() == b.get_text()) + for a, b in zip(s.plot.bar().get_xticklabels(), expected) + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ba41360058caf533f3baa9fc016e552fcfdbccfa --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/METADATA @@ -0,0 +1,188 @@ +Metadata-Version: 2.4 +Name: pdb-tools +Version: 2.6.1 +Summary: A swiss army knife for PDB files. +Home-page: http://bonvinlab.org/pdb-tools +Author: Joao Rodrigues +Author-email: j.p.g.l.m.rodrigues@gmail.com +License: Apache Software License, version 2 +Project-URL: Bug Reports, https://github.com/haddocking/pdb-tools/issues +Project-URL: Source, https://github.com/haddocking/pdb-tools +Keywords: bioinformatics protein structural-biology pdb +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Science/Research +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Chemistry +Classifier: Topic :: Scientific/Engineering :: Bio-Informatics +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Description-Content-Type: text/markdown +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: project-url +Dynamic: summary + +# pdb-tools + +[![PyPI version](https://badge.fury.io/py/pdb-tools.svg)](https://pypi.python.org/pypi/pdb-tools) +[![PyPi Downloads](https://img.shields.io/pypi/dm/pdb-tools.svg)](https://pypi.python.org/pypi/pdb-tools) +[![ci](https://github.com/haddocking/pdb-tools/actions/workflows/ci.yml/badge.svg)](https://github.com/haddocking/pdb-tools/actions/workflows/ci.yml) +[![DOI](https://zenodo.org/badge/27217350.svg)](https://doi.org/10.12688/f1000research.17456.1) + +A swiss army knife for manipulating and editing PDB files. + + +## Looking for the _other_ pdb-tools? +The Harms lab maintains a set of tools also called `pdbtools`, which perform a +slightly different set of functions. You can find them [here](https://github.com/harmslab/pdbtools). + + +## About +Manipulating PDB files is often painful. Extracting a particular chain or set of +residues, renumbering residues, splitting or merging models and chains, or just +ensuring the file is conforming to the PDB specifications are examples of tasks +that can be done using any decent parsing library or graphical interface. These, +however, almost always require 1) scripting knowledge, 2) time, and 3) installing +one or more programs. + +`pdb-tools` were designed to be a swiss-knife for the PDB format. They have no +external dependencies, besides obviously the [Python programming language](http://www.python.org). +They are the descendant of a set of old FORTRAN77 programs that had the +particular advantage of working with streams, i.e. the output of one script +could be piped into another. Since FORTRAN77 is a pain too, I rewrote them in +Python and added a few more utilities. + +The philosophy of the scripts is simple: one script, one task. If you want to +do two things, pipe the scripts together. Requests for new scripts will be taken +into consideration - use the Issues button or write them yourself and create a +Pull Request. + + +## Installation Instructions +`pdb-tools` are available on PyPi and can be installed though `pip`. This is the +recommended way as it makes updating/uninstalling rather simple: +```bash +pip install pdb-tools +``` + +Because we use semantic versioning in the development of `pdb-tools`, every bugfix +or new feature results in a new version of the software that is automatically published +on PyPI. As such, there is no difference between the code on github and the latest version +you can install with `pip`. To update your installation to the latest version of the code +run: +```bash +pip install --upgrade pdb-tools +``` + +## What can I do with them? +The names of the tools should be self-explanatory. Their command-line interface +is also pretty consistent. Therefore, here is a couple of examples to get you +started: + +* Downloading a structure + ```bash + pdb_fetch 1brs > 1brs.pdb # 6 chains + pdb_fetch -biounit 1brs > 1brs.pdb # 2 chains + ``` + +* Renumbering a structure + ```bash + pdb_reres -1 1ctf.pdb > 1ctf_renumbered.pdb + ``` + +* Selecting chain(s) + ```bash + pdb_selchain -A 1brs.pdb > 1brs_A.pdb + pdb_selchain -A,D 1brs.pdb > 1brs_AD.pdb + ``` + +* Deleting hydrogens + ```bash + pdb_delelem -H 1brs.pdb > 1brs_noH.pdb + ``` + +* Selecting backbone atoms + ```bash + pdb_selatom -CA,C,N,O 1brs.pdb > 1brs_bb.pdb + ``` + +* Selecting chains, removing HETATM, and producing a valid PDB file + ```bash + pdb_selchain -A,D 1brs.pdb | pdb_delhetatm | pdb_tidy > 1brs_AD_noHET.pdb + ``` + +*Note: On Windows the tools will have the `.exe` extension.* + + +## What _can't_ I do with them? +Operations that involve coordinates or numerical calculations are usually not in +the scope of `pdb-tools`. Use a proper library for that, it will be much faster +and scalable. Also, although we provide mmCIF<->PDB converters, we do not support +large mmCIF files with more than 99999 atoms, or 9999 residues in a single chain. +Our tools will complain if you try using them on such a molecule. + + +## Citation +We finally decided to write up a small publication describing the tools. If you +used them in a project that is going to be published, please cite us: + +``` +Rodrigues JPGLM, Teixeira JMC, Trellet M and Bonvin AMJJ. +pdb-tools: a swiss army knife for molecular structures. +F1000Research 2018, 7:1961 (https://doi.org/10.12688/f1000research.17456.1) +``` + +If you use a reference manager that supports BibTex, use this record: +``` +@Article{ 10.12688/f1000research.17456.1, +AUTHOR = { Rodrigues, JPGLM and Teixeira, JMC and Trellet, M and Bonvin, AMJJ}, +TITLE = {pdb-tools: a swiss army knife for molecular structures [version 1; peer review: 2 approved] +}, +JOURNAL = {F1000Research}, +VOLUME = {7}, +YEAR = {2018}, +NUMBER = {1961}, +DOI = {10.12688/f1000research.17456.1} +} +``` + +## Requirements +`pdb-tools` should run on Python 2.7+ and Python 3.x. We test on Python 2.7, 3.6, +and 3.7. There are no dependencies. + + +## Installing from Source +Download the zip archive or clone the repository with git. We recommend the `git` +approach since it makes updating the tools extremely simple. + +```bash +# To download +git clone https://github.com/haddocking/pdb-tools +cd pdb-tools + +# To update +git pull origin master + +# To install +python setup.py install +``` + +## Contributing +If you want to contribute to the development of `pdb-tools`, provide a bug fix, +or a new tools, read our `CONTRIBUTING` instructions [here](https://github.com/haddocking/pdb-tools/blob/master/CONTRIBUTING.md). + +## License +`pdb-tools` are open-source and licensed under the Apache License, version 2.0. +For details, see the LICENSE file. diff --git a/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ef485c50525b906bfb5e43429f83715f4eecf17b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/RECORD @@ -0,0 +1,154 @@ +../../../bin/__init__,sha256=jZ-WBF-ToEEHRhaTxt_GQk2Hm8BjhScIVFgyoiE_FbE,212 +../../../bin/pdb_b,sha256=gj7ahRsRdGPc3Kz3ESNjZlE3KXdcNM3y1oWLRX0UR4U,209 +../../../bin/pdb_chain,sha256=z_oDFAsfU7vGX1udLeTyydCAUMaCEHRx0iYM2_BuTD8,213 +../../../bin/pdb_chainbows,sha256=GKBDyCS-NmupQ2FJA8j_UcV6aq1bB_0ODQNsIByz6Ks,217 +../../../bin/pdb_chainxseg,sha256=JB5iCcD890WH-xQPyahGOFgeXP9CFbut6Er16tVYV6w,217 +../../../bin/pdb_chkensemble,sha256=FBRHlPbc0gTaX80GM2TFrB9Evg_8M5yQ2x_sCMxpgFA,219 +../../../bin/pdb_delchain,sha256=Vc-wygTlSRMJ17Y2cOMXUC0aF0MG3IkfRqQgDUg0Bx0,216 +../../../bin/pdb_delelem,sha256=z9mCrfIzvSBG9nkCdeymy4c5THiIJxjzySG7NdiTxqk,215 +../../../bin/pdb_delhetatm,sha256=ZOSn3g3Z3T2Jx2QlYLJM75gwc4ChjCgS9NJavY3xS68,217 +../../../bin/pdb_delinsertion,sha256=GhwPBkDKhiRB2EDIzmlKFZ9tgjXO3F9Oaltxt2mSjOw,220 +../../../bin/pdb_delres,sha256=oONWaocAQ3UzN1hMSuYa4hOJHGx3rNo7Tzpzj8s_h2w,214 +../../../bin/pdb_delresname,sha256=6kOvleuCDPkIfsFXAlysWDg65-S7jyEtUQYsNODS3Kk,218 +../../../bin/pdb_element,sha256=ZqwldS9nzWkBCjckCHaaCmEBg_b6g8oNP4aSWREYMZQ,215 +../../../bin/pdb_fetch,sha256=p6ozir017UyP06H7J78UBdfpBRXS1iE5i710-KdnQfE,213 +../../../bin/pdb_fixinsert,sha256=DJKySGzDXF7qg_dDiunSth-k47x0eHxy_WK9SD1nxU4,217 +../../../bin/pdb_fromcif,sha256=obxT82b90c3ab-3E_4r4Xnp_LT_J2DUbdrB3ZJfD7xk,215 +../../../bin/pdb_gap,sha256=yf6oTudFZq7H4ioRXn9i8TqJDdxaTE14Ho8ev9SStqc,211 +../../../bin/pdb_head,sha256=9xHdY0tcNER7d5VBepazuZfsyyrSYCIdep-yE8rQFEQ,212 +../../../bin/pdb_intersect,sha256=Fs0xiWsyYSsXHwYjw1PHunMdk6h1NlcJiPiOVkA6Kus,217 +../../../bin/pdb_keepcoord,sha256=ZM1PPZLVns3mUP9qvwhulO_82Ob_CqIV4G4KxRIVPQA,217 +../../../bin/pdb_merge,sha256=PEu1K6z8CURfkiCbzty00ODFF58M3TRKY_vqI8rX_BM,213 +../../../bin/pdb_mkensemble,sha256=O4wPycSA6n5V2cohdV5xggxeCGX946CQHO8XLDs4ymI,218 +../../../bin/pdb_occ,sha256=Jkcf-3ZWy12xXGxgDUHRnVJkW-9GQftV9dbBjJmAMfQ,211 +../../../bin/pdb_reatom,sha256=BFzPVysnUTzhb_2Jsr383FvXQsOKHntYK2lZis55WZI,214 +../../../bin/pdb_reres,sha256=MuxB3F1sBv4wZJWqfNpPMQIqBA0crqu9oVanPj1jJw0,213 +../../../bin/pdb_rplchain,sha256=yObfS2cM-NGQc_tDVnulkqWbPiwkg15KZLaXBt_tB18,216 +../../../bin/pdb_rplresname,sha256=UrSLu8SadDBCAIwDyHcU_gFwrU0prQoBHa_LDe-vahc,218 +../../../bin/pdb_seg,sha256=0njFqu7M1w4y93HH7qMbXxz-9N9LCwqz0sG41YHqiO4,211 +../../../bin/pdb_segxchain,sha256=qVbhMr9eUh9cl6aT1VR-OC5_QxG8JnvbOcngjJvczmc,217 +../../../bin/pdb_selaltloc,sha256=gvo3itYsrZDZK4tFIy_JqTpa3JlQlm-MaZ7Svv6cLbo,217 +../../../bin/pdb_selatom,sha256=fmAufzthp3dZmFfhuzF3hAU4yatkF9dJP7IyBoElmWw,215 +../../../bin/pdb_selchain,sha256=cqGCtF19fyeqcfiGz3WwfpeFuOolzY_Joqd8biczSyI,216 +../../../bin/pdb_selelem,sha256=uEplQTOJQV07bTOaNP6ZmbUSZis9yOg7X5idhxUsFl8,215 +../../../bin/pdb_selhetatm,sha256=ceohikcPMtC1YMO9lhufYM2NkVnwtc0jVDOsopksv8E,217 +../../../bin/pdb_selmodel,sha256=lSZovwxXKN8yZuhVL4X9XeHsmbhaihX8B2Plc2zD770,216 +../../../bin/pdb_selres,sha256=KccmCuDPGk230UxZ5VzJ788kHzg_U8EkqALMo3_5cRw,214 +../../../bin/pdb_selresname,sha256=QX2GaPySsFKB0W1ItdDEw-zITA-IKmaX4C8ksm6cuZU,218 +../../../bin/pdb_selseg,sha256=cusxqB3LIaxH5vVf-B2Iz71Nr8WGiJrW2QxVhdXrBpY,214 +../../../bin/pdb_shiftres,sha256=OCPZLolRUWzmU2vz1fieUixwUg3vlj8pEpLd6tuG9E4,216 +../../../bin/pdb_sort,sha256=QSf3DadfrYw8N3vQrohxnWC0jrKhUjNIIVC5khmY0WI,212 +../../../bin/pdb_splitchain,sha256=uBem_FVsZxsMH6mJPfVrUW86p8iMPBWyJ-nTbpMTDdA,218 +../../../bin/pdb_splitmodel,sha256=DqpKGmGBfBfhuNGcHhgWplX17KnR2IOeWrGi25js89s,218 +../../../bin/pdb_splitseg,sha256=qaXV8i8IGlTk10o8pjyKHcG04NkJN9gShUWbKqIGoOw,216 +../../../bin/pdb_tidy,sha256=3Z1T2bFG1AS3GbeixO21I8ts7CRt6ikOCqwb9XDbM78,212 +../../../bin/pdb_tocif,sha256=LJmeFBX7sfFi9Dfnd0jK4OoYvm-Qg_wfCIxwtoWgpYc,213 +../../../bin/pdb_tofasta,sha256=_Fx2nSYFJCEP6z4892utVtJW3gQmKZiiY_sha3z8LYM,215 +../../../bin/pdb_uniqname,sha256=jVFxR6_ek9DZGyc9L-FRlrlmTdqv6n2ZZLx8tbzaWJA,216 +../../../bin/pdb_validate,sha256=QEODCfhmYm705O1TNKB_riX1FcTyGYysmFXwcI17N2s,216 +../../../bin/pdb_wc,sha256=lppK0jzPgB7PUTFWGY0bT50tqzkqhmELqdh6dbdoU80,210 +pdb_tools-2.6.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pdb_tools-2.6.1.dist-info/METADATA,sha256=wwUspjg5lRk1DE8pCVlqkkWz7ibWAuypVp6oPJqQDFY,6780 +pdb_tools-2.6.1.dist-info/RECORD,, +pdb_tools-2.6.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92 +pdb_tools-2.6.1.dist-info/entry_points.txt,sha256=ZwR1wuBJ03mYzXiYYToZqtHlw1CV4OQxAUgJ2iR_AXk,1986 +pdb_tools-2.6.1.dist-info/licenses/LICENSE,sha256=cT2RbiAZ-YA-Vr_FpRv5cgvS3zh_KjQlBnvoewjElNQ,11350 +pdb_tools-2.6.1.dist-info/top_level.txt,sha256=VJ80Sd0ldoM5Fb0EG_JRbs2GmslbFIKBL8Y0Rok8q-U,9 +pdbtools/__init__.py,sha256=FN83ZHvtgK83OaOvhaKBJXqvn44ikqLt1pXloqS03O8,3320 +pdbtools/__pycache__/__init__.cpython-312.pyc,, +pdbtools/__pycache__/pdb_b.cpython-312.pyc,, +pdbtools/__pycache__/pdb_chain.cpython-312.pyc,, +pdbtools/__pycache__/pdb_chainbows.cpython-312.pyc,, +pdbtools/__pycache__/pdb_chainxseg.cpython-312.pyc,, +pdbtools/__pycache__/pdb_chkensemble.cpython-312.pyc,, +pdbtools/__pycache__/pdb_delchain.cpython-312.pyc,, +pdbtools/__pycache__/pdb_delelem.cpython-312.pyc,, +pdbtools/__pycache__/pdb_delhetatm.cpython-312.pyc,, +pdbtools/__pycache__/pdb_delinsertion.cpython-312.pyc,, +pdbtools/__pycache__/pdb_delres.cpython-312.pyc,, +pdbtools/__pycache__/pdb_delresname.cpython-312.pyc,, +pdbtools/__pycache__/pdb_element.cpython-312.pyc,, +pdbtools/__pycache__/pdb_fetch.cpython-312.pyc,, +pdbtools/__pycache__/pdb_fixinsert.cpython-312.pyc,, +pdbtools/__pycache__/pdb_fromcif.cpython-312.pyc,, +pdbtools/__pycache__/pdb_gap.cpython-312.pyc,, +pdbtools/__pycache__/pdb_head.cpython-312.pyc,, +pdbtools/__pycache__/pdb_intersect.cpython-312.pyc,, +pdbtools/__pycache__/pdb_keepcoord.cpython-312.pyc,, +pdbtools/__pycache__/pdb_merge.cpython-312.pyc,, +pdbtools/__pycache__/pdb_mkensemble.cpython-312.pyc,, +pdbtools/__pycache__/pdb_occ.cpython-312.pyc,, +pdbtools/__pycache__/pdb_reatom.cpython-312.pyc,, +pdbtools/__pycache__/pdb_reres.cpython-312.pyc,, +pdbtools/__pycache__/pdb_rplchain.cpython-312.pyc,, +pdbtools/__pycache__/pdb_rplresname.cpython-312.pyc,, +pdbtools/__pycache__/pdb_seg.cpython-312.pyc,, +pdbtools/__pycache__/pdb_segxchain.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selaltloc.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selatom.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selchain.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selelem.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selhetatm.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selmodel.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selres.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selresname.cpython-312.pyc,, +pdbtools/__pycache__/pdb_selseg.cpython-312.pyc,, +pdbtools/__pycache__/pdb_shiftres.cpython-312.pyc,, +pdbtools/__pycache__/pdb_sort.cpython-312.pyc,, +pdbtools/__pycache__/pdb_splitchain.cpython-312.pyc,, +pdbtools/__pycache__/pdb_splitmodel.cpython-312.pyc,, +pdbtools/__pycache__/pdb_splitseg.cpython-312.pyc,, +pdbtools/__pycache__/pdb_tidy.cpython-312.pyc,, +pdbtools/__pycache__/pdb_tocif.cpython-312.pyc,, +pdbtools/__pycache__/pdb_tofasta.cpython-312.pyc,, +pdbtools/__pycache__/pdb_uniqname.cpython-312.pyc,, +pdbtools/__pycache__/pdb_validate.cpython-312.pyc,, +pdbtools/__pycache__/pdb_wc.cpython-312.pyc,, +pdbtools/pdb_b.py,sha256=stTb1z6uzpUl564wfcU6SqR5f8eLGP5B-l5TuyKQBfs,5026 +pdbtools/pdb_chain.py,sha256=pA4k_Qc25eYEu7Cuq0T9uiKcPckpG-ZisOiKyE16Ako,4955 +pdbtools/pdb_chainbows.py,sha256=L91PjEINGsD5dioND5spVbQ31MzJRFRP8pwfa_mp9Ts,4486 +pdbtools/pdb_chainxseg.py,sha256=tVTNwSdCJ-k3B98UbEMhVXGTO6mjM5IImWfhVBBYfYE,3812 +pdbtools/pdb_chkensemble.py,sha256=w64kSWqWDxLnpCNu-HxZTQq1sNTKtD4xWfS7koyObMA,5282 +pdbtools/pdb_delchain.py,sha256=MFEHI2oRenKPhMZeRnoXLW9dETHN7GTdDR2Rw-mhnzI,5201 +pdbtools/pdb_delelem.py,sha256=9QBYgh7mIBf4Bvj2mVPe6Wr73QUcKz8JH9PcUxBoqJo,5258 +pdbtools/pdb_delhetatm.py,sha256=9R4NLqSvFOX9Na6_HVMhT5hy1rT_2Rj2w4_XrdW1IBY,3740 +pdbtools/pdb_delinsertion.py,sha256=hKTnjwfMPJ2QOPmwd1wMyScfPrGEEz-CcJk45ZB8wX4,2243 +pdbtools/pdb_delres.py,sha256=ZrCQbPkMHye3FpxyvMuc5FYj1KWh5xwrEoMW0OzHehU,7907 +pdbtools/pdb_delresname.py,sha256=aNOyr_LcYO4UakaPuJxC64s6pd1ZnZTx2wJ3up_Mvow,5209 +pdbtools/pdb_element.py,sha256=dnij6pHjzRCrVQ-CerlQBe3QqZ_FRpajV1l-7jYvDQY,5321 +pdbtools/pdb_fetch.py,sha256=QU6hRsyDeY9xZJMk5mv8_QaoMQVJCyIB4Pvp2Hs6tc4,4800 +pdbtools/pdb_fixinsert.py,sha256=vKK7ucVh8Ipx3kHpYN-KetQg7Rr0lC1O_E71FBHZ3jE,7092 +pdbtools/pdb_fromcif.py,sha256=55_XeSJGAiODeDdDYmraIoJuWYpcIJjxR2j9_5wMKkg,8168 +pdbtools/pdb_gap.py,sha256=SHQp7W_Lc4z7Pr1_xdjy67IYHYMboMgXF1JaQ5pdIn0,4326 +pdbtools/pdb_head.py,sha256=0GPzlYIQZIugMZLLXtHwPGvvY4ukNJIg3gNgSkjocDg,5082 +pdbtools/pdb_intersect.py,sha256=JFo8_7kqJGHSjZjEPsCjeTBj2L3pUxtUB3rH8leK7rg,3890 +pdbtools/pdb_keepcoord.py,sha256=Y-2B-4RLsuCdoGPd7AQ94SDm7Qt4LCjaxEsytEDSRrc,3444 +pdbtools/pdb_merge.py,sha256=ZGfiKOrakzzC_EI5I4IPujCVrmW5tnpDLBWFWxLe7o0,3096 +pdbtools/pdb_mkensemble.py,sha256=MMldN9gWgaLk5HaeKpiE4eNXRaGOsALNbr4NE4MPzCU,4145 +pdbtools/pdb_occ.py,sha256=_lpq2oHXx1h7hTXA276sGxgMlgDQ2eqGQuWtp9Kl4d8,4745 +pdbtools/pdb_reatom.py,sha256=0y9Dt70_3gwnLWmc1PJeWTU1lPF4IRxGGrVxo2JIUR4,6043 +pdbtools/pdb_reres.py,sha256=s0gAIIKz6zFTKxMn5OsgXrOsIfi7gFcLeFIpjRl3k-o,5770 +pdbtools/pdb_rplchain.py,sha256=0fE8wpb1X_aDX-RVhB9VbYcQSqDIqVLCWm_TcoUZB_s,5184 +pdbtools/pdb_rplresname.py,sha256=IR89pvG3kdAa1GrNYCaj1XU67AJRwL3Uy2zOkp5QEJ8,5106 +pdbtools/pdb_seg.py,sha256=SCKZzQKXJxF2W1yYo3-w9SsA3w1C0dFhYqRrN6G9a5U,4958 +pdbtools/pdb_segxchain.py,sha256=2ZakxyOsPxrY3KcwJ1bVKwtHGDWIbVOWSbxGjK2U_3Y,4407 +pdbtools/pdb_selaltloc.py,sha256=GLNgCXO7-TQ3yiclM9VGuzH7Cmv_4IA5rtkCN3ggdng,15351 +pdbtools/pdb_selatom.py,sha256=x60cAFLYU4JOgaQ-uRXvQtVt3W9vEWShMiGxbqkKXx8,5267 +pdbtools/pdb_selchain.py,sha256=EsEz4DNjNsWLPDSgpDdVpw2uEBLIuVowAfcRvrp4Y-k,5136 +pdbtools/pdb_selelem.py,sha256=jQ4zVfHincDyW1jbqJRR4H-gvkmgb9gqo3X3qlD5zMs,5298 +pdbtools/pdb_selhetatm.py,sha256=rTlNaD8lZQwfW0-51KdRsCBn0rnDNMXisAvq9t9EeRg,3711 +pdbtools/pdb_selmodel.py,sha256=s-HzuWrAlBP0qGJpboa5ccZECUQ1t95CqL2NH1D54PM,5538 +pdbtools/pdb_selres.py,sha256=2ru7kmerulQel2qNz3EhgevQ0v2dRe3m6NlDG08sP14,8753 +pdbtools/pdb_selresname.py,sha256=i2wo7EgXPHVy8rlbD-iB8ynw0umYFEop9YCUUQdCsSk,5281 +pdbtools/pdb_selseg.py,sha256=xFRfcVrqbWv_9HhLQbKvPOedhbmdU-s4GoVupAvxWzs,5089 +pdbtools/pdb_shiftres.py,sha256=LrZufworF1xF0u_uY0_QYjIfU7Uk7AftWJAwnN5BXL4,5079 +pdbtools/pdb_sort.py,sha256=szYyd5NhpVjfNSEO07LBuFtHHM3eZXRfZ-T7YNORs60,8280 +pdbtools/pdb_splitchain.py,sha256=TepAD4vlUD7kc3oqJQ49WOM7xr8hdvisP6BgZfkGbNc,3765 +pdbtools/pdb_splitmodel.py,sha256=EwE7xklqT0LTJIP6wezOjpp1cwcdoSeCkWkJFtRXN1s,3626 +pdbtools/pdb_splitseg.py,sha256=g5pQ9rye9q3cgY866ZwDaCNEAzevKOr_ePX84L0tdUw,3868 +pdbtools/pdb_tidy.py,sha256=fJWDyU5wdJvxwz3BTi88k75K1Zu2-qmsJW-EJ52xC2Q,8644 +pdbtools/pdb_tocif.py,sha256=8xS8eROua71uzxB8kR9WOKmnaJAdr11XKPVFwhLUZOY,6768 +pdbtools/pdb_tofasta.py,sha256=n9RxmiVcSo1sX-oWMly4-Xi4YwNviLCk0uuGQYt1gFE,6336 +pdbtools/pdb_uniqname.py,sha256=uucIbHShFdHl6nskcrALNf_jzHgFA8zCyx0dXtONRVM,3890 +pdbtools/pdb_validate.py,sha256=yTjlgexYoB52oLr3kFlSBqhPh-WeZWSAEuBPaORiCyY,6286 +pdbtools/pdb_wc.py,sha256=0aOGwNG66A4tUJANt-r1z_Pp3LoCOadHXGpmSoabNGU,8477 diff --git a/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0885d055554a9bce53952482316a33cebf0845e4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.10.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/entry_points.txt b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..88f14e64d57f2ba4f328e5a2c99fb1568089c63f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/entry_points.txt @@ -0,0 +1,50 @@ +[console_scripts] +__init__ = pdbtools.__init__:main +pdb_b = pdbtools.pdb_b:main +pdb_chain = pdbtools.pdb_chain:main +pdb_chainbows = pdbtools.pdb_chainbows:main +pdb_chainxseg = pdbtools.pdb_chainxseg:main +pdb_chkensemble = pdbtools.pdb_chkensemble:main +pdb_delchain = pdbtools.pdb_delchain:main +pdb_delelem = pdbtools.pdb_delelem:main +pdb_delhetatm = pdbtools.pdb_delhetatm:main +pdb_delinsertion = pdbtools.pdb_delinsertion:main +pdb_delres = pdbtools.pdb_delres:main +pdb_delresname = pdbtools.pdb_delresname:main +pdb_element = pdbtools.pdb_element:main +pdb_fetch = pdbtools.pdb_fetch:main +pdb_fixinsert = pdbtools.pdb_fixinsert:main +pdb_fromcif = pdbtools.pdb_fromcif:main +pdb_gap = pdbtools.pdb_gap:main +pdb_head = pdbtools.pdb_head:main +pdb_intersect = pdbtools.pdb_intersect:main +pdb_keepcoord = pdbtools.pdb_keepcoord:main +pdb_merge = pdbtools.pdb_merge:main +pdb_mkensemble = pdbtools.pdb_mkensemble:main +pdb_occ = pdbtools.pdb_occ:main +pdb_reatom = pdbtools.pdb_reatom:main +pdb_reres = pdbtools.pdb_reres:main +pdb_rplchain = pdbtools.pdb_rplchain:main +pdb_rplresname = pdbtools.pdb_rplresname:main +pdb_seg = pdbtools.pdb_seg:main +pdb_segxchain = pdbtools.pdb_segxchain:main +pdb_selaltloc = pdbtools.pdb_selaltloc:main +pdb_selatom = pdbtools.pdb_selatom:main +pdb_selchain = pdbtools.pdb_selchain:main +pdb_selelem = pdbtools.pdb_selelem:main +pdb_selhetatm = pdbtools.pdb_selhetatm:main +pdb_selmodel = pdbtools.pdb_selmodel:main +pdb_selres = pdbtools.pdb_selres:main +pdb_selresname = pdbtools.pdb_selresname:main +pdb_selseg = pdbtools.pdb_selseg:main +pdb_shiftres = pdbtools.pdb_shiftres:main +pdb_sort = pdbtools.pdb_sort:main +pdb_splitchain = pdbtools.pdb_splitchain:main +pdb_splitmodel = pdbtools.pdb_splitmodel:main +pdb_splitseg = pdbtools.pdb_splitseg:main +pdb_tidy = pdbtools.pdb_tidy:main +pdb_tocif = pdbtools.pdb_tocif:main +pdb_tofasta = pdbtools.pdb_tofasta:main +pdb_uniqname = pdbtools.pdb_uniqname:main +pdb_validate = pdbtools.pdb_validate:main +pdb_wc = pdbtools.pdb_wc:main diff --git a/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/top_level.txt b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..2409dc9b246d2364b50bd6681041488efdf77828 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pdb_tools-2.6.1.dist-info/top_level.txt @@ -0,0 +1 @@ +pdbtools diff --git a/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e56d5d1f85d656265cf5760c69f3896b3fc96984 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/METADATA @@ -0,0 +1,111 @@ +Metadata-Version: 2.4 +Name: pip +Version: 26.0.1 +Summary: The PyPA recommended tool for installing Python packages. +Author-email: The pip developers +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-Expression: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Topic :: Software Development :: Build Tools +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +License-File: AUTHORS.txt +License-File: LICENSE.txt +License-File: src/pip/_vendor/cachecontrol/LICENSE.txt +License-File: src/pip/_vendor/certifi/LICENSE +License-File: src/pip/_vendor/dependency_groups/LICENSE.txt +License-File: src/pip/_vendor/distlib/LICENSE.txt +License-File: src/pip/_vendor/distro/LICENSE +License-File: src/pip/_vendor/idna/LICENSE.md +License-File: src/pip/_vendor/msgpack/COPYING +License-File: src/pip/_vendor/packaging/LICENSE +License-File: src/pip/_vendor/packaging/LICENSE.APACHE +License-File: src/pip/_vendor/packaging/LICENSE.BSD +License-File: src/pip/_vendor/pkg_resources/LICENSE +License-File: src/pip/_vendor/platformdirs/LICENSE +License-File: src/pip/_vendor/pygments/LICENSE +License-File: src/pip/_vendor/pyproject_hooks/LICENSE +License-File: src/pip/_vendor/requests/LICENSE +License-File: src/pip/_vendor/resolvelib/LICENSE +License-File: src/pip/_vendor/rich/LICENSE +License-File: src/pip/_vendor/tomli/LICENSE +License-File: src/pip/_vendor/tomli_w/LICENSE +License-File: src/pip/_vendor/truststore/LICENSE +License-File: src/pip/_vendor/urllib3/LICENSE.txt +Project-URL: Changelog, https://pip.pypa.io/en/stable/news/ +Project-URL: Documentation, https://pip.pypa.io +Project-URL: Homepage, https://pip.pypa.io/ +Project-URL: Source, https://github.com/pypa/pip + +pip - The Python Package Installer +================================== + +.. |pypi-version| image:: https://img.shields.io/pypi/v/pip.svg + :target: https://pypi.org/project/pip/ + :alt: PyPI + +.. |python-versions| image:: https://img.shields.io/pypi/pyversions/pip + :target: https://pypi.org/project/pip + :alt: PyPI - Python Version + +.. |docs-badge| image:: https://readthedocs.org/projects/pip/badge/?version=latest + :target: https://pip.pypa.io/en/latest + :alt: Documentation + +|pypi-version| |python-versions| |docs-badge| + +pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes. + +Please take a look at our documentation for how to install and use pip: + +* `Installation`_ +* `Usage`_ + +We release updates regularly, with a new version every 3 months. Find more details in our documentation: + +* `Release notes`_ +* `Release process`_ + +If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms: + +* `Issue tracking`_ +* `Discourse channel`_ +* `User IRC`_ + +If you want to get involved, head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms: + +* `GitHub page`_ +* `Development documentation`_ +* `Development IRC`_ + +Code of Conduct +--------------- + +Everyone interacting in the pip project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _package installer: https://packaging.python.org/guides/tool-recommendations/ +.. _Python Package Index: https://pypi.org +.. _Installation: https://pip.pypa.io/en/stable/installation/ +.. _Usage: https://pip.pypa.io/en/stable/ +.. _Release notes: https://pip.pypa.io/en/stable/news.html +.. _Release process: https://pip.pypa.io/en/latest/development/release-process/ +.. _GitHub page: https://github.com/pypa/pip +.. _Development documentation: https://pip.pypa.io/en/latest/development +.. _Issue tracking: https://github.com/pypa/pip/issues +.. _Discourse channel: https://discuss.python.org/c/packaging +.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa +.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + diff --git a/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1d9f3003e9e5de794b293984e063411d1ff79b2e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/RECORD @@ -0,0 +1,878 @@ +../../../bin/pip,sha256=xTG89juck_AfqBFWHdk_qWj3ODKDKls7951hZbjQMZ8,269 +../../../bin/pip3,sha256=xTG89juck_AfqBFWHdk_qWj3ODKDKls7951hZbjQMZ8,269 +../../../bin/pip3.12,sha256=xTG89juck_AfqBFWHdk_qWj3ODKDKls7951hZbjQMZ8,269 +pip-26.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pip-26.0.1.dist-info/METADATA,sha256=ZqIZuNGsG6l2gHiKlQjVQghFQhgSWfhEDHuCVPW3aN8,4675 +pip-26.0.1.dist-info/RECORD,, +pip-26.0.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip-26.0.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +pip-26.0.1.dist-info/entry_points.txt,sha256=Vhf8s0IYgX37mtd4vGL73BPcxdKnqeCFPzB5-d30x8o,84 +pip-26.0.1.dist-info/licenses/AUTHORS.txt,sha256=grSl9YDNOpOFFJTX8ZYKSdgfouXi_DzlRyYGE2-u5aI,11731 +pip-26.0.1.dist-info/licenses/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/dependency_groups/LICENSE.txt,sha256=GrNuPipLqGMWJThPh-ngkdsfrtA0xbIzJbMjmr8sxSU,1099 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/idna/LICENSE.md,sha256=t6M2q_OwThgOwGXN0W5wXQeeHMehT5EKpukYfza5zYc,1541 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086 +pip-26.0.1.dist-info/licenses/src/pip/_vendor/urllib3/LICENSE.txt,sha256=w3vxhuJ8-dvpYZ5V7f486nswCRzrPaY8fay-Dm13kHs,1115 +pip/__init__.py,sha256=3EhKF2588Ab15tmBszgD3Bp0N26sJx7VhS2Akn_qY38,355 +pip/__main__.py,sha256=WzbhHXTbSE6gBY19mNN9m4s5o_365LOvTYSgqgbdBhE,854 +pip/__pip-runner__.py,sha256=JOoEZTwrtv7jRaXBkgSQKAE04yNyfFmGHxqpHiGHvL0,1450 +pip/__pycache__/__init__.cpython-312.pyc,, +pip/__pycache__/__main__.cpython-312.pyc,, +pip/__pycache__/__pip-runner__.cpython-312.pyc,, +pip/_internal/__init__.py,sha256=S7i9Dn9aSZS0MG-2Wrve3dV9TImPzvQn5jjhp9t_uf0,511 +pip/_internal/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/__pycache__/build_env.cpython-312.pyc,, +pip/_internal/__pycache__/cache.cpython-312.pyc,, +pip/_internal/__pycache__/configuration.cpython-312.pyc,, +pip/_internal/__pycache__/exceptions.cpython-312.pyc,, +pip/_internal/__pycache__/main.cpython-312.pyc,, +pip/_internal/__pycache__/pyproject.cpython-312.pyc,, +pip/_internal/__pycache__/self_outdated_check.cpython-312.pyc,, +pip/_internal/__pycache__/wheel_builder.cpython-312.pyc,, +pip/_internal/build_env.py,sha256=XpgOIlTQLgz3PvDT2n7j2NzX_rVFZLCIG7t7b2ddhcM,21911 +pip/_internal/cache.py,sha256=nMh48Yv3yu1HS1yCdscouu6B6B5zYBWdV6bhqs7gL-E,10345 +pip/_internal/cli/__init__.py,sha256=Iqg_tKA771XuMO1P4t_sDHnSKPzkUb9D0DqunAmw_ko,131 +pip/_internal/cli/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/cli/__pycache__/autocompletion.cpython-312.pyc,, +pip/_internal/cli/__pycache__/base_command.cpython-312.pyc,, +pip/_internal/cli/__pycache__/cmdoptions.cpython-312.pyc,, +pip/_internal/cli/__pycache__/command_context.cpython-312.pyc,, +pip/_internal/cli/__pycache__/index_command.cpython-312.pyc,, +pip/_internal/cli/__pycache__/main.cpython-312.pyc,, +pip/_internal/cli/__pycache__/main_parser.cpython-312.pyc,, +pip/_internal/cli/__pycache__/parser.cpython-312.pyc,, +pip/_internal/cli/__pycache__/progress_bars.cpython-312.pyc,, +pip/_internal/cli/__pycache__/req_command.cpython-312.pyc,, +pip/_internal/cli/__pycache__/spinners.cpython-312.pyc,, +pip/_internal/cli/__pycache__/status_codes.cpython-312.pyc,, +pip/_internal/cli/autocompletion.py,sha256=ZG2cM03nlcNrs-WG_SFTW46isx9s2Go5lUD_8-iv70o,7193 +pip/_internal/cli/base_command.py,sha256=6OW75PSGzkH8Fz761WZ3OSz1TsuO3-suc6iap-sQjTM,9168 +pip/_internal/cli/cmdoptions.py,sha256=hfA9B29Nnq2vYMWhFVg7EcWjdlfdPBPU4WwWT2Lkq4A,36164 +pip/_internal/cli/command_context.py,sha256=kmu3EWZbfBega1oDamnGJTA_UaejhIQNuMj2CVmMXu0,817 +pip/_internal/cli/index_command.py,sha256=s3x75lpDXWJtCkBacTQ3qAAprldHMJCniEQ5qkQ0FiI,6484 +pip/_internal/cli/main.py,sha256=ljDQBkvBtC8xTjOdb6rDJzJUNi1s-PnVR_W5C-Mq0Dk,3137 +pip/_internal/cli/main_parser.py,sha256=YjzJAjqf78ARNsLlnJT9l6fNbpyDPJA-arOIXYsK5Ik,4403 +pip/_internal/cli/parser.py,sha256=EIFExrWX_1nrl1Ib--GOor70WYqLtduHByenb1u9xH4,13827 +pip/_internal/cli/progress_bars.py,sha256=IW1PH5n2FPqUBTP7ULQ5Yu-wyNNO9XGY3g1PT4RMu44,4706 +pip/_internal/cli/req_command.py,sha256=QjDXId0hFdopwE8hNx2eustumxUNbnOCvG_ORmUC7vM,16482 +pip/_internal/cli/spinners.py,sha256=EJzZIZNyUtJljp3-WjcsyIrqxW-HUsfWzhuW84n_Tqw,7362 +pip/_internal/cli/status_codes.py,sha256=sEFHUaUJbqv8iArL3HAtcztWZmGOFX01hTesSytDEh0,116 +pip/_internal/commands/__init__.py,sha256=aNeCbQurGWihfhQq7BqaLXHqWDQ0i3I04OS7kxK6plQ,4026 +pip/_internal/commands/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/commands/__pycache__/cache.cpython-312.pyc,, +pip/_internal/commands/__pycache__/check.cpython-312.pyc,, +pip/_internal/commands/__pycache__/completion.cpython-312.pyc,, +pip/_internal/commands/__pycache__/configuration.cpython-312.pyc,, +pip/_internal/commands/__pycache__/debug.cpython-312.pyc,, +pip/_internal/commands/__pycache__/download.cpython-312.pyc,, +pip/_internal/commands/__pycache__/freeze.cpython-312.pyc,, +pip/_internal/commands/__pycache__/hash.cpython-312.pyc,, +pip/_internal/commands/__pycache__/help.cpython-312.pyc,, +pip/_internal/commands/__pycache__/index.cpython-312.pyc,, +pip/_internal/commands/__pycache__/inspect.cpython-312.pyc,, +pip/_internal/commands/__pycache__/install.cpython-312.pyc,, +pip/_internal/commands/__pycache__/list.cpython-312.pyc,, +pip/_internal/commands/__pycache__/lock.cpython-312.pyc,, +pip/_internal/commands/__pycache__/search.cpython-312.pyc,, +pip/_internal/commands/__pycache__/show.cpython-312.pyc,, +pip/_internal/commands/__pycache__/uninstall.cpython-312.pyc,, +pip/_internal/commands/__pycache__/wheel.cpython-312.pyc,, +pip/_internal/commands/cache.py,sha256=XjT7kjY8GSISMksFHsLvjS9Ogfi5extNlUUv-dUoWCM,9142 +pip/_internal/commands/check.py,sha256=hVFBQezQ3zj4EydoWbFQj_afPUppMt7r9JPAlY22U6Y,2244 +pip/_internal/commands/completion.py,sha256=LjvRIZ6QUiDXJL3IOMFeD-_J97HfjMGgEk0j2tWGu1U,4565 +pip/_internal/commands/configuration.py,sha256=6gNOGrVWnOLU15zUnAiNuOMhf76RRIZvCdVD0degPRk,10105 +pip/_internal/commands/debug.py,sha256=_8IqM8Fx1_lY2STu_qspr63tufF7zyFJCyYAXtxz0N4,6805 +pip/_internal/commands/download.py,sha256=LUNVobuvCdagjLBuPBaxHeBiHEiIe03fTO2m6ahC8qw,5178 +pip/_internal/commands/freeze.py,sha256=fxoW8AAc-bAqB_fXdNq2VnZ3JfWkFMg-bR6LcdDVO7A,3099 +pip/_internal/commands/hash.py,sha256=GO9pRN3wXC2kQaovK57TaLYBMc3IltOH92O6QEw6YE0,1679 +pip/_internal/commands/help.py,sha256=Bz3LcjNQXkz4Cu__pL4CZ86o4-HNLZj1NZWdlJhjuu0,1108 +pip/_internal/commands/index.py,sha256=kDpx2MO6ZxTt5PpeY4jqcssVbYhzxpkpreDe_6PPhks,5520 +pip/_internal/commands/inspect.py,sha256=ogm4UT7LRo8bIQcWUS1IiA25QdD4VHLa7JaPAodDttM,3177 +pip/_internal/commands/install.py,sha256=L6X1qi49ROVTGABhwwxDgBBTijlOpVn6XSDVZ7QW1Kc,30588 +pip/_internal/commands/list.py,sha256=L5nWuwawqSrBNsuxfyHLAagfz7XJP86tC9nK3L9YiI8,13497 +pip/_internal/commands/lock.py,sha256=145ihjUK_-7gP8O65XPDi_xMhlh5hne1ptkHdfnbAnQ,6027 +pip/_internal/commands/search.py,sha256=zbMsX_YASj6kXA6XIBgTDv0bGK51xG-CV3IynZJcE-c,5782 +pip/_internal/commands/show.py,sha256=oLVJIfKWmDKm0SsQGEi3pozNiqrXjTras_fbBSYKpBA,8066 +pip/_internal/commands/uninstall.py,sha256=CsOihqvb6ZA6O67L70oXeoLHeOfNzMM88H9g-9aocgw,3868 +pip/_internal/commands/wheel.py,sha256=L9vEzJ_E42scF_Hgh5X4Hk39nqJDKxGg4u7glDYbNWc,5880 +pip/_internal/configuration.py,sha256=WxwwSwY_Bm6QzDgf32BsujEyO8dgRedegCpgbUfDvM8,14568 +pip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858 +pip/_internal/distributions/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/distributions/__pycache__/base.cpython-312.pyc,, +pip/_internal/distributions/__pycache__/installed.cpython-312.pyc,, +pip/_internal/distributions/__pycache__/sdist.cpython-312.pyc,, +pip/_internal/distributions/__pycache__/wheel.cpython-312.pyc,, +pip/_internal/distributions/base.py,sha256=l-OTCAIs25lsapejA6IYpPZxSM5-BET4sdZDkql8jiY,1830 +pip/_internal/distributions/installed.py,sha256=kgIEE_1NzjZxLBSC-v5s64uOFZlVEt3aPrjTtL6x2XY,929 +pip/_internal/distributions/sdist.py,sha256=RYwQIbuxpKy6OjlBZCAefxpMDaoocUQ4dFtheGsiTOQ,6627 +pip/_internal/distributions/wheel.py,sha256=_HbG0OehF8dwj4UX-xV__tXLwgPus9OjMEf2NTRqBbE,1364 +pip/_internal/exceptions.py,sha256=JdPCrQ9iTLvE-GBebzBEeGP3hoTffWEKqbYEsa6cEZc,32165 +pip/_internal/index/__init__.py,sha256=tzwMH_fhQeubwMqHdSivasg1cRgTSbNg2CiMVnzMmyU,29 +pip/_internal/index/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/index/__pycache__/collector.cpython-312.pyc,, +pip/_internal/index/__pycache__/package_finder.cpython-312.pyc,, +pip/_internal/index/__pycache__/sources.cpython-312.pyc,, +pip/_internal/index/collector.py,sha256=R7Gcx_4GEoSEI-iazfAZVEPG3Lp6mbZT4lbAD6NjAc0,16144 +pip/_internal/index/package_finder.py,sha256=a3_L4FDNsuDf3y8Af9J7sfsHR1ahs8o13Ths-WYwFh0,41776 +pip/_internal/index/sources.py,sha256=nXJkOjhLy-O2FsrKU9RIqCOqgY2PsoKWybtZjjRgqU0,8639 +pip/_internal/locations/__init__.py,sha256=Sd67ap1LIemvXArUDFqm8U-HuZvj9i3ApEuiIwUc9UE,14157 +pip/_internal/locations/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/locations/__pycache__/_distutils.cpython-312.pyc,, +pip/_internal/locations/__pycache__/_sysconfig.cpython-312.pyc,, +pip/_internal/locations/__pycache__/base.cpython-312.pyc,, +pip/_internal/locations/_distutils.py,sha256=jpFj4V00rD9IR3vA9TqrGkwcdNVFc58LsChZavge9JY,5975 +pip/_internal/locations/_sysconfig.py,sha256=8CpTjtxaCzHSCrKpaxWnHE7aKcJrRJRmntR1ZLVysLk,7779 +pip/_internal/locations/base.py,sha256=AImjYJWxOtDkc0KKc6Y4Gz677cg91caMA4L94B9FZEg,2550 +pip/_internal/main.py,sha256=1cHqjsfFCrMFf3B5twzocxTJUdHMLoXUpy5lJoFqUi8,338 +pip/_internal/metadata/__init__.py,sha256=vp-JAxiWg_-l5F8AT0Jcey72uUnh8CDwwol9-KktHZ8,5824 +pip/_internal/metadata/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/metadata/__pycache__/_json.cpython-312.pyc,, +pip/_internal/metadata/__pycache__/base.cpython-312.pyc,, +pip/_internal/metadata/__pycache__/pkg_resources.cpython-312.pyc,, +pip/_internal/metadata/_json.py,sha256=hNvnMHOXLAyNlzirWhPL9Nx2CvCqa1iRma6Osq1YfV8,2711 +pip/_internal/metadata/base.py,sha256=BGuMenlcQT8i7j9iclrfdC3vSwgvhr8gjn955cCy16s,25420 +pip/_internal/metadata/importlib/__init__.py,sha256=jUUidoxnHcfITHHaAWG1G2i5fdBYklv_uJcjo2x7VYE,135 +pip/_internal/metadata/importlib/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/metadata/importlib/__pycache__/_compat.cpython-312.pyc,, +pip/_internal/metadata/importlib/__pycache__/_dists.cpython-312.pyc,, +pip/_internal/metadata/importlib/__pycache__/_envs.cpython-312.pyc,, +pip/_internal/metadata/importlib/_compat.py,sha256=sneVh4_6WxQZK4ljdl3ylVuP-q0ttSqbgl9mWt0HnOg,2804 +pip/_internal/metadata/importlib/_dists.py,sha256=znZD7MN4RC73-87KXAn6tKZv9lAQRI0AxxK2bubDvPw,8420 +pip/_internal/metadata/importlib/_envs.py,sha256=H3qVLXVh4LWvrPvu_ekXf3dfbtwnlhNJQP2pxXpccfU,5333 +pip/_internal/metadata/pkg_resources.py,sha256=NO76ZrfR2-LKJTyaXrmQoGhmJMArALvacrlZHViSDT8,10544 +pip/_internal/models/__init__.py,sha256=AjmCEBxX_MH9f_jVjIGNCFJKYCYeSEe18yyvNx4uRKQ,62 +pip/_internal/models/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/models/__pycache__/candidate.cpython-312.pyc,, +pip/_internal/models/__pycache__/direct_url.cpython-312.pyc,, +pip/_internal/models/__pycache__/format_control.cpython-312.pyc,, +pip/_internal/models/__pycache__/index.cpython-312.pyc,, +pip/_internal/models/__pycache__/installation_report.cpython-312.pyc,, +pip/_internal/models/__pycache__/link.cpython-312.pyc,, +pip/_internal/models/__pycache__/release_control.cpython-312.pyc,, +pip/_internal/models/__pycache__/scheme.cpython-312.pyc,, +pip/_internal/models/__pycache__/search_scope.cpython-312.pyc,, +pip/_internal/models/__pycache__/selection_prefs.cpython-312.pyc,, +pip/_internal/models/__pycache__/target_python.cpython-312.pyc,, +pip/_internal/models/__pycache__/wheel.cpython-312.pyc,, +pip/_internal/models/candidate.py,sha256=zzgFRuw_kWPjKpGw7LC0ZUMD2CQ2EberUIYs8izjdCA,753 +pip/_internal/models/direct_url.py,sha256=4NMWacu_QzPPWREC1te7v6Wfv-2HkI4tvSJF-CBgLh4,6555 +pip/_internal/models/format_control.py,sha256=PwemYG1L27BM0f1KP61rm24wShENFyxqlD1TWu34alc,2471 +pip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030 +pip/_internal/models/installation_report.py,sha256=cqfWJ93ThCxjcacqSWryOCD2XtIn1CZrgzZxAv5FQZ0,2839 +pip/_internal/models/link.py,sha256=zti5UCx1hT03etYqm6MCqFd714clmTgX8rTZT9CKZDQ,21992 +pip/_internal/models/release_control.py,sha256=XD14Hy_XLh9xWR1p7JHqPZPEv3Nnb1BZGMpClk76sLs,3403 +pip/_internal/models/scheme.py,sha256=PakmHJM3e8OOWSZFtfz1Az7f1meONJnkGuQxFlt3wBE,575 +pip/_internal/models/search_scope.py,sha256=1hxU2IVsAaLZVjp0CbzJbYaYzCxv72_Qbg3JL0qhXo0,4507 +pip/_internal/models/selection_prefs.py,sha256=IDOA3euRtyqWUyIK7lX2bzIZasYiEvunKA6H3Mngk-M,2221 +pip/_internal/models/target_python.py,sha256=I0eFS-eia3kwhrOvgsphFZtNAB2IwXZ9Sr9fp6IjBP4,4243 +pip/_internal/models/wheel.py,sha256=1SdfDvN7ALTsbyZ9EOsNy1GPirP1n6EjHyzPrZyLSh8,2920 +pip/_internal/network/__init__.py,sha256=FMy06P__y6jMjUc8z3ZcQdKF-pmZ2zM14_vBeHPGhUI,49 +pip/_internal/network/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/network/__pycache__/auth.cpython-312.pyc,, +pip/_internal/network/__pycache__/cache.cpython-312.pyc,, +pip/_internal/network/__pycache__/download.cpython-312.pyc,, +pip/_internal/network/__pycache__/lazy_wheel.cpython-312.pyc,, +pip/_internal/network/__pycache__/session.cpython-312.pyc,, +pip/_internal/network/__pycache__/utils.cpython-312.pyc,, +pip/_internal/network/__pycache__/xmlrpc.cpython-312.pyc,, +pip/_internal/network/auth.py,sha256=azFp14I9cyWAAzkxF2VM0Q_xtHnbNz3_NQXszy87KQo,20806 +pip/_internal/network/cache.py,sha256=kmRXKQrG9E26xQRj211LHeEGpDg_SlYU9Dn1fJ-AMeI,4862 +pip/_internal/network/download.py,sha256=8sVwIc9MWwpGlMPYCkO1S9U-FD8TA2utw42tj00skjM,12667 +pip/_internal/network/lazy_wheel.py,sha256=y9gVksdJCSjnLfYzs_m3DYUAtl3hc_k-xFPDBd9DgOs,7646 +pip/_internal/network/session.py,sha256=7zK7EeQCSRFipu4ZzcWl1V3AMKkiXdtGqFr7GvU2LrY,19555 +pip/_internal/network/utils.py,sha256=ACsXd1msqNCidHVXsu7LHUSr8NgaypcOKQ4KG-Z_wJM,4091 +pip/_internal/network/xmlrpc.py,sha256=_-Rnk3vOff8uF9hAGmT6SLALflY1gMBcbGwS12fb_Y4,1830 +pip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/operations/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/operations/__pycache__/check.cpython-312.pyc,, +pip/_internal/operations/__pycache__/freeze.cpython-312.pyc,, +pip/_internal/operations/__pycache__/prepare.cpython-312.pyc,, +pip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/operations/build/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/operations/build/__pycache__/build_tracker.cpython-312.pyc,, +pip/_internal/operations/build/__pycache__/metadata.cpython-312.pyc,, +pip/_internal/operations/build/__pycache__/metadata_editable.cpython-312.pyc,, +pip/_internal/operations/build/__pycache__/wheel.cpython-312.pyc,, +pip/_internal/operations/build/__pycache__/wheel_editable.cpython-312.pyc,, +pip/_internal/operations/build/build_tracker.py,sha256=W3b5cmkMWPaE6QIwfzsTayJo7-OlxFHWDxfPuax1KcE,4771 +pip/_internal/operations/build/metadata.py,sha256=INHaeiRfOiLYCXApfDNRo9Cw2xI4VwTc0KItvfdfOjk,1421 +pip/_internal/operations/build/metadata_editable.py,sha256=oWudMsnjy4loO_Jy7g4N9nxsnaEX_iDlVRgCy7pu1rs,1509 +pip/_internal/operations/build/wheel.py,sha256=3bP-nNiJ4S8JvMaBnyessXQUBhxTqt1GBx6DQ1iPJDY,1136 +pip/_internal/operations/build/wheel_editable.py,sha256=q3kfElclM6FutVbFwE87JOTpVWt5ixDf3_UkHAIVfz4,1478 +pip/_internal/operations/check.py,sha256=yC2XWth6iehGGE_fj7XRJLjVKBsTIG3ZoWRkFi3rOwc,5894 +pip/_internal/operations/freeze.py,sha256=PDdY-y_ZtZZJLAKcaWPIGRKAGW7DXR48f0aMRU0j7BA,9854 +pip/_internal/operations/install/__init__.py,sha256=ak-UETcQPKlFZaWoYKWu5QVXbpFBvg0sXc3i0O4vSYY,50 +pip/_internal/operations/install/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/operations/install/__pycache__/wheel.cpython-312.pyc,, +pip/_internal/operations/install/wheel.py,sha256=FQIl2AnNadHV5YGGOVEmOHtUUNO8lpzj3Icoo4S2xis,27923 +pip/_internal/operations/prepare.py,sha256=ptVsmQf0Mo6jirk1Q5Djdse_wJw5Zdh1Fla2iL9HAJM,28830 +pip/_internal/pyproject.py,sha256=J-sTWqC-XfsKQgz9m1bypMWZPHItsSHzIN_NWeIRmhM,4555 +pip/_internal/req/__init__.py,sha256=WcY9z7D3rlIKX1QY8_tRnAsS_poebiGGdtQ7EJ5JQQo,3041 +pip/_internal/req/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/req/__pycache__/constructors.cpython-312.pyc,, +pip/_internal/req/__pycache__/pep723.cpython-312.pyc,, +pip/_internal/req/__pycache__/req_dependency_group.cpython-312.pyc,, +pip/_internal/req/__pycache__/req_file.cpython-312.pyc,, +pip/_internal/req/__pycache__/req_install.cpython-312.pyc,, +pip/_internal/req/__pycache__/req_set.cpython-312.pyc,, +pip/_internal/req/__pycache__/req_uninstall.cpython-312.pyc,, +pip/_internal/req/constructors.py,sha256=R-6n8irjnaa2DMMXlR4YMouXzykFBlzUFjhOZ1NcUUg,18688 +pip/_internal/req/pep723.py,sha256=olZL3tLmHWJhyLNfbD6U9UuikuzTcLDB06qd9WavTjs,1225 +pip/_internal/req/req_dependency_group.py,sha256=0yEQCUaO5Bza66Y3D5o9JRf0qII5QgCRugn1x5aRivA,2618 +pip/_internal/req/req_file.py,sha256=e32ZQ3kJaL_Sdtf32twGKqIau_AqR43MeSycl0iS2Mw,20685 +pip/_internal/req/req_install.py,sha256=vv5cbs3P5gf43e_1v72gwSQ2N_D_qpsfuXOyerMhDuI,31273 +pip/_internal/req/req_set.py,sha256=awkqIXnYA4Prmsj0Qb3zhqdbYUmXd-1o0P-KZ3mvRQs,2828 +pip/_internal/req/req_uninstall.py,sha256=dCmOHt-9RaJBq921L4tMH3PmIBDetGplnbjRKXmGt00,24099 +pip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/resolution/__pycache__/base.cpython-312.pyc,, +pip/_internal/resolution/base.py,sha256=RIsqSP79olPdOgtPKW-oOQ364ICVopehA6RfGkRfe2s,577 +pip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/legacy/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/resolution/legacy/__pycache__/resolver.cpython-312.pyc,, +pip/_internal/resolution/legacy/resolver.py,sha256=bwUqE66etz2bcPabqxed18-iyqqb-kx3Er2aT6GeUJY,24060 +pip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/base.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/factory.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/provider.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-312.pyc,, +pip/_internal/resolution/resolvelib/base.py,sha256=_AoP0ZWlaSct8CRDn2ol3CbNn4zDtnh_0zQGjXASDKI,5047 +pip/_internal/resolution/resolvelib/candidates.py,sha256=50AN7BfB-pCfEmbKNlFZSXtdC0C8ms1waJrF2arknQE,20454 +pip/_internal/resolution/resolvelib/factory.py,sha256=82mLwnPlig37mMrDwcgKHJTE9mPczVuJIxeaUb7CQ0Y,34028 +pip/_internal/resolution/resolvelib/found_candidates.py,sha256=8bZYDCZLXSdLHy_s1o5f4r15HmKvqFUhzBUQOF21Lr4,6018 +pip/_internal/resolution/resolvelib/provider.py,sha256=tbVPfFv4Vg780yZ2_XGoGFP5LVo0U2bFnZov3jpSAIk,11441 +pip/_internal/resolution/resolvelib/reporter.py,sha256=faSgjqme0k_uzv1fvM5T0ZatPQ2eEktNvKBqfvXeGjc,3909 +pip/_internal/resolution/resolvelib/requirements.py,sha256=Izl9n8nc188lA1BSPS8QxfudfDQPHgngw-ij6hXt0nQ,8239 +pip/_internal/resolution/resolvelib/resolver.py,sha256=wQ94Hkep-7kWEHAc-NbMJhmzeEzgEAtxeBxyKVzZoeo,13437 +pip/_internal/self_outdated_check.py,sha256=zDKsyLMufFHuEZY16WRu129FBbBp-ADuxyWMIN4ihPE,8284 +pip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_internal/utils/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/utils/__pycache__/_jaraco_text.cpython-312.pyc,, +pip/_internal/utils/__pycache__/_log.cpython-312.pyc,, +pip/_internal/utils/__pycache__/appdirs.cpython-312.pyc,, +pip/_internal/utils/__pycache__/compat.cpython-312.pyc,, +pip/_internal/utils/__pycache__/compatibility_tags.cpython-312.pyc,, +pip/_internal/utils/__pycache__/datetime.cpython-312.pyc,, +pip/_internal/utils/__pycache__/deprecation.cpython-312.pyc,, +pip/_internal/utils/__pycache__/direct_url_helpers.cpython-312.pyc,, +pip/_internal/utils/__pycache__/egg_link.cpython-312.pyc,, +pip/_internal/utils/__pycache__/entrypoints.cpython-312.pyc,, +pip/_internal/utils/__pycache__/filesystem.cpython-312.pyc,, +pip/_internal/utils/__pycache__/filetypes.cpython-312.pyc,, +pip/_internal/utils/__pycache__/glibc.cpython-312.pyc,, +pip/_internal/utils/__pycache__/hashes.cpython-312.pyc,, +pip/_internal/utils/__pycache__/logging.cpython-312.pyc,, +pip/_internal/utils/__pycache__/misc.cpython-312.pyc,, +pip/_internal/utils/__pycache__/packaging.cpython-312.pyc,, +pip/_internal/utils/__pycache__/pylock.cpython-312.pyc,, +pip/_internal/utils/__pycache__/retry.cpython-312.pyc,, +pip/_internal/utils/__pycache__/subprocess.cpython-312.pyc,, +pip/_internal/utils/__pycache__/temp_dir.cpython-312.pyc,, +pip/_internal/utils/__pycache__/unpacking.cpython-312.pyc,, +pip/_internal/utils/__pycache__/urls.cpython-312.pyc,, +pip/_internal/utils/__pycache__/virtualenv.cpython-312.pyc,, +pip/_internal/utils/__pycache__/wheel.cpython-312.pyc,, +pip/_internal/utils/_jaraco_text.py,sha256=M15uUPIh5NpP1tdUGBxRau6q1ZAEtI8-XyLEETscFfE,3350 +pip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015 +pip/_internal/utils/appdirs.py,sha256=LrzDPZMKVh0rubtCx9vu3XlZbLCSug6VSj4Qsvt66BA,1681 +pip/_internal/utils/compat.py,sha256=C9LHXJAKkwAH8Hn3nPkz9EYK3rqPBeO_IXkOG2zzsdQ,2514 +pip/_internal/utils/compatibility_tags.py,sha256=DiNSLqpuruXUamGQwOJ2WZByDGLTGaXi9O-Xf8fOi34,6630 +pip/_internal/utils/datetime.py,sha256=kuJOf1mW8G5tRFN6jWardddS-9qSaR53lK1jmx3NTZY,868 +pip/_internal/utils/deprecation.py,sha256=HVhvyO5qiRFcG88PhZlp_87qdKQNwPTUIIHWtsTR2yI,3696 +pip/_internal/utils/direct_url_helpers.py,sha256=ttKv4GMUqlRwPPog9_CUopy6SDgoxVILzeBJzgfn2tg,3200 +pip/_internal/utils/egg_link.py,sha256=YWfsrbmfcrfWgqQYy6OuIjsyb9IfL1q_2v4zsms1WjI,2459 +pip/_internal/utils/entrypoints.py,sha256=uPjAyShKObdotjQjJUzprQ6r3xQvDIZwUYfHHqZ7Dok,3324 +pip/_internal/utils/filesystem.py,sha256=mJ_PP8z1V1x4HMhydWIWDyEmWikLX0f-NXPCXEcjiLo,6892 +pip/_internal/utils/filetypes.py,sha256=sEMa38qaqjvx1Zid3OCAUja31BOBU-USuSMPBvU3yjo,689 +pip/_internal/utils/glibc.py,sha256=sEh8RJJLYSdRvTqAO4THVPPA-YSDVLD4SI9So-bxX1U,3726 +pip/_internal/utils/hashes.py,sha256=d32UI1en8nyqZzdZQvxUVdfeBoe4ADWx7HtrIM4-XQ4,4998 +pip/_internal/utils/logging.py,sha256=6lJWMC6c7_aD_i4sdgaaeb-Tm3kWpYg0hba_V1-OLnE,13414 +pip/_internal/utils/misc.py,sha256=phFIbHm2kmliHDXJ0eNPxgGP423ZpvZoMKKtJ1_Zvjs,23722 +pip/_internal/utils/packaging.py,sha256=s5tpUmFumwV0H9JSTzryrIY4JwQM8paGt7Sm7eNwt2Y,1601 +pip/_internal/utils/pylock.py,sha256=nKQknZgyswWgzi--hRQX_DLUYQ3g5wGTCwVNQNdoJ54,3817 +pip/_internal/utils/retry.py,sha256=83wReEB2rcntMZ5VLd7ascaYSjn_kLdlQCqxILxWkPM,1461 +pip/_internal/utils/subprocess.py,sha256=r4-Ba_Yc3uZXQpi0K4pZFsCT_QqdSvtF3XJ-204QWaA,8983 +pip/_internal/utils/temp_dir.py,sha256=D9c8D7WOProOO8GGDqpBeVSj10NGFmunG0o2TodjjIU,9307 +pip/_internal/utils/unpacking.py,sha256=4hNg6dqHOn_KzGCzSC76nChG97d_UjtF9AnLSof672o,12972 +pip/_internal/utils/urls.py,sha256=aF_eg9ul5d8bMCxfSSSxQcfs-OpJdbStYqZHoy2K1RE,1601 +pip/_internal/utils/virtualenv.py,sha256=mX-UPyw1MPxhwUxKhbqWWX70J6PHXAJjVVrRnG0h9mc,3455 +pip/_internal/utils/wheel.py,sha256=YdRuj6MicG-Q9Mg03FbUv1WTLam6Lc7AgijY4voVyis,4468 +pip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596 +pip/_internal/vcs/__pycache__/__init__.cpython-312.pyc,, +pip/_internal/vcs/__pycache__/bazaar.cpython-312.pyc,, +pip/_internal/vcs/__pycache__/git.cpython-312.pyc,, +pip/_internal/vcs/__pycache__/mercurial.cpython-312.pyc,, +pip/_internal/vcs/__pycache__/subversion.cpython-312.pyc,, +pip/_internal/vcs/__pycache__/versioncontrol.cpython-312.pyc,, +pip/_internal/vcs/bazaar.py,sha256=3W1eHjkYx2vc6boeb2NBh4I_rlGAXM-vrzfNhLm1Rxg,3734 +pip/_internal/vcs/git.py,sha256=TTeqDuzS-_BFSNuUStVWmE2nGDpKuvUhBBJk_CCQXV0,19144 +pip/_internal/vcs/mercurial.py,sha256=w1ZJWLKqNP1onEjkfjlwBVnMqPZNSIER8ayjQcnTq4w,5575 +pip/_internal/vcs/subversion.py,sha256=uUgdPvxmvEB8Qwtjr0Hc0XgFjbiNi5cbvI4vARLOJXo,11787 +pip/_internal/vcs/versioncontrol.py,sha256=Ma_HMZBVveSkeYvxacvqeujnkSIaF1XjxTsS3BwcJ8E,22599 +pip/_internal/wheel_builder.py,sha256=yvEULStZtty9Kplp89tDis3hGdyKQ-2BUbFLmJ_5ink,9010 +pip/_vendor/README.rst,sha256=pKKBwCWhu3M3qQ9dDnsmxb3KdsRr-nWmMq2srbH_Bi0,9394 +pip/_vendor/__init__.py,sha256=WzusPTGWIMeQQWSVJ0h2rafGkVTa9WKJ2HT-2-EoZrU,4907 +pip/_vendor/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/cachecontrol/LICENSE.txt,sha256=hu7uh74qQ_P_H1ZJb0UfaSQ5JvAl_tuwM2ZsMExMFhs,558 +pip/_vendor/cachecontrol/__init__.py,sha256=GxwRkm_TQBtPZpfpVK9r6S9dAy2DVnVgDVHJKTiPZ1k,820 +pip/_vendor/cachecontrol/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/_cmd.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/adapter.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/cache.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/controller.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/heuristics.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/serialize.cpython-312.pyc,, +pip/_vendor/cachecontrol/__pycache__/wrapper.cpython-312.pyc,, +pip/_vendor/cachecontrol/_cmd.py,sha256=iist2EpzJvDVIhMAxXq8iFnTBsiZAd6iplxfmNboNyk,1737 +pip/_vendor/cachecontrol/adapter.py,sha256=W-HW-l01gyCsnxkOyCbqx7sxrWYoBbKrDsKkVVQN6NE,6586 +pip/_vendor/cachecontrol/cache.py,sha256=OXwv7Fn2AwnKNiahJHnjtvaKLndvVLv_-zO-ltlV9qI,1953 +pip/_vendor/cachecontrol/caches/__init__.py,sha256=dtrrroK5BnADR1GWjCZ19aZ0tFsMfvFBtLQQU1sp_ag,303 +pip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-312.pyc,, +pip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-312.pyc,, +pip/_vendor/cachecontrol/caches/file_cache.py,sha256=d8upFmy_zwaCmlbWEVBlLXFddt8Zw8c5SFpxeOZsdfw,4117 +pip/_vendor/cachecontrol/caches/redis_cache.py,sha256=9rmqwtYu_ljVkW6_oLqbC7EaX_a8YT_yLuna-eS0dgo,1386 +pip/_vendor/cachecontrol/controller.py,sha256=xBauC-vUSu5GsJsxD4-W-JaKqqbBz0MN6Zv8PA2N8hI,19102 +pip/_vendor/cachecontrol/filewrapper.py,sha256=DhxC_rSk-beKdbsYhfvBUDovQHX9r3gHH_jP9-q_mKk,4354 +pip/_vendor/cachecontrol/heuristics.py,sha256=gqMXU8w0gQuEQiSdu3Yg-0vd9kW7nrWKbLca75rheGE,4881 +pip/_vendor/cachecontrol/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/cachecontrol/serialize.py,sha256=HQd2IllQ05HzPkVLMXTF2uX5mjEQjDBkxCqUJUODpZk,5163 +pip/_vendor/cachecontrol/wrapper.py,sha256=hsGc7g8QGQTT-4f8tgz3AM5qwScg6FO0BSdLSRdEvpU,1417 +pip/_vendor/certifi/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989 +pip/_vendor/certifi/__init__.py,sha256=969deMMS7Uchipr0oO4dbRBUvRi0uNYCn07VmG1aTrg,94 +pip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255 +pip/_vendor/certifi/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/certifi/__pycache__/__main__.cpython-312.pyc,, +pip/_vendor/certifi/__pycache__/core.cpython-312.pyc,, +pip/_vendor/certifi/cacert.pem,sha256=Tzl1_zCrvzVEO0hgZK6Ly0Hf9wf_31dsdtKS-0WKoKk,270954 +pip/_vendor/certifi/core.py,sha256=gu_ECVI1m3Rq0ytpsNE61hgQGcKaOAt9Rs9G8KsTCOI,3442 +pip/_vendor/certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/dependency_groups/LICENSE.txt,sha256=GrNuPipLqGMWJThPh-ngkdsfrtA0xbIzJbMjmr8sxSU,1099 +pip/_vendor/dependency_groups/__init__.py,sha256=C3OFu0NGwDzQ4LOmmSOFPsRSvkbBn-mdd4j_5YqJw-s,250 +pip/_vendor/dependency_groups/__main__.py,sha256=UNTM7P5mfVtT7wDi9kOTXWgV3fu3e8bTrt1Qp1jvjKo,1709 +pip/_vendor/dependency_groups/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/dependency_groups/__pycache__/__main__.cpython-312.pyc,, +pip/_vendor/dependency_groups/__pycache__/_implementation.cpython-312.pyc,, +pip/_vendor/dependency_groups/__pycache__/_lint_dependency_groups.cpython-312.pyc,, +pip/_vendor/dependency_groups/__pycache__/_pip_wrapper.cpython-312.pyc,, +pip/_vendor/dependency_groups/__pycache__/_toml_compat.cpython-312.pyc,, +pip/_vendor/dependency_groups/_implementation.py,sha256=Gqb2DlQELRakeHlKf6QtQSW0M-bcEomxHw4JsvID1ls,8041 +pip/_vendor/dependency_groups/_lint_dependency_groups.py,sha256=yp-DDqKXtbkDTNa0ifa-FmOA8ra24lPZEXftW-R5AuI,1710 +pip/_vendor/dependency_groups/_pip_wrapper.py,sha256=nuVW_w_ntVxpE26ELEvngMY0N04sFLsijXRyZZROFG8,1865 +pip/_vendor/dependency_groups/_toml_compat.py,sha256=BHnXnFacm3DeolsA35GjI6qkDApvua-1F20kv3BfZWE,285 +pip/_vendor/dependency_groups/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/distlib/LICENSE.txt,sha256=gI4QyKarjesUn_mz-xn0R6gICUYG1xKpylf-rTVSWZ0,14531 +pip/_vendor/distlib/__init__.py,sha256=Deo3uo98aUyIfdKJNqofeSEFWwDzrV2QeGLXLsgq0Ag,625 +pip/_vendor/distlib/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/distlib/__pycache__/compat.cpython-312.pyc,, +pip/_vendor/distlib/__pycache__/resources.cpython-312.pyc,, +pip/_vendor/distlib/__pycache__/scripts.cpython-312.pyc,, +pip/_vendor/distlib/__pycache__/util.cpython-312.pyc,, +pip/_vendor/distlib/compat.py,sha256=2jRSjRI4o-vlXeTK2BCGIUhkc6e9ZGhSsacRM5oseTw,41467 +pip/_vendor/distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820 +pip/_vendor/distlib/scripts.py,sha256=Qvp76E9Jc3IgyYubnpqI9fS7eseGOe4FjpeVKqKt9Iw,18612 +pip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792 +pip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784 +pip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032 +pip/_vendor/distlib/util.py,sha256=vMPGvsS4j9hF6Y9k3Tyom1aaHLb0rFmZAEyzeAdel9w,66682 +pip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648 +pip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448 +pip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888 +pip/_vendor/distro/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325 +pip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981 +pip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64 +pip/_vendor/distro/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/distro/__pycache__/__main__.cpython-312.pyc,, +pip/_vendor/distro/__pycache__/distro.cpython-312.pyc,, +pip/_vendor/distro/distro.py,sha256=XqbefacAhDT4zr_trnbA15eY8vdK4GTghgmvUGrEM_4,49430 +pip/_vendor/distro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/idna/LICENSE.md,sha256=t6M2q_OwThgOwGXN0W5wXQeeHMehT5EKpukYfza5zYc,1541 +pip/_vendor/idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868 +pip/_vendor/idna/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/idna/__pycache__/codec.cpython-312.pyc,, +pip/_vendor/idna/__pycache__/compat.cpython-312.pyc,, +pip/_vendor/idna/__pycache__/core.cpython-312.pyc,, +pip/_vendor/idna/__pycache__/idnadata.cpython-312.pyc,, +pip/_vendor/idna/__pycache__/intranges.cpython-312.pyc,, +pip/_vendor/idna/__pycache__/package_data.cpython-312.pyc,, +pip/_vendor/idna/__pycache__/uts46data.cpython-312.pyc,, +pip/_vendor/idna/codec.py,sha256=M2SGWN7cs_6B32QmKTyTN6xQGZeYQgQ2wiX3_DR6loE,3438 +pip/_vendor/idna/compat.py,sha256=RzLy6QQCdl9784aFhb2EX9EKGCJjg0P3PilGdeXXcx8,316 +pip/_vendor/idna/core.py,sha256=P26_XVycuMTZ1R2mNK1ZREVzM5mvTzdabBXfyZVU1Lc,13246 +pip/_vendor/idna/idnadata.py,sha256=SG8jhaGE53iiD6B49pt2pwTv_UvClciWE-N54oR2p4U,79623 +pip/_vendor/idna/intranges.py,sha256=amUtkdhYcQG8Zr-CoMM_kVRacxkivC1WgxN1b63KKdU,1898 +pip/_vendor/idna/package_data.py,sha256=_CUavOxobnbyNG2FLyHoN8QHP3QM9W1tKuw7eq9QwBk,21 +pip/_vendor/idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/idna/uts46data.py,sha256=H9J35VkD0F9L9mKOqjeNGd2A-Va6FlPoz6Jz4K7h-ps,243725 +pip/_vendor/msgpack/COPYING,sha256=SS3tuoXaWHL3jmCRvNH-pHTWYNNay03ulkuKqz8AdCc,614 +pip/_vendor/msgpack/__init__.py,sha256=RA8gcqK17YpkxBnNwXJVa1oa2LygWDgfF1nA1NPw3mo,1109 +pip/_vendor/msgpack/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/msgpack/__pycache__/exceptions.cpython-312.pyc,, +pip/_vendor/msgpack/__pycache__/ext.cpython-312.pyc,, +pip/_vendor/msgpack/__pycache__/fallback.cpython-312.pyc,, +pip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081 +pip/_vendor/msgpack/ext.py,sha256=kteJv03n9tYzd5oo3xYopVTo4vRaAxonBQQJhXohZZo,5726 +pip/_vendor/msgpack/fallback.py,sha256=0g1Pzp0vtmBEmJ5w9F3s_-JMVURP8RS4G1cc5TRaAsI,32390 +pip/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +pip/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +pip/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +pip/_vendor/packaging/__init__.py,sha256=y4lVbpeBzCGk-IPDw5BGBZ_b0P3ukEEJZAbGYc6Ey8c,494 +pip/_vendor/packaging/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/_elffile.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/_manylinux.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/_musllinux.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/_parser.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/_structures.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/_tokenizer.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/markers.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/metadata.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/pylock.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/requirements.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/specifiers.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/tags.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/utils.cpython-312.pyc,, +pip/_vendor/packaging/__pycache__/version.cpython-312.pyc,, +pip/_vendor/packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211 +pip/_vendor/packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559 +pip/_vendor/packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707 +pip/_vendor/packaging/_parser.py,sha256=U_DajsEx2VoC_F46fSVV3hDKNCWoQYkPkasO3dld0ig,10518 +pip/_vendor/packaging/_structures.py,sha256=Hn49Ta8zV9Wo8GiCL8Nl2ARZY983Un3pruZGVNldPwE,1514 +pip/_vendor/packaging/_tokenizer.py,sha256=M8EwNIdXeL9NMFuFrQtiOKwjka_xFx8KjRQnfE8O_z8,5421 +pip/_vendor/packaging/licenses/__init__.py,sha256=TwXLHZCXwSgdFwRLPxW602T6mSieunSFHM6fp8pgW78,5819 +pip/_vendor/packaging/licenses/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/packaging/licenses/__pycache__/_spdx.cpython-312.pyc,, +pip/_vendor/packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122 +pip/_vendor/packaging/markers.py,sha256=ZX-cLvW1S3cZcEc0fHI4z7zSx5U2T19yMpDP_mE-CYw,12771 +pip/_vendor/packaging/metadata.py,sha256=CWVZpN_HfoYMSSDuCP7igOvGgqA9AOmpW8f3qTisfnc,39360 +pip/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/packaging/pylock.py,sha256=-R1uNfJ4PaLto7Mg62YsGOHgvskuiIEqPwxOywl42Jk,22537 +pip/_vendor/packaging/requirements.py,sha256=PMCAWD8aNMnVD-6uZMedhBuAVX2573eZ4yPBLXmz04I,2870 +pip/_vendor/packaging/specifiers.py,sha256=tF2nC-jwW94FYe6So9dNGenQx1Hdif7ErmWlVp1QiXE,40821 +pip/_vendor/packaging/tags.py,sha256=cXLV1pJD3UtJlDg7Wz3zrfdQhRZqr8jumSAKKAAd2xE,22856 +pip/_vendor/packaging/utils.py,sha256=N4c6oZzFJy6klTZ3AnkNz7sSkJesuFWPp68LA3B5dAo,5040 +pip/_vendor/packaging/version.py,sha256=RVRKq8_GD5Bcak6E1kGG8K7siNZYW9n_XK8M2ZLl0H8,23284 +pip/_vendor/pkg_resources/LICENSE,sha256=htoPAa6uRjSKPD1GUZXcHOzN55956HdppkuNoEsqR0E,1023 +pip/_vendor/pkg_resources/__init__.py,sha256=vbTJ0_ruUgGxQjlEqsruFmiNPVyh2t9q-zyTDT053xI,124451 +pip/_vendor/pkg_resources/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/platformdirs/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089 +pip/_vendor/platformdirs/__init__.py,sha256=UfeSHWl8AeTtbOBOoHAxK4dODOWkZtfy-m_i7cWdJ8c,22344 +pip/_vendor/platformdirs/__main__.py,sha256=jBJ8zb7Mpx5ebcqF83xrpO94MaeCpNGHVf9cvDN2JLg,1505 +pip/_vendor/platformdirs/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/platformdirs/__pycache__/__main__.cpython-312.pyc,, +pip/_vendor/platformdirs/__pycache__/android.cpython-312.pyc,, +pip/_vendor/platformdirs/__pycache__/api.cpython-312.pyc,, +pip/_vendor/platformdirs/__pycache__/macos.cpython-312.pyc,, +pip/_vendor/platformdirs/__pycache__/unix.cpython-312.pyc,, +pip/_vendor/platformdirs/__pycache__/version.cpython-312.pyc,, +pip/_vendor/platformdirs/__pycache__/windows.cpython-312.pyc,, +pip/_vendor/platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013 +pip/_vendor/platformdirs/api.py,sha256=wPHOlwOsfz2oqQZ6A2FcCu5kEAj-JondzoNOHYFQ0h8,9281 +pip/_vendor/platformdirs/macos.py,sha256=0XoOgin1NK7Qki7iskD-oS8xKxw6bXgoKEgdqpCRAFQ,6322 +pip/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458 +pip/_vendor/platformdirs/version.py,sha256=BI_dKLSMwlkl57vlxZnT8oVjPiUC2W_sdx_8_h99HeQ,704 +pip/_vendor/platformdirs/windows.py,sha256=XvCfklGUMVxJbXit51jpYMN-lNeScPB82qS1CAeplL0,10362 +pip/_vendor/pygments/LICENSE,sha256=qdZvHVJt8C4p3Oc0NtNOVuhjL0bCdbvf_HBWnogvnxc,1331 +pip/_vendor/pygments/__init__.py,sha256=8uNqJCCwXqbEx5aSsBr0FykUQOBDKBihO5mPqiw1aqo,2983 +pip/_vendor/pygments/__main__.py,sha256=WrndpSe6i1ckX_SQ1KaxD9CTKGzD0EuCOFxcbwFpoLU,353 +pip/_vendor/pygments/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/__main__.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/console.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/filter.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/formatter.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/lexer.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/modeline.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/plugin.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/regexopt.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/scanner.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/sphinxext.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/style.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/token.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/unistring.cpython-312.pyc,, +pip/_vendor/pygments/__pycache__/util.cpython-312.pyc,, +pip/_vendor/pygments/console.py,sha256=AagDWqwea2yBWf10KC9ptBgMpMjxKp8yABAmh-NQOVk,1718 +pip/_vendor/pygments/filter.py,sha256=YLtpTnZiu07nY3oK9nfR6E9Y1FBHhP5PX8gvkJWcfag,1910 +pip/_vendor/pygments/filters/__init__.py,sha256=4U4jtA0X3iP83uQnB9-TI-HDSw8E8y8zMYHa0UjbbaI,40392 +pip/_vendor/pygments/filters/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/pygments/formatter.py,sha256=KZQMmyo_xkOIkQG8g66LYEkBh1bx7a0HyGCBcvhI9Ew,4390 +pip/_vendor/pygments/formatters/__init__.py,sha256=KTwBmnXlaopJhQDOemVHYHskiDghuq-08YtP6xPNJPg,5385 +pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-312.pyc,, +pip/_vendor/pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176 +pip/_vendor/pygments/lexer.py,sha256=_kBrOJ_NT5Tl0IVM0rA9c8eysP6_yrlGzEQI0eVYB-A,35349 +pip/_vendor/pygments/lexers/__init__.py,sha256=wbIME35GH7bI1B9rNPJFqWT-ij_RApZDYPUlZycaLzA,12115 +pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-312.pyc,, +pip/_vendor/pygments/lexers/__pycache__/python.cpython-312.pyc,, +pip/_vendor/pygments/lexers/_mapping.py,sha256=l4tCXM8e9aPC2BD6sjIr0deT-J-z5tHgCwL-p1fS0PE,77602 +pip/_vendor/pygments/lexers/python.py,sha256=vxjn1cOHclIKJKxoyiBsQTY65GHbkZtZRuKQ2AVCKaw,53853 +pip/_vendor/pygments/modeline.py,sha256=K5eSkR8GS1r5OkXXTHOcV0aM_6xpk9eWNEIAW-OOJ2g,1005 +pip/_vendor/pygments/plugin.py,sha256=tPx0rJCTIZ9ioRgLNYG4pifCbAwTRUZddvLw-NfAk2w,1891 +pip/_vendor/pygments/regexopt.py,sha256=wXaP9Gjp_hKAdnICqoDkRxAOQJSc4v3X6mcxx3z-TNs,3072 +pip/_vendor/pygments/scanner.py,sha256=nNcETRR1tRuiTaHmHSTTECVYFPcLf6mDZu1e4u91A9E,3092 +pip/_vendor/pygments/sphinxext.py,sha256=5x7Zh9YlU6ISJ31dMwduiaanb5dWZnKg3MyEQsseNnQ,7981 +pip/_vendor/pygments/style.py,sha256=PlOZqlsnTVd58RGy50vkA2cXQ_lP5bF5EGMEBTno6DA,6420 +pip/_vendor/pygments/styles/__init__.py,sha256=x9ebctfyvCAFpMTlMJ5YxwcNYBzjgq6zJaKkNm78r4M,2042 +pip/_vendor/pygments/styles/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/pygments/styles/__pycache__/_mapping.cpython-312.pyc,, +pip/_vendor/pygments/styles/_mapping.py,sha256=6lovFUE29tz6EsV3XYY4hgozJ7q1JL7cfO3UOlgnS8w,3312 +pip/_vendor/pygments/token.py,sha256=WbdWGhYm_Vosb0DDxW9lHNPgITXfWTsQmHt6cy9RbcM,6226 +pip/_vendor/pygments/unistring.py,sha256=al-_rBemRuGvinsrM6atNsHTmJ6DUbw24q2O2Ru1cBc,63208 +pip/_vendor/pygments/util.py,sha256=oRtSpiAo5jM9ulntkvVbgXUdiAW57jnuYGB7t9fYuhc,10031 +pip/_vendor/pyproject_hooks/LICENSE,sha256=GyKwSbUmfW38I6Z79KhNjsBLn9-xpR02DkK0NCyLQVQ,1081 +pip/_vendor/pyproject_hooks/__init__.py,sha256=cPB_a9LXz5xvsRbX1o2qyAdjLatZJdQ_Lc5McNX-X7Y,691 +pip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-312.pyc,, +pip/_vendor/pyproject_hooks/_impl.py,sha256=jY-raxnmyRyB57ruAitrJRUzEexuAhGTpgMygqx67Z4,14936 +pip/_vendor/pyproject_hooks/_in_process/__init__.py,sha256=MJNPpfIxcO-FghxpBbxkG1rFiQf6HOUbV4U5mq0HFns,557 +pip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/pyproject_hooks/_in_process/__pycache__/_in_process.cpython-312.pyc,, +pip/_vendor/pyproject_hooks/_in_process/_in_process.py,sha256=qcXMhmx__MIJq10gGHW3mA4Tl8dy8YzHMccwnNoKlw0,12216 +pip/_vendor/pyproject_hooks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/requests/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142 +pip/_vendor/requests/__init__.py,sha256=HlB_HzhrzGtfD_aaYUwUh1zWXLZ75_YCLyit75d0Vz8,5057 +pip/_vendor/requests/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/__version__.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/_internal_utils.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/adapters.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/api.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/auth.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/certs.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/compat.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/cookies.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/exceptions.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/help.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/hooks.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/models.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/packages.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/sessions.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/status_codes.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/structures.cpython-312.pyc,, +pip/_vendor/requests/__pycache__/utils.cpython-312.pyc,, +pip/_vendor/requests/__version__.py,sha256=QKDceK8K_ujqwDDc3oYrR0odOBYgKVOQQ5vFap_G_cg,435 +pip/_vendor/requests/_internal_utils.py,sha256=nMQymr4hs32TqVo5AbCrmcJEhvPUh7xXlluyqwslLiQ,1495 +pip/_vendor/requests/adapters.py,sha256=2MLFOK9GpYNhiTd6zLDUrAgSkIB-76i6pmSuUJjHC2w,26429 +pip/_vendor/requests/api.py,sha256=_Zb9Oa7tzVIizTKwFrPjDEY9ejtm_OnSRERnADxGsQs,6449 +pip/_vendor/requests/auth.py,sha256=kF75tqnLctZ9Mf_hm9TZIj4cQWnN5uxRz8oWsx5wmR0,10186 +pip/_vendor/requests/certs.py,sha256=kHDlkK_beuHXeMPc5jta2wgl8gdKeUWt5f2nTDVrvt8,441 +pip/_vendor/requests/compat.py,sha256=QfbmdTFiZzjSHMXiMrd4joCRU6RabtQ9zIcPoVaHIus,1822 +pip/_vendor/requests/cookies.py,sha256=bNi-iqEj4NPZ00-ob-rHvzkvObzN3lEpgw3g6paS3Xw,18590 +pip/_vendor/requests/exceptions.py,sha256=D1wqzYWne1mS2rU43tP9CeN1G7QAy7eqL9o1god6Ejw,4272 +pip/_vendor/requests/help.py,sha256=hRKaf9u0G7fdwrqMHtF3oG16RKktRf6KiwtSq2Fo1_0,3813 +pip/_vendor/requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733 +pip/_vendor/requests/models.py,sha256=taljlg6vJ4b-xMu2TaMNFFkaiwMex_VsEQ6qUTN3wzY,35575 +pip/_vendor/requests/packages.py,sha256=_ZQDCJTJ8SP3kVWunSqBsRZNPzj2c1WFVqbdr08pz3U,1057 +pip/_vendor/requests/sessions.py,sha256=Cl1dpEnOfwrzzPbku-emepNeN4Rt_0_58Iy2x-JGTm8,30503 +pip/_vendor/requests/status_codes.py,sha256=iJUAeA25baTdw-6PfD0eF4qhpINDJRJI-yaMqxs4LEI,4322 +pip/_vendor/requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912 +pip/_vendor/requests/utils.py,sha256=WS3wHSQaaEfceu1syiFo5jf4e_CWKUTep_IabOVI_J0,33225 +pip/_vendor/resolvelib/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751 +pip/_vendor/resolvelib/__init__.py,sha256=yoX-d4STvwGGCiQRE5cJC9Cter69SgVgqClxOCvSP7M,541 +pip/_vendor/resolvelib/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/resolvelib/__pycache__/providers.cpython-312.pyc,, +pip/_vendor/resolvelib/__pycache__/reporters.cpython-312.pyc,, +pip/_vendor/resolvelib/__pycache__/structs.cpython-312.pyc,, +pip/_vendor/resolvelib/providers.py,sha256=pIWJbIdJJ9GFtNbtwTH0Ia43Vj6hYCEJj2DOLue15FM,8914 +pip/_vendor/resolvelib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/resolvelib/reporters.py,sha256=pNJf4nFxLpAeKxlBUi2GEj0a2Ij1nikY0UabTKXesT4,2037 +pip/_vendor/resolvelib/resolvers/__init__.py,sha256=728M3EvmnPbVXS7ExXlv2kMu6b7wEsoPutEfl-uVk_I,640 +pip/_vendor/resolvelib/resolvers/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/resolvelib/resolvers/__pycache__/abstract.cpython-312.pyc,, +pip/_vendor/resolvelib/resolvers/__pycache__/criterion.cpython-312.pyc,, +pip/_vendor/resolvelib/resolvers/__pycache__/exceptions.cpython-312.pyc,, +pip/_vendor/resolvelib/resolvers/__pycache__/resolution.cpython-312.pyc,, +pip/_vendor/resolvelib/resolvers/abstract.py,sha256=CNeQPnpAudY77nmzOkONSmAgRlzIf06X-X9mvRYODms,1543 +pip/_vendor/resolvelib/resolvers/criterion.py,sha256=lcmZGv5sKHOnFD_RzZwvlGSj19MeA-5rCMpdf2Sgw7Y,1768 +pip/_vendor/resolvelib/resolvers/exceptions.py,sha256=ln_jaQtgLlRUSFY627yiHG2gD7AgaXzRKaElFVh7fDQ,1768 +pip/_vendor/resolvelib/resolvers/resolution.py,sha256=3J_zkW-sD3EY-BlNXjyln__njpyH5n0UZJT6uV7CheA,24212 +pip/_vendor/resolvelib/structs.py,sha256=pu-EJiR2IBITr2SQeNPRa0rXhjlStfmO_GEgAhr3004,6420 +pip/_vendor/rich/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056 +pip/_vendor/rich/__init__.py,sha256=dRxjIL-SbFVY0q3IjSMrfgBTHrm1LZDgLOygVBwiYZc,6090 +pip/_vendor/rich/__main__.py,sha256=e_aVC-tDzarWQW9SuZMuCgBr6ODV_iDNV2Wh2xkxOlw,7896 +pip/_vendor/rich/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/__main__.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_cell_widths.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_emoji_codes.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_emoji_replace.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_export_format.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_extension.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_fileno.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_inspect.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_log_render.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_loop.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_null_file.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_palettes.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_pick.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_ratio.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_spinners.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_stack.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_timer.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_win32_console.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_windows.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_windows_renderer.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/_wrap.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/abc.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/align.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/ansi.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/bar.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/box.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/cells.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/color.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/color_triplet.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/columns.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/console.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/constrain.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/containers.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/control.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/default_styles.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/diagnose.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/emoji.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/errors.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/file_proxy.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/filesize.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/highlighter.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/json.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/jupyter.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/layout.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/live.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/live_render.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/logging.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/markup.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/measure.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/padding.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/pager.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/palette.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/panel.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/pretty.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/progress.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/progress_bar.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/prompt.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/protocol.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/region.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/repr.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/rule.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/scope.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/screen.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/segment.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/spinner.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/status.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/style.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/styled.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/syntax.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/table.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/terminal_theme.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/text.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/theme.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/themes.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/traceback.cpython-312.pyc,, +pip/_vendor/rich/__pycache__/tree.cpython-312.pyc,, +pip/_vendor/rich/_cell_widths.py,sha256=fbmeyetEdHjzE_Vx2l1uK7tnPOhMs2X1lJfO3vsKDpA,10209 +pip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235 +pip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064 +pip/_vendor/rich/_export_format.py,sha256=RI08pSrm5tBSzPMvnbTqbD9WIalaOoN5d4M1RTmLq1Y,2128 +pip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265 +pip/_vendor/rich/_fileno.py,sha256=HWZxP5C2ajMbHryvAQZseflVfQoGzsKOHzKGsLD8ynQ,799 +pip/_vendor/rich/_inspect.py,sha256=ROT0PLC2GMWialWZkqJIjmYq7INRijQQkoSokWTaAiI,9656 +pip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225 +pip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236 +pip/_vendor/rich/_null_file.py,sha256=ADGKp1yt-k70FMKV6tnqCqecB-rSJzp-WQsD7LPL-kg,1394 +pip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063 +pip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423 +pip/_vendor/rich/_ratio.py,sha256=IOtl78sQCYZsmHyxhe45krkb68u9xVz7zFsXVJD-b2Y,5325 +pip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919 +pip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351 +pip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417 +pip/_vendor/rich/_win32_console.py,sha256=BSaDRIMwBLITn_m0mTRLPqME5q-quGdSMuYMpYeYJwc,22755 +pip/_vendor/rich/_windows.py,sha256=aBwaD_S56SbgopIvayVmpk0Y28uwY2C5Bab1wl3Bp-I,1925 +pip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783 +pip/_vendor/rich/_wrap.py,sha256=FlSsom5EX0LVkA3KWy34yHnCfLtqX-ZIepXKh-70rpc,3404 +pip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890 +pip/_vendor/rich/align.py,sha256=dg-7uY0ukMLLlUEsBDRLva22_sQgIJD4BK0dmZHFHug,10324 +pip/_vendor/rich/ansi.py,sha256=Avs1LHbSdcyOvDOdpELZUoULcBiYewY76eNBp6uFBhs,6921 +pip/_vendor/rich/bar.py,sha256=ldbVHOzKJOnflVNuv1xS7g6dLX2E3wMnXkdPbpzJTcs,3263 +pip/_vendor/rich/box.py,sha256=kmavBc_dn73L_g_8vxWSwYJD2uzBXOUFTtJOfpbczcM,10686 +pip/_vendor/rich/cells.py,sha256=KrQkj5-LghCCpJLSNQIyAZjndc4bnEqOEmi5YuZ9UCY,5130 +pip/_vendor/rich/color.py,sha256=3HSULVDj7qQkXUdFWv78JOiSZzfy5y1nkcYhna296V0,18211 +pip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054 +pip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131 +pip/_vendor/rich/console.py,sha256=t9azZpmRMVU5cphVBZSShNsmBxd2-IAWcTTlhor-E1s,100849 +pip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288 +pip/_vendor/rich/containers.py,sha256=c_56TxcedGYqDepHBMTuZdUIijitAQgnox-Qde0Z1qo,5502 +pip/_vendor/rich/control.py,sha256=EUTSUFLQbxY6Zmo_sdM-5Ls323vIHTBfN8TPulqeHUY,6487 +pip/_vendor/rich/default_styles.py,sha256=khQFqqaoDs3bprMqWpHw8nO5UpG2DN6QtuTd6LzZwYc,8257 +pip/_vendor/rich/diagnose.py,sha256=fJl1TItRn19gGwouqTg-8zPUW3YqQBqGltrfPQs1H9w,1025 +pip/_vendor/rich/emoji.py,sha256=Wd4bQubZdSy6-PyrRQNuMHtn2VkljK9uPZPVlu2cmx0,2367 +pip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642 +pip/_vendor/rich/file_proxy.py,sha256=Tl9THMDZ-Pk5Wm8sI1gGg_U5DhusmxD-FZ0fUbcU0W0,1683 +pip/_vendor/rich/filesize.py,sha256=_iz9lIpRgvW7MNSeCZnLg-HwzbP4GETg543WqD8SFs0,2484 +pip/_vendor/rich/highlighter.py,sha256=G_sn-8DKjM1sEjLG_oc4ovkWmiUpWvj8bXi0yed2LnY,9586 +pip/_vendor/rich/json.py,sha256=vVEoKdawoJRjAFayPwXkMBPLy7RSTs-f44wSQDR2nJ0,5031 +pip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252 +pip/_vendor/rich/layout.py,sha256=ajkSFAtEVv9EFTcFs-w4uZfft7nEXhNzL7ZVdgrT5rI,14004 +pip/_vendor/rich/live.py,sha256=tF3ukAAJZ_N2ZbGclqZ-iwLoIoZ8f0HHUz79jAyJqj8,15180 +pip/_vendor/rich/live_render.py,sha256=It_39YdzrBm8o3LL0kaGorPFg-BfZWAcrBjLjFokbx4,3521 +pip/_vendor/rich/logging.py,sha256=5KaPPSMP9FxcXPBcKM4cGd_zW78PMgf-YbMVnvfSw0o,12468 +pip/_vendor/rich/markup.py,sha256=3euGKP5s41NCQwaSjTnJxus5iZMHjxpIM0W6fCxra38,8451 +pip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305 +pip/_vendor/rich/padding.py,sha256=KVEI3tOwo9sgK1YNSuH__M1_jUWmLZwRVV_KmOtVzyM,4908 +pip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828 +pip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396 +pip/_vendor/rich/panel.py,sha256=9sQl00hPIqH5G2gALQo4NepFwpP0k9wT-s_gOms5pIc,11157 +pip/_vendor/rich/pretty.py,sha256=gy3S72u4FRg2ytoo7N1ZDWDIvB4unbzd5iUGdgm-8fc,36391 +pip/_vendor/rich/progress.py,sha256=CUc2lkU-X59mVdGfjMCBkZeiGPL3uxdONjhNJF2T7wY,60408 +pip/_vendor/rich/progress_bar.py,sha256=mZTPpJUwcfcdgQCTTz3kyY-fc79ddLwtx6Ghhxfo064,8162 +pip/_vendor/rich/prompt.py,sha256=l0RhQU-0UVTV9e08xW1BbIj0Jq2IXyChX4lC0lFNzt4,12447 +pip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391 +pip/_vendor/rich/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166 +pip/_vendor/rich/repr.py,sha256=5MZJZmONgC6kud-QW-_m1okXwL2aR6u6y-pUcUCJz28,4431 +pip/_vendor/rich/rule.py,sha256=0fNaS_aERa3UMRc3T5WMpN_sumtDxfaor2y3of1ftBk,4602 +pip/_vendor/rich/scope.py,sha256=TMUU8qo17thyqQCPqjDLYpg_UU1k5qVd-WwiJvnJVas,2843 +pip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591 +pip/_vendor/rich/segment.py,sha256=otnKeKGEV-WRlQVosfJVeFDcDxAKHpvJ_hLzSu5lumM,24743 +pip/_vendor/rich/spinner.py,sha256=onIhpKlljRHppTZasxO8kXgtYyCHUkpSgKglRJ3o51g,4214 +pip/_vendor/rich/status.py,sha256=kkPph3YeAZBo-X-4wPp8gTqZyU466NLwZBA4PZTTewo,4424 +pip/_vendor/rich/style.py,sha256=W9Ccy8Py8lNICtlfcp-ryzMTuQaGxAU3av7-g5fHu0s,26990 +pip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258 +pip/_vendor/rich/syntax.py,sha256=eDKIRwl--eZ0Lwo2da2RRtfutXGavrJO61Cl5OkS59U,36371 +pip/_vendor/rich/table.py,sha256=ZmT7V7MMCOYKw7TGY9SZLyYDf6JdM-WVf07FdVuVhTI,40049 +pip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370 +pip/_vendor/rich/text.py,sha256=AO7JPCz6-gaN1thVLXMBntEmDPVYFgFNG1oM61_sanU,47552 +pip/_vendor/rich/theme.py,sha256=oNyhXhGagtDlbDye3tVu3esWOWk0vNkuxFw-_unlaK0,3771 +pip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102 +pip/_vendor/rich/traceback.py,sha256=c0WmB_L04_UfZbLaoH982_U_s7eosxKMUiAVmDPdRYU,35861 +pip/_vendor/rich/tree.py,sha256=yWnQ6rAvRGJ3qZGqBrxS2SW2TKBTNrP0SdY8QxOFPuw,9451 +pip/_vendor/tomli/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +pip/_vendor/tomli/__init__.py,sha256=qzEGl8QHhqgQPCuLzfKyPIuH3KKPspf-UVPbZ0ppBD4,314 +pip/_vendor/tomli/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/tomli/__pycache__/_parser.cpython-312.pyc,, +pip/_vendor/tomli/__pycache__/_re.cpython-312.pyc,, +pip/_vendor/tomli/__pycache__/_types.cpython-312.pyc,, +pip/_vendor/tomli/_parser.py,sha256=bO8tUYmnyA2K6m4TnbQbfUqmIFcDv7mG1KuC9gqRVmA,25778 +pip/_vendor/tomli/_re.py,sha256=n8-Io8ZK1U-F6jzlg7Pabc40hLFJsawE2uNLKH9w7iU,3235 +pip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254 +pip/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 +pip/_vendor/tomli_w/LICENSE,sha256=uAgWsNUwuKzLTCIReDeQmEpuO2GSLCte6S8zcqsnQv4,1072 +pip/_vendor/tomli_w/__init__.py,sha256=0F8yDtXx3Uunhm874KrAcP76srsM98y7WyHQwCulZbo,169 +pip/_vendor/tomli_w/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/tomli_w/__pycache__/_writer.cpython-312.pyc,, +pip/_vendor/tomli_w/_writer.py,sha256=dsifFS2xYf1i76mmRyfz9y125xC7Z_HQ845ZKhJsYXs,6961 +pip/_vendor/tomli_w/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26 +pip/_vendor/truststore/LICENSE,sha256=M757fo-k_Rmxdg4ajtimaL2rhSyRtpLdQUJLy3Jan8o,1086 +pip/_vendor/truststore/__init__.py,sha256=Bu7kqkmpunhLsj5xCu8gT_25ktoPXcSnwe8VHk1GmJo,1320 +pip/_vendor/truststore/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/truststore/__pycache__/_api.cpython-312.pyc,, +pip/_vendor/truststore/__pycache__/_macos.cpython-312.pyc,, +pip/_vendor/truststore/__pycache__/_openssl.cpython-312.pyc,, +pip/_vendor/truststore/__pycache__/_ssl_constants.cpython-312.pyc,, +pip/_vendor/truststore/__pycache__/_windows.cpython-312.pyc,, +pip/_vendor/truststore/_api.py,sha256=CYJCV5BTfttZYfqY3movdMBE-8az7uhET_LYbKT2Nn4,11413 +pip/_vendor/truststore/_macos.py,sha256=nZlLkOmszUE0g6ryRwBVGY5COzPyudcsiJtDWarM5LQ,20503 +pip/_vendor/truststore/_openssl.py,sha256=zB-SQvJydks7tQ0yIwrP6GD3fQNSSaPiq7zw4yF5T40,2412 +pip/_vendor/truststore/_ssl_constants.py,sha256=NUD4fVKdSD02ri7-db0tnO0VqLP9aHuzmStcW7tAl08,1130 +pip/_vendor/truststore/_windows.py,sha256=rAHyKYD8M7t-bXfG8VgOVa3TpfhVhbt4rZQlO45YuP8,17993 +pip/_vendor/truststore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/LICENSE.txt,sha256=w3vxhuJ8-dvpYZ5V7f486nswCRzrPaY8fay-Dm13kHs,1115 +pip/_vendor/urllib3/__init__.py,sha256=iXLcYiJySn0GNbWOOZDDApgBL1JgP44EZ8i1760S8Mc,3333 +pip/_vendor/urllib3/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/_collections.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/_version.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/connection.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/connectionpool.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/exceptions.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/fields.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/filepost.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/poolmanager.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/request.cpython-312.pyc,, +pip/_vendor/urllib3/__pycache__/response.cpython-312.pyc,, +pip/_vendor/urllib3/_collections.py,sha256=pyASJJhW7wdOpqJj9QJA8FyGRfr8E8uUUhqUvhF0728,11372 +pip/_vendor/urllib3/_version.py,sha256=t9wGB6ooOTXXgiY66K1m6BZS1CJyXHAU8EoWDTe6Shk,64 +pip/_vendor/urllib3/connection.py,sha256=ttIA909BrbTUzwkqEe_TzZVh4JOOj7g61Ysei2mrwGg,20314 +pip/_vendor/urllib3/connectionpool.py,sha256=e2eiAwNbFNCKxj4bwDKNK-w7HIdSz3OmMxU_TIt-evQ,40408 +pip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/appengine.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/securetransport.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/_appengine_environ.py,sha256=bDbyOEhW2CKLJcQqAKAyrEHN-aklsyHFKq6vF8ZFsmk,957 +pip/_vendor/urllib3/contrib/_securetransport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/bindings.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/__pycache__/low_level.cpython-312.pyc,, +pip/_vendor/urllib3/contrib/_securetransport/bindings.py,sha256=4Xk64qIkPBt09A5q-RIFUuDhNc9mXilVapm7WnYnzRw,17632 +pip/_vendor/urllib3/contrib/_securetransport/low_level.py,sha256=B2JBB2_NRP02xK6DCa1Pa9IuxrPwxzDzZbixQkb7U9M,13922 +pip/_vendor/urllib3/contrib/appengine.py,sha256=VR68eAVE137lxTgjBDwCna5UiBZTOKa01Aj_-5BaCz4,11036 +pip/_vendor/urllib3/contrib/ntlmpool.py,sha256=NlfkW7WMdW8ziqudopjHoW299og1BTWi0IeIibquFwk,4528 +pip/_vendor/urllib3/contrib/pyopenssl.py,sha256=hDJh4MhyY_p-oKlFcYcQaVQRDv6GMmBGuW9yjxyeejM,17081 +pip/_vendor/urllib3/contrib/securetransport.py,sha256=Fef1IIUUFHqpevzXiDPbIGkDKchY2FVKeVeLGR1Qq3g,34446 +pip/_vendor/urllib3/contrib/socks.py,sha256=aRi9eWXo9ZEb95XUxef4Z21CFlnnjbEiAo9HOseoMt4,7097 +pip/_vendor/urllib3/exceptions.py,sha256=0Mnno3KHTNfXRfY7638NufOPkUb6mXOm-Lqj-4x2w8A,8217 +pip/_vendor/urllib3/fields.py,sha256=kvLDCg_JmH1lLjUUEY_FLS8UhY7hBvDPuVETbY8mdrM,8579 +pip/_vendor/urllib3/filepost.py,sha256=5b_qqgRHVlL7uLtdAYBzBh-GHmU5AfJVt_2N0XS3PeY,2440 +pip/_vendor/urllib3/packages/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/urllib3/packages/__pycache__/six.cpython-312.pyc,, +pip/_vendor/urllib3/packages/backports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-312.pyc,, +pip/_vendor/urllib3/packages/backports/__pycache__/weakref_finalize.cpython-312.pyc,, +pip/_vendor/urllib3/packages/backports/makefile.py,sha256=nbzt3i0agPVP07jqqgjhaYjMmuAi_W5E0EywZivVO8E,1417 +pip/_vendor/urllib3/packages/backports/weakref_finalize.py,sha256=tRCal5OAhNSRyb0DhHp-38AtIlCsRP8BxF3NX-6rqIA,5343 +pip/_vendor/urllib3/packages/six.py,sha256=b9LM0wBXv7E7SrbCjAm4wwN-hrH-iNxv18LgWNMMKPo,34665 +pip/_vendor/urllib3/poolmanager.py,sha256=aWyhXRtNO4JUnCSVVqKTKQd8EXTvUm1VN9pgs2bcONo,19990 +pip/_vendor/urllib3/request.py,sha256=YTWFNr7QIwh7E1W9dde9LM77v2VWTJ5V78XuTTw7D1A,6691 +pip/_vendor/urllib3/response.py,sha256=fmDJAFkG71uFTn-sVSTh2Iw0WmcXQYqkbRjihvwBjU8,30641 +pip/_vendor/urllib3/util/__init__.py,sha256=JEmSmmqqLyaw8P51gUImZh8Gwg9i1zSe-DoqAitn2nc,1155 +pip/_vendor/urllib3/util/__pycache__/__init__.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/connection.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/proxy.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/queue.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/request.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/response.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/retry.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssl_.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/timeout.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/url.cpython-312.pyc,, +pip/_vendor/urllib3/util/__pycache__/wait.cpython-312.pyc,, +pip/_vendor/urllib3/util/connection.py,sha256=5Lx2B1PW29KxBn2T0xkN1CBgRBa3gGVJBKoQoRogEVk,4901 +pip/_vendor/urllib3/util/proxy.py,sha256=zUvPPCJrp6dOF0N4GAVbOcl6o-4uXKSrGiTkkr5vUS4,1605 +pip/_vendor/urllib3/util/queue.py,sha256=nRgX8_eX-_VkvxoX096QWoz8Ps0QHUAExILCY_7PncM,498 +pip/_vendor/urllib3/util/request.py,sha256=C0OUt2tcU6LRiQJ7YYNP9GvPrSvl7ziIBekQ-5nlBZk,3997 +pip/_vendor/urllib3/util/response.py,sha256=GJpg3Egi9qaJXRwBh5wv-MNuRWan5BIu40oReoxWP28,3510 +pip/_vendor/urllib3/util/retry.py,sha256=6ENvOZ8PBDzh8kgixpql9lIrb2dxH-k7ZmBanJF2Ng4,22050 +pip/_vendor/urllib3/util/ssl_.py,sha256=QDuuTxPSCj1rYtZ4xpD7Ux-r20TD50aHyqKyhQ7Bq4A,17460 +pip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ir4cZVEjmAk8gUAIHWSi7wtOO83UCYABY2xFD1Ql_WA,5758 +pip/_vendor/urllib3/util/ssltransport.py,sha256=NA-u5rMTrDFDFC8QzRKUEKMG0561hOD4qBTr3Z4pv6E,6895 +pip/_vendor/urllib3/util/timeout.py,sha256=cwq4dMk87mJHSBktK1miYJ-85G-3T3RmT20v7SFCpno,10168 +pip/_vendor/urllib3/util/url.py,sha256=lCAE7M5myA8EDdW0sJuyyZhVB9K_j38ljWhHAnFaWoE,14296 +pip/_vendor/urllib3/util/wait.py,sha256=fOX0_faozG2P7iVojQoE1mbydweNyTcm-hXEfFrTtLI,5403 +pip/_vendor/vendor.txt,sha256=f2msFLZ-chXWIZSKW31NLGyMWmt_-Vfy7sY5dHYgmnw,342 +pip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286 diff --git a/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/REQUESTED b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/entry_points.txt b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..c6436d21fcc6479564ce8581c93e30e2cc60a096 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip-26.0.1.dist-info/entry_points.txt @@ -0,0 +1,4 @@ +[console_scripts] +pip=pip._internal.cli.main:main +pip3=pip._internal.cli.main:main + diff --git a/.venv_haddock/lib/python3.12/site-packages/pip/__init__.py b/.venv_haddock/lib/python3.12/site-packages/pip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..978b4129206ef2857676dcf0fb4f71243b35328f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip/__init__.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +__version__ = "26.0.1" + + +def main(args: list[str] | None = None) -> int: + """This is an internal API only meant for use by pip's own console scripts. + + For additional details, see https://github.com/pypa/pip/issues/7498. + """ + from pip._internal.utils.entrypoints import _wrapper + + return _wrapper(args) diff --git a/.venv_haddock/lib/python3.12/site-packages/pip/__main__.py b/.venv_haddock/lib/python3.12/site-packages/pip/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..5991326115fe5026470165b387ba2bc78bceb006 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip/__main__.py @@ -0,0 +1,24 @@ +import os +import sys + +# Remove '' and current working directory from the first entry +# of sys.path, if present to avoid using current directory +# in pip commands check, freeze, install, list and show, +# when invoked as python -m pip +if sys.path[0] in ("", os.getcwd()): + sys.path.pop(0) + +# If we are running from a wheel, add the wheel to sys.path +# This allows the usage python pip-*.whl/pip install pip-*.whl +if __package__ == "": + # __file__ is pip-*.whl/pip/__main__.py + # first dirname call strips of '/__main__.py', second strips off '/pip' + # Resulting path is the name of the wheel itself + # Add that to sys.path so we can import pip + path = os.path.dirname(os.path.dirname(__file__)) + sys.path.insert(0, path) + +if __name__ == "__main__": + from pip._internal.cli.main import main as _main + + sys.exit(_main()) diff --git a/.venv_haddock/lib/python3.12/site-packages/pip/__pip-runner__.py b/.venv_haddock/lib/python3.12/site-packages/pip/__pip-runner__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6be157831a67d8d45d75ce1c6f14aad0ad47b8f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip/__pip-runner__.py @@ -0,0 +1,50 @@ +"""Execute exactly this copy of pip, within a different environment. + +This file is named as it is, to ensure that this module can't be imported via +an import statement. +""" + +# /!\ This version compatibility check section must be Python 2 compatible. /!\ + +import sys + +# Copied from pyproject.toml +PYTHON_REQUIRES = (3, 9) + + +def version_str(version): # type: ignore + return ".".join(str(v) for v in version) + + +if sys.version_info[:2] < PYTHON_REQUIRES: + raise SystemExit( + "This version of pip does not support python {} (requires >={}).".format( + version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES) + ) + ) + +# From here on, we can use Python 3 features, but the syntax must remain +# Python 2 compatible. + +import runpy # noqa: E402 +from importlib.machinery import PathFinder # noqa: E402 +from os.path import dirname # noqa: E402 + +PIP_SOURCES_ROOT = dirname(dirname(__file__)) + + +class PipImportRedirectingFinder: + @classmethod + def find_spec(self, fullname, path=None, target=None): # type: ignore + if fullname != "pip": + return None + + spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target) + assert spec, (PIP_SOURCES_ROOT, fullname) + return spec + + +sys.meta_path.insert(0, PipImportRedirectingFinder()) + +assert __name__ == "__main__", "Cannot run __pip-runner__.py as a non-main module" +runpy.run_module("pip", run_name="__main__", alter_sys=True) diff --git a/.venv_haddock/lib/python3.12/site-packages/pip/py.typed b/.venv_haddock/lib/python3.12/site-packages/pip/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..493b53e4e7a3984ddd49780313bf3bd9901dc1e0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pip/py.typed @@ -0,0 +1,4 @@ +pip is a command line program. While it is implemented in Python, and so is +available for import, you must not use pip's internal APIs in this way. Typing +information is provided as a convenience only and is not a guarantee. Expect +unannounced changes to the API and types in releases. diff --git a/.venv_haddock/lib/python3.12/site-packages/prodigy_lig/__init__.py b/.venv_haddock/lib/python3.12/site-packages/prodigy_lig/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20ab5a90c0ffceb1678b00cc43ff61e2a2873a8e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/prodigy_lig/__init__.py @@ -0,0 +1 @@ +version = '1.0.1' diff --git a/.venv_haddock/lib/python3.12/site-packages/prodigy_lig/prodigy_lig.py b/.venv_haddock/lib/python3.12/site-packages/prodigy_lig/prodigy_lig.py new file mode 100644 index 0000000000000000000000000000000000000000..c6151bc03f8e30c103a0e9ad3b3e4cb323e69145 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/prodigy_lig/prodigy_lig.py @@ -0,0 +1,618 @@ +""" +Calculate the Binding Affinity score using the PRODIGY-LIG model +prodigy_lig dependes on biopython for the structure manipulations +and only requires a single structure file (in mmCIF or PDB format) +as input. + +prodigy_lig is licensed under the Apache License 2.0 included in +the LICENSE file of this repository or at the following URL +https://github.com/haddocking/prodigy-lig/blob/master/LICENSE + +If you use prodigy_lig in your research please cite the following +papers: + +1. https://doi.org/10.1093/bioinformatics/bty816 +2. https://doi.org/10.1007/s10822-017-0049-y +""" + +from os.path import basename, splitext +import sys +import argparse + +try: + from Bio.PDB import PDBParser, FastMMCIFParser, PDBIO +except ImportError: + print( + "prodigy_lig depends on Biopython. Please install " + "Biopython along with its dependencies and restart." + ) + sys.exit(1) + + +class ProdigyLig(object): + """Run the prodigy-lig calculations and store all the relevant output.""" + + def __init__(self, structure, chains, electrostatics, cutoff=10.5): + """Initialise the Prodigy-lig instance.""" + self.chains = self._parse_chains(chains) + self.structure = self._clean_structure(structure) + self.electrostatics = electrostatics + self.cutoff = cutoff + self.dg_score = None + self.dg_elec = None + self.dg = None + self.atomic_contacts = None + self.contact_counts = None + + def predict(self): + """ + API method used by the webserver + """ + self.atomic_contacts = calc_atomic_contacts( + self.structure, self.chains, self.cutoff + ) + + if len(self.atomic_contacts) == 0: + raise RuntimeWarning("There are no contacts between the specified chains.") + + self.contact_counts = calculate_contact_counts(self.atomic_contacts) + + if self.electrostatics is not None: + self.dg_score = calculate_score(self.contact_counts, self.electrostatics) + self.dg_elec = calculate_DG_electrostatics( + self.contact_counts, self.electrostatics + ) + self.dg = calculate_DG(self.contact_counts) + + def as_dict(self): + """Return the data of the class as a dictionary for the server.""" + data = { + "structure": self.structure.id, + "chains": self.chains, + "electrostatics": self.electrostatics, + "cutoff": self.cutoff, + "dg_score": self.dg_score, + "dg_elec": self.dg_elec, + "dg": self.dg, + } + + data.update(self.contact_counts) + + return data + + def _clean_structure(self, structure): + """ + Remove all the unnecessary elements from the structure. + + Water molecules, ions and cofactors need to be removed from the structure + because otherwise their presence might affect the algorithm. In the case + of multi-model structures we are only keeping the first model. + """ + + def _is_it_a_residue(residue): + """ + Check for the presence of backbone atoms. + + Pretty often PDB files contain modified residues that are part of + a protein but are classified as HETATM, such as a selenomethionine + (MSE). We want to keep these atoms instead of discarding them. + """ + backbone_atoms = {"C", "CA", "N", "O"} + residue_atoms = set([_.id for _ in residue.child_list]) + + if len(residue_atoms.intersection(backbone_atoms)) >= 3: + return True + else: + return False + + if len(structure) > 1: + for i in range(1, len(structure)): + structure.detach_child(structure[i].id) + + chains = self.chains[0] + list(self.chains[1][0]) + specified_chains = {chain for chain in chains} + structure_chains = [chain.id for chain in list(structure.get_chains())] + + for chain in specified_chains: + if chain not in structure_chains: + raise RuntimeWarning( + ( + "Chain {} specified during runtime wasn't found " + "in the structure" + ).format(chain) + ) + + ligand_chain, ligand_residue = self.chains[1] + ligand_residues = [_.resname for _ in structure[0][ligand_chain].child_list] + + if ligand_residue not in ligand_residues: + raise RuntimeError( + ( + "Ligand identifier {} not found " "in chain {} of the input file." + ).format(ligand_residue, ligand_chain) + ) + + if ligand_residues.count(ligand_residue) > 1: + raise RuntimeError( + ( + "Ligand identifier {} found {} times in " + "chain {} of the input file. Please " + "remove the redundant molecule(s)." + ).format( + ligand_residue, ligand_residues.count(ligand_residue), ligand_chain + ) + ) + + for chain in structure_chains: + if chain not in specified_chains: + structure[0].detach_child(chain) + else: + for res in list(structure[0][chain].child_list): + if res.id[0] == "W": + structure[0][chain].detach_child(res.id) + continue + if chain not in self.chains[0]: + # We are only interested in the ligand here. + # Everything else can go. + if res.resname != ligand_residue: + structure[0][chain].detach_child(res.id) + else: + if res.resname != ligand_residue: + if _is_it_a_residue(res) or res.id[0] == " ": + continue + else: + structure[0][chain].detach_child(res.id) + + return structure + + @staticmethod + def _parse_chains(chains): + """ + Parse the chain and return a list of lists. + + The chains specification requires one chain per interactor. The first + argument following the -c flag is the specfication for the protein + selection and more than one chain ids can be specified by comma separating + them. The second command line argument following -c corresponds to the + ligand specification and requires one chain id followed by the reside + identifier of the ligand (e.g. -c A B:LIG). The parsed chains are returned + as a list. + """ + parsed_chains = [] + flattened_chains_string = "".join(chains) + protein_chain_string, ligand_chain_string = [_.upper() for _ in chains] + + try: + flattened_chains_string.encode("ascii") + except UnicodeDecodeError: + raise RuntimeError("Please use uppercase ASCII characters [ A-Z ].") + + for char in protein_chain_string: + if not char.isalpha() and char != ",": + raise RuntimeError( + "Use uppercase ASCII characters [ A-Z ] to specify the" + " chains and , to separate them." + ) + + # Make sure that "A," or "A,B," didn't slip through + comma_count = protein_chain_string.count(",") + + if 2 * comma_count + 1 != len(protein_chain_string): + raise RuntimeError( + "Specify multiple chains like this: prodigy_lig.py -c A,B C" + ) + + parsed_chains.append(protein_chain_string.split(",")) + + ligand_specification = ( + "Use uppercase ASCII characters [ A-Z ] to speciy the " + "chain and ligand identifiers. Separate the ligand " + "identifier from its chain by colon. prodigy_lig.py " + "-c A B:LIG" + ) + if len(ligand_chain_string) != 5: + raise RuntimeError(ligand_specification) + + for char in ligand_chain_string: + if not char.isalnum() and char != ":": + raise RuntimeError(ligand_specification) + + if ligand_chain_string.count(":") != 1: + raise RuntimeError(ligand_specification) + + chain, ligand = ligand_chain_string.split(":") + if len(chain) != 1: + raise RuntimeError(ligand_specification) + + if len(ligand) != 3: + raise RuntimeError(ligand_specification) + + parsed_chains.append(ligand_chain_string.split(":")) + + return parsed_chains + + def print_contacts(self, outfile=""): + """Print the atomic contacts to STDOUT or the specified handle.""" + if outfile: + handle = open(outfile, "w") + else: + handle = sys.stdout + + for line in self.atomic_contacts: + handle.write("{}\n".format(line)) + + if handle is not sys.stdout: + handle.close() + + def print_prediction(self, outfile="", verbose=False): + """Print to the File or STDOUT if no filename is specified.""" + if outfile: + handle = open(outfile, "w") + else: + handle = sys.stdout + if self.electrostatics is not None: + header = ["Job name", "DGprediction (Kcal/mol)", "DGscore"] + values = [self.structure.id, self.dg_elec, self.dg_score] + if verbose: + header.append("Electrostatics Energy") + values.append(self.electrostatics) + for key, value in sorted(self.contact_counts.items()): + header.append(key) + values.append(value) + handle.write("\t".join(header) + "\n") + handle.write( + ("{}" + "\t{:.2f}" * 3 + "\t{:4d}" * 10 + "\n").format(*values) + ) + else: + handle.write("\t".join(header) + "\n") + handle.write("{}\t{:.2f}\t{:.2f}\n".format(*values)) + else: + header = ["Job name", "DGprediction (low refinement) (Kcal/mol)"] + values = [self.structure.id, self.dg] + if verbose: + for key, value in sorted(self.contact_counts.items()): + header.append(key) + values.append(value) + handle.write("\t".join(header) + "\n") + handle.write(("{}\t{:.2f}" + "\t{:4d}" * 10 + "\n").format(*values)) + else: + handle.write("\t".join(header) + "\n") + handle.write("{}\t{:.2f}\n".format(*values)) + if handle is not sys.stdout: + handle.close() + + def print_structure(self, outfile=""): + """Store the processed structure in a file.""" + io = PDBIO() + io.set_structure(self.structure) + io.save(outfile) + + +def extract_electrostatics(pdb_file): + """ + Extracts the electrostatics energy from a HADDOCK PDB file. + + :param pdb_file: The input PDB file. + :return: Electrostatics energy + """ + electrostatics = None + for line in pdb_file: + # scan for Haddock energies line and assign electrostatics + if line.startswith("REMARK energies"): + line = line.rstrip() + line = line.replace("REMARK energies: ", "") + electrostatics = float(line.split(",")[6]) + break + # stop on first ATOM Line as remarks should be beforehand + elif line.startswith("ATOM"): + break + # try to reset file handle for further processing + try: + pdb_file.seek(0) + except Exception: + pass + return electrostatics + + +def calc_atomic_contacts(structure, chains, cutoff=10.5): + """ + Calculate the contacts without calling out to the CPP code. + + :param structure: Biopython structure object of the input file + :param chains: the interactor selection as array (e.g [ ['A', 'B'], ['A','LIG'] ]) + :param cutoff: the distance cutoff to determine interactions in Angstrom + :return: List of contacts + """ + contacts = [] + structure = structure[0] + prot_chains = {_ for _ in chains[0] + list(chains[1][0])} + lig_chain, lig_res = chains[1] + + for lig_atom in structure[lig_chain].get_atoms(): + if lig_atom.parent.resname == lig_res: + for prot_chain in prot_chains: + for prot_atom in structure[prot_chain].get_atoms(): + if prot_atom.parent.resname != lig_atom.parent.resname: + dist = lig_atom - prot_atom + if dist <= cutoff: + contacts.append( + "\t".join( + [ + prot_atom.parent.resname, + prot_atom.parent.parent.id, + str(prot_atom.parent.id[1]), + prot_atom.element, + lig_atom.parent.resname, + lig_atom.parent.parent.id, + str(lig_atom.parent.id[1]), + lig_atom.element, + str(dist), + ] + ) + ) + + return contacts + + +def calculate_contact_counts(contacts): + """ + Calculate the counts of the various atomic contact types based on the + types of atoms that are in contact. The categories are: + CC: Carbon-Carbon + NN: Nitrogen-Nitrogen + OO: Oxygen-Oxygen + XX: Other-Other + and the combinations: CN, CO, CX, NO, NX, OX + + :param contacts: The output of the calc_atomic_contacts functions + :return: dict of the counts of each category defined above + """ + + def _classify_atom(atom): + """ + Classify the atom involved in the interaction in one of the categories + laid out in calculate_atomic_contacts. + + :param atom: The atom involved in the interaction + :return: Atom type. One of C, N, O, X + """ + if atom == "C" or atom == "N" or atom == "O": + return atom + else: + return "X" + + def _classify_contact(atom_classes): + """ + Classify the contact in one of the categories defined in the function + calculate_atomic_contact_counts. + + :param atom_classes: Class of the atoms involved in the interaction + :type atom_classes: List of length 2 + :return: One of CC, NN, OO, XX, CN, CO, CX, NO, NX, OX + """ + atom_1, atom_2 = atom_classes + if atom_1 == "C" and atom_2 == "C": + return "CC" + elif (atom_1 == "C" and atom_2 == "N") or (atom_1 == "N" and atom_2 == "C"): + return "CN" + elif (atom_1 == "C" and atom_2 == "O") or (atom_1 == "O" and atom_2 == "C"): + return "CO" + elif (atom_1 == "C" and atom_2 == "X") or (atom_1 == "X" and atom_2 == "C"): + return "CX" + elif (atom_1 == "N" and atom_2 == "N") or (atom_1 == "N" and atom_2 == "N"): + return "NN" + elif (atom_1 == "N" and atom_2 == "O") or (atom_1 == "O" and atom_2 == "N"): + return "NO" + elif (atom_1 == "N" and atom_2 == "X") or (atom_1 == "X" and atom_2 == "N"): + return "NX" + elif (atom_1 == "O" and atom_2 == "O") or (atom_1 == "O" and atom_2 == "O"): + return "OO" + elif (atom_1 == "O" and atom_2 == "X") or (atom_1 == "X" and atom_2 == "O"): + return "OX" + elif (atom_1 == "X" and atom_2 == "X") or (atom_1 == "X" and atom_2 == "X"): + return "XX" + else: + return None + + counts = { + "CC": 0, + "NN": 0, + "OO": 0, + "XX": 0, + "CN": 0, + "CO": 0, + "CX": 0, + "NO": 0, + "NX": 0, + "OX": 0, + } + + allowed_atoms = {"C", "N", "O", "F", "CL", "BR", "S", "P"} + + for line in contacts: + if len(line) == 0: + continue + words = line.split() + + atom_name_1 = words[3] + atom_name_2 = words[7] + + if not (atom_name_1 in allowed_atoms and atom_name_2 in allowed_atoms): + continue + + atom_class_1 = _classify_atom(atom_name_1) + atom_class_2 = _classify_atom(atom_name_2) + + contact_class = _classify_contact([atom_class_1, atom_class_2]) + counts[contact_class] += 1 + + return counts + + +def calculate_score(contact_counts, electrostatics_energy): + """ + Calculates the PRODIGY-lig score based on the contact counts and the + electrostatics energy. + + :param contact_counts: Counts of the CC, NN, OO, XX contacts + :type contact_counts: dict + :param electrostatics_energy: Electrostatics energy calculated by HADDOCK + :type electrostatics_energy: float + :return: The PRODIGY-lig score + """ + elec_weight = 0.343794 + cc_weight = -0.037597 + nn_weight = 0.138738 + oo_weight = 0.160043 + xx_weight = -3.088861 + intercept = 187.011384 + + return ( + (elec_weight * electrostatics_energy) + + (cc_weight * contact_counts["CC"]) + + (nn_weight * contact_counts["NN"]) + + (oo_weight * contact_counts["OO"]) + + (xx_weight * contact_counts["XX"]) + + intercept + ) + + +def calculate_DG(contact_counts): + """ + Calculates the PRODIGY-lig binding affinity using the weigths that + have been trained for the prediction without electrostatics. + """ + nn_weight = 0.0354707 + xx_weight = -0.1277895 + cn_weight = -0.0072166 + intercept = -5.1923181 + + return ( + (nn_weight * contact_counts["NN"]) + + (xx_weight * contact_counts["XX"]) + + (cn_weight * contact_counts["CN"]) + + intercept + ) + + +def calculate_DG_electrostatics(contact_counts, electrostatics_energy): + """ + Calculates the PRODIGY-lig binding affinity using the weights that + have been optimised for the prediction with electrostatics. + """ + elec_weight = 0.0115148 + cc_weight = -0.0014852 + nn_weight = 0.0057097 + xx_weight = -0.1301806 + intercept = -5.1002233 + + return ( + (elec_weight * electrostatics_energy) + + (cc_weight * contact_counts["CC"]) + + (nn_weight * contact_counts["NN"]) + + (xx_weight * contact_counts["XX"]) + + intercept + ) + + +def _parse_arguments(): + """Parse the command line arguments.""" + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Authors: Panagiotis Koukos, Anna Vangone, Joerg Schaarschmidt", + ) + + parser.add_argument( + "-c", + "--chains", + required=True, + nargs=2, + help=( + "Which chains to use. Expects two sets of arguments. The first " + "set refers to the protein selection and multiple chains can be" + " specified by separating the chain identifiers with commas. The" + " second set refers to the ligand and requires one chain and the" + " residue identifier of the ligand. A typical use case could be " + "the following: prodigy_lig.py -c A,B A:LIG" + ), + ) + parser.add_argument( + "-i", + "--input_file", + required=True, + help="This is the PDB/mmcif file for which the score will be calculated.", + ) + parser.add_argument( + "-e", + "--electrostatics", + required=False, + type=float, + help="This is the electrostatics energy as calculated during the" + " water refinement stage of HADDOCK.", + ) + parser.add_argument( + "-d", + "--distance_cutoff", + required=False, + default=10.5, + type=float, + help="This is the distance cutoff for the Atomic Contacts " " (def = 10.5Å).", + ) + parser.add_argument( + "-o", + "--output_file", + default=None, + action="store_true", + required=False, + help="Store the processed file. The filename will be the name " + "of the input with -processed appended just before the " + "file ending.", + ) + parser.add_argument( + "-v", + "--verbose", + default=False, + action="store_true", + required=False, + help="Include the calculated contact counts in the output.", + ) + + return parser.parse_args() + + +def main(): + """Run it.""" + args = _parse_arguments() + fname, s_ext = splitext(basename(args.input_file)) + parser = None + if s_ext in {".pdb", ".ent"}: + parser = PDBParser(QUIET=1) + elif s_ext == ".cif": + parser = FastMMCIFParser(QUIET=1) + + with open(args.input_file) as in_file: + # try to set electrostatics from input file if not provided by user + electrostatics = ( + args.electrostatics + if args.electrostatics or s_ext == ".cif" + else extract_electrostatics(in_file) + ) + prodigy_lig = ProdigyLig( + parser.get_structure(fname, in_file), + chains=args.chains, + electrostatics=electrostatics, + cutoff=args.distance_cutoff, + ) + + prodigy_lig.predict() + prodigy_lig.print_prediction("", args.verbose) + + if args.output_file is not None: + output_file_name = splitext(prodigy_lig.structure.id)[0] + output_file_name += "-processed.pdb" + prodigy_lig.print_structure(output_file_name) + + +if __name__ == "__main__": + main() diff --git a/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e65815cf0b3132689485874a93034ede7206bf4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/LICENSE @@ -0,0 +1,54 @@ +Copyright 2017- Paul Ganssle +Copyright 2017- dateutil contributors (see AUTHORS file) + + Licensed 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. + +The above license applies to all contributions after 2017-12-01, as well as +all contributions that have been re-licensed (see AUTHORS file for the list of +contributors who have re-licensed their code). +-------------------------------------------------------------------------------- +dateutil - Extensions to the standard Python datetime module. + +Copyright (c) 2003-2011 - Gustavo Niemeyer +Copyright (c) 2012-2014 - Tomi Pieviläinen +Copyright (c) 2014-2016 - Yaron de Leeuw +Copyright (c) 2015- - Paul Ganssle +Copyright (c) 2015- - dateutil contributors (see AUTHORS file) + +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 copyright holder 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. + +The above BSD License Applies to all code, even that also covered by Apache 2.0. \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..577f2bf2b7749e1b123b8225d610b1b257e430cc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/METADATA @@ -0,0 +1,204 @@ +Metadata-Version: 2.1 +Name: python-dateutil +Version: 2.9.0.post0 +Summary: Extensions to the standard Python datetime module +Home-page: https://github.com/dateutil/dateutil +Author: Gustavo Niemeyer +Author-email: gustavo@niemeyer.net +Maintainer: Paul Ganssle +Maintainer-email: dateutil@python.org +License: Dual License +Project-URL: Documentation, https://dateutil.readthedocs.io/en/stable/ +Project-URL: Source, https://github.com/dateutil/dateutil +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +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 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development :: Libraries +Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,>=2.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: six >=1.5 + +dateutil - powerful extensions to datetime +========================================== + +|pypi| |support| |licence| + +|gitter| |readthedocs| + +|travis| |appveyor| |pipelines| |coverage| + +.. |pypi| image:: https://img.shields.io/pypi/v/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: pypi version + +.. |support| image:: https://img.shields.io/pypi/pyversions/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: supported Python version + +.. |travis| image:: https://img.shields.io/travis/dateutil/dateutil/master.svg?style=flat-square&label=Travis%20Build + :target: https://travis-ci.org/dateutil/dateutil + :alt: travis build status + +.. |appveyor| image:: https://img.shields.io/appveyor/ci/dateutil/dateutil/master.svg?style=flat-square&logo=appveyor + :target: https://ci.appveyor.com/project/dateutil/dateutil + :alt: appveyor build status + +.. |pipelines| image:: https://dev.azure.com/pythondateutilazure/dateutil/_apis/build/status/dateutil.dateutil?branchName=master + :target: https://dev.azure.com/pythondateutilazure/dateutil/_build/latest?definitionId=1&branchName=master + :alt: azure pipelines build status + +.. |coverage| image:: https://codecov.io/gh/dateutil/dateutil/branch/master/graphs/badge.svg?branch=master + :target: https://codecov.io/gh/dateutil/dateutil?branch=master + :alt: Code coverage + +.. |gitter| image:: https://badges.gitter.im/dateutil/dateutil.svg + :alt: Join the chat at https://gitter.im/dateutil/dateutil + :target: https://gitter.im/dateutil/dateutil + +.. |licence| image:: https://img.shields.io/pypi/l/python-dateutil.svg?style=flat-square + :target: https://pypi.org/project/python-dateutil/ + :alt: licence + +.. |readthedocs| image:: https://img.shields.io/readthedocs/dateutil/latest.svg?style=flat-square&label=Read%20the%20Docs + :alt: Read the documentation at https://dateutil.readthedocs.io/en/latest/ + :target: https://dateutil.readthedocs.io/en/latest/ + +The `dateutil` module provides powerful extensions to +the standard `datetime` module, available in Python. + +Installation +============ +`dateutil` can be installed from PyPI using `pip` (note that the package name is +different from the importable name):: + + pip install python-dateutil + +Download +======== +dateutil is available on PyPI +https://pypi.org/project/python-dateutil/ + +The documentation is hosted at: +https://dateutil.readthedocs.io/en/stable/ + +Code +==== +The code and issue tracker are hosted on GitHub: +https://github.com/dateutil/dateutil/ + +Features +======== + +* Computing of relative deltas (next month, next year, + next Monday, last week of month, etc); +* Computing of relative deltas between two given + date and/or datetime objects; +* Computing of dates based on very flexible recurrence rules, + using a superset of the `iCalendar `_ + specification. Parsing of RFC strings is supported as well. +* Generic parsing of dates in almost any string format; +* Timezone (tzinfo) implementations for tzfile(5) format + files (/etc/localtime, /usr/share/zoneinfo, etc), TZ + environment string (in all known formats), iCalendar + format files, given ranges (with help from relative deltas), + local machine timezone, fixed offset timezone, UTC timezone, + and Windows registry-based time zones. +* Internal up-to-date world timezone information based on + Olson's database. +* Computing of Easter Sunday dates for any given year, + using Western, Orthodox or Julian algorithms; +* A comprehensive test suite. + +Quick example +============= +Here's a snapshot, just to give an idea about the power of the +package. For more examples, look at the documentation. + +Suppose you want to know how much time is left, in +years/months/days/etc, before the next easter happening on a +year with a Friday 13th in August, and you want to get today's +date out of the "date" unix system command. Here is the code: + +.. code-block:: python3 + + >>> from dateutil.relativedelta import * + >>> from dateutil.easter import * + >>> from dateutil.rrule import * + >>> from dateutil.parser import * + >>> from datetime import * + >>> now = parse("Sat Oct 11 17:13:46 UTC 2003") + >>> today = now.date() + >>> year = rrule(YEARLY,dtstart=now,bymonth=8,bymonthday=13,byweekday=FR)[0].year + >>> rdelta = relativedelta(easter(year), today) + >>> print("Today is: %s" % today) + Today is: 2003-10-11 + >>> print("Year with next Aug 13th on a Friday is: %s" % year) + Year with next Aug 13th on a Friday is: 2004 + >>> print("How far is the Easter of that year: %s" % rdelta) + How far is the Easter of that year: relativedelta(months=+6) + >>> print("And the Easter of that year is: %s" % (today+rdelta)) + And the Easter of that year is: 2004-04-11 + +Being exactly 6 months ahead was **really** a coincidence :) + +Contributing +============ + +We welcome many types of contributions - bug reports, pull requests (code, infrastructure or documentation fixes). For more information about how to contribute to the project, see the ``CONTRIBUTING.md`` file in the repository. + + +Author +====== +The dateutil module was written by Gustavo Niemeyer +in 2003. + +It is maintained by: + +* Gustavo Niemeyer 2003-2011 +* Tomi Pieviläinen 2012-2014 +* Yaron de Leeuw 2014-2016 +* Paul Ganssle 2015- + +Starting with version 2.4.1 and running until 2.8.2, all source and binary +distributions will be signed by a PGP key that has, at the very least, been +signed by the key which made the previous release. A table of release signing +keys can be found below: + +=========== ============================ +Releases Signing key fingerprint +=========== ============================ +2.4.1-2.8.2 `6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB`_ +=========== ============================ + +New releases *may* have signed tags, but binary and source distributions +uploaded to PyPI will no longer have GPG signatures attached. + +Contact +======= +Our mailing list is available at `dateutil@python.org `_. As it is hosted by the PSF, it is subject to the `PSF code of +conduct `_. + +License +======= + +All contributions after December 1, 2017 released under dual license - either `Apache 2.0 License `_ or the `BSD 3-Clause License `_. Contributions before December 1, 2017 - except those those explicitly relicensed - are released only under the BSD 3-Clause License. + + +.. _6B49 ACBA DCF6 BD1C A206 67AB CD54 FCE3 D964 BEFB: + https://pgp.mit.edu/pks/lookup?op=vindex&search=0xCD54FCE3D964BEFB diff --git a/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8abf769beb56ed307111268106e19c87137b23df --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/RECORD @@ -0,0 +1,44 @@ +dateutil/__init__.py,sha256=Mqam67WO9IkTmUFyI66vS6IoSXTp9G388DadH2LCMLY,620 +dateutil/__pycache__/__init__.cpython-312.pyc,, +dateutil/__pycache__/_common.cpython-312.pyc,, +dateutil/__pycache__/_version.cpython-312.pyc,, +dateutil/__pycache__/easter.cpython-312.pyc,, +dateutil/__pycache__/relativedelta.cpython-312.pyc,, +dateutil/__pycache__/rrule.cpython-312.pyc,, +dateutil/__pycache__/tzwin.cpython-312.pyc,, +dateutil/__pycache__/utils.cpython-312.pyc,, +dateutil/_common.py,sha256=77w0yytkrxlYbSn--lDVPUMabUXRR9I3lBv_vQRUqUY,932 +dateutil/_version.py,sha256=BV031OxDDAmy58neUg5yyqLkLaqIw7ibK9As3jiMib0,166 +dateutil/easter.py,sha256=dyBi-lKvimH1u_k6p7Z0JJK72QhqVtVBsqByvpEPKvc,2678 +dateutil/parser/__init__.py,sha256=wWk6GFuxTpjoggCGtgkceJoti4pVjl4_fHQXpNOaSYg,1766 +dateutil/parser/__pycache__/__init__.cpython-312.pyc,, +dateutil/parser/__pycache__/_parser.cpython-312.pyc,, +dateutil/parser/__pycache__/isoparser.cpython-312.pyc,, +dateutil/parser/_parser.py,sha256=7klDdyicksQB_Xgl-3UAmBwzCYor1AIZqklIcT6dH_8,58796 +dateutil/parser/isoparser.py,sha256=8Fy999bnCd1frSdOYuOraWfJTtd5W7qQ51NwNuH_hXM,13233 +dateutil/relativedelta.py,sha256=IY_mglMjoZbYfrvloTY2ce02aiVjPIkiZfqgNTZRfuA,24903 +dateutil/rrule.py,sha256=KJzKlaCd1jEbu4A38ZltslaoAUh9nSbdbOFdjp70Kew,66557 +dateutil/tz/__init__.py,sha256=F-Mz13v6jYseklQf9Te9J6nzcLDmq47gORa61K35_FA,444 +dateutil/tz/__pycache__/__init__.cpython-312.pyc,, +dateutil/tz/__pycache__/_common.cpython-312.pyc,, +dateutil/tz/__pycache__/_factories.cpython-312.pyc,, +dateutil/tz/__pycache__/tz.cpython-312.pyc,, +dateutil/tz/__pycache__/win.cpython-312.pyc,, +dateutil/tz/_common.py,sha256=cgzDTANsOXvEc86cYF77EsliuSab8Puwpsl5-bX3_S4,12977 +dateutil/tz/_factories.py,sha256=unb6XQNXrPMveksTCU-Ag8jmVZs4SojoPUcAHpWnrvU,2569 +dateutil/tz/tz.py,sha256=EUnEdMfeThXiY6l4sh9yBabZ63_POzy01zSsh9thn1o,62855 +dateutil/tz/win.py,sha256=xJszWgSwE1xPx_HJj4ZkepyukC_hNy016WMcXhbRaB8,12935 +dateutil/tzwin.py,sha256=7Ar4vdQCnnM0mKR3MUjbIKsZrBVfHgdwsJZc_mGYRew,59 +dateutil/utils.py,sha256=dKCchEw8eObi0loGTx91unBxm_7UGlU3v_FjFMdqwYM,1965 +dateutil/zoneinfo/__init__.py,sha256=KYg0pthCMjcp5MXSEiBJn3nMjZeNZav7rlJw5-tz1S4,5889 +dateutil/zoneinfo/__pycache__/__init__.cpython-312.pyc,, +dateutil/zoneinfo/__pycache__/rebuild.cpython-312.pyc,, +dateutil/zoneinfo/dateutil-zoneinfo.tar.gz,sha256=0-pS57bpaN4NiE3xKIGTWW-pW4A9tPkqGCeac5gARHU,156400 +dateutil/zoneinfo/rebuild.py,sha256=MiqYzCIHvNbMH-LdRYLv-4T0EIA7hDKt5GLR0IRTLdI,2392 +python_dateutil-2.9.0.post0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +python_dateutil-2.9.0.post0.dist-info/LICENSE,sha256=ugD1Gg2SgjtaHN4n2LW50jIeZ-2NqbwWPv-W1eF-V34,2889 +python_dateutil-2.9.0.post0.dist-info/METADATA,sha256=qdQ22jIr6AgzL5jYgyWZjofLaTpniplp_rTPrXKabpM,8354 +python_dateutil-2.9.0.post0.dist-info/RECORD,, +python_dateutil-2.9.0.post0.dist-info/WHEEL,sha256=-G_t0oGuE7UD0DrSpVZnq1hHMBV9DD2XkS5v7XpmTnk,110 +python_dateutil-2.9.0.post0.dist-info/top_level.txt,sha256=4tjdWkhRZvF7LA_BYe_L9gB2w_p2a-z5y6ArjaRkot8,9 +python_dateutil-2.9.0.post0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 diff --git a/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4724c45738f6ac125bb3a21787855562e6870440 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66501480ba5b63f98ee9a59c1f99e5e6917da6d9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/top_level.txt @@ -0,0 +1 @@ +dateutil diff --git a/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/python_dateutil-2.9.0.post0.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/LICENSE.txt b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f1c11289f6a54cb07ebdbf31d02e8e81b18b07f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2003-2019 Stuart Bishop + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9b1bad2b30b972f27cd5055763c2583a3fd074d4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/METADATA @@ -0,0 +1,648 @@ +Metadata-Version: 2.1 +Name: pytz +Version: 2026.1.post1 +Summary: World timezone definitions, modern and historical +Home-page: http://pythonhosted.org/pytz +Download-URL: https://pypi.org/project/pytz/ +Author: Stuart Bishop +Author-email: stuart@stuartbishop.net +Maintainer: Stuart Bishop +Maintainer-email: stuart@stuartbishop.net +License: MIT +Keywords: timezone,tzinfo,datetime,olson,time +Platform: Independent +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.4 +Classifier: Programming Language :: Python :: 2.5 +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.1 +Classifier: Programming Language :: Python :: 3.2 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +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 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +License-File: LICENSE.txt + +pytz - World Timezone Definitions for Python +============================================ + +:Author: Stuart Bishop + +Introduction +~~~~~~~~~~~~ + +pytz brings the Olson tz database into Python. This library allows +accurate and cross platform timezone calculations using Python 2.4 +or higher. It also solves the issue of ambiguous times at the end +of daylight saving time, which you can read more about in the Python +Library Reference (``datetime.tzinfo``). + +Almost all of the Olson timezones are supported. + +.. note:: + + Projects using Python 3.9 or later should be using the support + now included as part of the standard library, and third party + packages work with it such as `tzdata `_. + pytz offers no advantages beyond backwards compatibility with + code written for earlier versions of Python. + +.. note:: + + This library differs from the documented Python API for + tzinfo implementations; if you want to create local wallclock + times you need to use the ``localize()`` method documented in this + document. In addition, if you perform date arithmetic on local + times that cross DST boundaries, the result may be in an incorrect + timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get + 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A + ``normalize()`` method is provided to correct this. Unfortunately these + issues cannot be resolved without modifying the Python datetime + implementation (see PEP-431). + + +Installation +~~~~~~~~~~~~ + +This package can either be installed using ``pip`` or from a tarball using the +standard Python distutils. + +If you are installing using ``pip``, you don't need to download anything as the +latest version will be downloaded for you from PyPI:: + + pip install pytz + +If you are installing from a tarball, run the following command as an +administrative user:: + + python setup.py install + + +pytz for Enterprise +~~~~~~~~~~~~~~~~~~~ + +Available as part of the Tidelift Subscription. + +The maintainers of pytz and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. `Learn more. `_. + + +Example & Usage +~~~~~~~~~~~~~~~ + +Localized times and date arithmetic +----------------------------------- + +>>> from datetime import datetime, timedelta +>>> from pytz import timezone +>>> import pytz +>>> utc = pytz.utc +>>> utc.zone +'UTC' +>>> eastern = timezone('US/Eastern') +>>> eastern.zone +'US/Eastern' +>>> amsterdam = timezone('Europe/Amsterdam') +>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z' + +This library only supports two ways of building a localized time. The +first is to use the ``localize()`` method provided by the pytz library. +This is used to localize a naive datetime (datetime with no timezone +information): + +>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0)) +>>> print(loc_dt.strftime(fmt)) +2002-10-27 06:00:00 EST-0500 + +The second way of building a localized time is by converting an existing +localized time using the standard ``astimezone()`` method: + +>>> ams_dt = loc_dt.astimezone(amsterdam) +>>> ams_dt.strftime(fmt) +'2002-10-27 12:00:00 CET+0100' + +Unfortunately using the tzinfo argument of the standard datetime +constructors ''does not work'' with pytz for many timezones. + +>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt) # /!\ Does not work this way! +'2002-10-27 12:00:00 LMT+0018' + +It is safe for timezones without daylight saving transitions though, such +as UTC: + +>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt) # /!\ Not recommended except for UTC +'2002-10-27 12:00:00 UTC+0000' + +The preferred way of dealing with times is to always work in UTC, +converting to localtime only when generating output to be read +by humans. + +>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) +>>> loc_dt = utc_dt.astimezone(eastern) +>>> loc_dt.strftime(fmt) +'2002-10-27 01:00:00 EST-0500' + +This library also allows you to do date arithmetic using local +times, although it is more complicated than working in UTC as you +need to use the ``normalize()`` method to handle daylight saving time +and other timezone transitions. In this example, ``loc_dt`` is set +to the instant when daylight saving time ends in the US/Eastern +timezone. + +>>> before = loc_dt - timedelta(minutes=10) +>>> before.strftime(fmt) +'2002-10-27 00:50:00 EST-0500' +>>> eastern.normalize(before).strftime(fmt) +'2002-10-27 01:50:00 EDT-0400' +>>> after = eastern.normalize(before + timedelta(minutes=20)) +>>> after.strftime(fmt) +'2002-10-27 01:10:00 EST-0500' + +Creating local times is also tricky, and the reason why working with +local times is not recommended. Unfortunately, you cannot just pass +a ``tzinfo`` argument when constructing a datetime (see the next +section for more details) + +>>> dt = datetime(2002, 10, 27, 1, 30, 0) +>>> dt1 = eastern.localize(dt, is_dst=True) +>>> dt1.strftime(fmt) +'2002-10-27 01:30:00 EDT-0400' +>>> dt2 = eastern.localize(dt, is_dst=False) +>>> dt2.strftime(fmt) +'2002-10-27 01:30:00 EST-0500' + +Converting between timezones is more easily done, using the +standard astimezone method. + +>>> utc_dt = datetime.fromtimestamp(1143408899, tz=utc) +>>> utc_dt.strftime(fmt) +'2006-03-26 21:34:59 UTC+0000' +>>> au_tz = timezone('Australia/Sydney') +>>> au_dt = utc_dt.astimezone(au_tz) +>>> au_dt.strftime(fmt) +'2006-03-27 08:34:59 AEDT+1100' +>>> utc_dt2 = au_dt.astimezone(utc) +>>> utc_dt2.strftime(fmt) +'2006-03-26 21:34:59 UTC+0000' +>>> utc_dt == utc_dt2 +True + +You can take shortcuts when dealing with the UTC side of timezone +conversions. ``normalize()`` and ``localize()`` are not really +necessary when there are no daylight saving time transitions to +deal with. + +>>> utc_dt = datetime.fromtimestamp(1143408899, tz=utc) +>>> utc_dt.strftime(fmt) +'2006-03-26 21:34:59 UTC+0000' +>>> au_tz = timezone('Australia/Sydney') +>>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz)) +>>> au_dt.strftime(fmt) +'2006-03-27 08:34:59 AEDT+1100' +>>> utc_dt2 = au_dt.astimezone(utc) +>>> utc_dt2.strftime(fmt) +'2006-03-26 21:34:59 UTC+0000' + + +``tzinfo`` API +-------------- + +The ``tzinfo`` instances returned by the ``timezone()`` function have +been extended to cope with ambiguous times by adding an ``is_dst`` +parameter to the ``utcoffset()``, ``dst()`` && ``tzname()`` methods. + +>>> tz = timezone('America/St_Johns') + +>>> normal = datetime(2009, 9, 1) +>>> ambiguous = datetime(2009, 10, 31, 23, 30) + +The ``is_dst`` parameter is ignored for most timestamps. It is only used +during DST transition ambiguous periods to resolve that ambiguity. + +>>> print(tz.utcoffset(normal, is_dst=True)) +-1 day, 21:30:00 +>>> print(tz.dst(normal, is_dst=True)) +1:00:00 +>>> tz.tzname(normal, is_dst=True) +'NDT' + +>>> print(tz.utcoffset(ambiguous, is_dst=True)) +-1 day, 21:30:00 +>>> print(tz.dst(ambiguous, is_dst=True)) +1:00:00 +>>> tz.tzname(ambiguous, is_dst=True) +'NDT' + +>>> print(tz.utcoffset(normal, is_dst=False)) +-1 day, 21:30:00 +>>> tz.dst(normal, is_dst=False).seconds +3600 +>>> tz.tzname(normal, is_dst=False) +'NDT' + +>>> print(tz.utcoffset(ambiguous, is_dst=False)) +-1 day, 20:30:00 +>>> tz.dst(ambiguous, is_dst=False) +datetime.timedelta(0) +>>> tz.tzname(ambiguous, is_dst=False) +'NST' + +If ``is_dst`` is not specified, ambiguous timestamps will raise +an ``pytz.exceptions.AmbiguousTimeError`` exception. + +>>> print(tz.utcoffset(normal)) +-1 day, 21:30:00 +>>> print(tz.dst(normal)) +1:00:00 +>>> tz.tzname(normal) +'NDT' + +>>> import pytz.exceptions +>>> try: +... tz.utcoffset(ambiguous) +... except pytz.exceptions.AmbiguousTimeError: +... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous) +pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00 +>>> try: +... tz.dst(ambiguous) +... except pytz.exceptions.AmbiguousTimeError: +... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous) +pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00 +>>> try: +... tz.tzname(ambiguous) +... except pytz.exceptions.AmbiguousTimeError: +... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous) +pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00 + + +Problems with Localtime +~~~~~~~~~~~~~~~~~~~~~~~ + +The major problem we have to deal with is that certain datetimes +may occur twice in a year. For example, in the US/Eastern timezone +on the last Sunday morning in October, the following sequence +happens: + + - 01:00 EDT occurs + - 1 hour later, instead of 2:00am the clock is turned back 1 hour + and 01:00 happens again (this time 01:00 EST) + +In fact, every instant between 01:00 and 02:00 occurs twice. This means +that if you try and create a time in the 'US/Eastern' timezone +the standard datetime syntax, there is no way to specify if you meant +before of after the end-of-daylight-saving-time transition. Using the +pytz custom syntax, the best you can do is make an educated guess: + +>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 1, 30, 00)) +>>> loc_dt.strftime(fmt) +'2002-10-27 01:30:00 EST-0500' + +As you can see, the system has chosen one for you and there is a 50% +chance of it being out by one hour. For some applications, this does +not matter. However, if you are trying to schedule meetings with people +in different timezones or analyze log files it is not acceptable. + +The best and simplest solution is to stick with using UTC. The pytz +package encourages using UTC for internal timezone representation by +including a special UTC implementation based on the standard Python +reference implementation in the Python documentation. + +The UTC timezone unpickles to be the same instance, and pickles to a +smaller size than other pytz tzinfo instances. The UTC implementation +can be obtained as pytz.utc, pytz.UTC, or pytz.timezone('UTC'). + +>>> import pickle, pytz +>>> dt = datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc) +>>> naive = dt.replace(tzinfo=None) +>>> p = pickle.dumps(dt, 1) +>>> naive_p = pickle.dumps(naive, 1) +>>> len(p) - len(naive_p) +17 +>>> new = pickle.loads(p) +>>> new == dt +True +>>> new is dt +False +>>> new.tzinfo is dt.tzinfo +True +>>> pytz.utc is pytz.UTC is pytz.timezone('UTC') +True + +Note that some other timezones are commonly thought of as the same (GMT, +Greenwich, Universal, etc.). The definition of UTC is distinct from these +other timezones, and they are not equivalent. For this reason, they will +not compare the same in Python. + +>>> utc == pytz.timezone('GMT') +False + +See the section `What is UTC`_, below. + +If you insist on working with local times, this library provides a +facility for constructing them unambiguously: + +>>> loc_dt = datetime(2002, 10, 27, 1, 30, 00) +>>> est_dt = eastern.localize(loc_dt, is_dst=True) +>>> edt_dt = eastern.localize(loc_dt, is_dst=False) +>>> print(est_dt.strftime(fmt) + ' / ' + edt_dt.strftime(fmt)) +2002-10-27 01:30:00 EDT-0400 / 2002-10-27 01:30:00 EST-0500 + +If you pass None as the is_dst flag to localize(), pytz will refuse to +guess and raise exceptions if you try to build ambiguous or non-existent +times. + +For example, 1:30am on 27th Oct 2002 happened twice in the US/Eastern +timezone when the clocks where put back at the end of Daylight Saving +Time: + +>>> dt = datetime(2002, 10, 27, 1, 30, 00) +>>> try: +... eastern.localize(dt, is_dst=None) +... except pytz.exceptions.AmbiguousTimeError: +... print('pytz.exceptions.AmbiguousTimeError: %s' % dt) +pytz.exceptions.AmbiguousTimeError: 2002-10-27 01:30:00 + +Similarly, 2:30am on 7th April 2002 never happened at all in the +US/Eastern timezone, as the clocks where put forward at 2:00am skipping +the entire hour: + +>>> dt = datetime(2002, 4, 7, 2, 30, 00) +>>> try: +... eastern.localize(dt, is_dst=None) +... except pytz.exceptions.NonExistentTimeError: +... print('pytz.exceptions.NonExistentTimeError: %s' % dt) +pytz.exceptions.NonExistentTimeError: 2002-04-07 02:30:00 + +Both of these exceptions share a common base class to make error handling +easier: + +>>> isinstance(pytz.AmbiguousTimeError(), pytz.InvalidTimeError) +True +>>> isinstance(pytz.NonExistentTimeError(), pytz.InvalidTimeError) +True + + +A special case is where countries change their timezone definitions +with no daylight savings time switch. For example, in 1915 Warsaw +switched from Warsaw time to Central European time with no daylight savings +transition. So at the stroke of midnight on August 5th 1915 the clocks +were wound back 24 minutes creating an ambiguous time period that cannot +be specified without referring to the timezone abbreviation or the +actual UTC offset. In this case midnight happened twice, neither time +during a daylight saving time period. pytz handles this transition by +treating the ambiguous period before the switch as daylight savings +time, and the ambiguous period after as standard time. + + +>>> warsaw = pytz.timezone('Europe/Warsaw') +>>> amb_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=True) +>>> amb_dt1.strftime(fmt) +'1915-08-04 23:59:59 WMT+0124' +>>> amb_dt2 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False) +>>> amb_dt2.strftime(fmt) +'1915-08-04 23:59:59 CET+0100' +>>> switch_dt = warsaw.localize(datetime(1915, 8, 5, 00, 00, 00), is_dst=False) +>>> switch_dt.strftime(fmt) +'1915-08-05 00:00:00 CET+0100' +>>> str(switch_dt - amb_dt1) +'0:24:01' +>>> str(switch_dt - amb_dt2) +'0:00:01' + +The best way of creating a time during an ambiguous time period is +by converting from another timezone such as UTC: + +>>> utc_dt = datetime(1915, 8, 4, 22, 36, tzinfo=pytz.utc) +>>> utc_dt.astimezone(warsaw).strftime(fmt) +'1915-08-04 23:36:00 CET+0100' + +The standard Python way of handling all these ambiguities is not to +handle them, such as demonstrated in this example using the US/Eastern +timezone definition from the Python documentation (Note that this +implementation only works for dates between 1987 and 2006 - it is +included for tests only!): + +>>> from pytz.reference import Eastern # pytz.reference only for tests +>>> dt = datetime(2002, 10, 27, 0, 30, tzinfo=Eastern) +>>> str(dt) +'2002-10-27 00:30:00-04:00' +>>> str(dt + timedelta(hours=1)) +'2002-10-27 01:30:00-05:00' +>>> str(dt + timedelta(hours=2)) +'2002-10-27 02:30:00-05:00' +>>> str(dt + timedelta(hours=3)) +'2002-10-27 03:30:00-05:00' + +Notice the first two results? At first glance you might think they are +correct, but taking the UTC offset into account you find that they are +actually two hours appart instead of the 1 hour we asked for. + +>>> from pytz.reference import UTC # pytz.reference only for tests +>>> str(dt.astimezone(UTC)) +'2002-10-27 04:30:00+00:00' +>>> str((dt + timedelta(hours=1)).astimezone(UTC)) +'2002-10-27 06:30:00+00:00' + + +Country Information +~~~~~~~~~~~~~~~~~~~ + +A mechanism is provided to access the timezones commonly in use +for a particular country, looked up using the ISO 3166 country code. +It returns a list of strings that can be used to retrieve the relevant +tzinfo instance using ``pytz.timezone()``: + +>>> print(' '.join(pytz.country_timezones['nz'])) +Pacific/Auckland Pacific/Chatham + +The Olson database comes with a ISO 3166 country code to English country +name mapping that pytz exposes as a dictionary: + +>>> print(pytz.country_names['nz']) +New Zealand + + +What is UTC +~~~~~~~~~~~ + +'UTC' is `Coordinated Universal Time`_. It is a successor to, but distinct +from, Greenwich Mean Time (GMT) and the various definitions of Universal +Time. UTC is now the worldwide standard for regulating clocks and time +measurement. + +All other timezones are defined relative to UTC, and include offsets like +UTC+0800 - hours to add or subtract from UTC to derive the local time. No +daylight saving time occurs in UTC, making it a useful timezone to perform +date arithmetic without worrying about the confusion and ambiguities caused +by daylight saving time transitions, your country changing its timezone, or +mobile computers that roam through multiple timezones. + +.. _Coordinated Universal Time: https://en.wikipedia.org/wiki/Coordinated_Universal_Time + + +Helpers +~~~~~~~ + +There are two lists of timezones provided. + +``all_timezones`` is the exhaustive list of the timezone names that can +be used. + +>>> from pytz import all_timezones +>>> len(all_timezones) >= 500 +True +>>> 'Etc/Greenwich' in all_timezones +True + +``common_timezones`` is a list of useful, current timezones. It doesn't +contain deprecated zones or historical zones, except for a few I've +deemed in common usage, such as US/Eastern (open a bug report if you +think other timezones are deserving of being included here). It is also +a sequence of strings. + +>>> from pytz import common_timezones +>>> len(common_timezones) < len(all_timezones) +True +>>> 'Etc/Greenwich' in common_timezones +False +>>> 'Australia/Melbourne' in common_timezones +True +>>> 'US/Eastern' in common_timezones +True +>>> 'Canada/Eastern' in common_timezones +True +>>> 'Australia/Yancowinna' in all_timezones +True +>>> 'Australia/Yancowinna' in common_timezones +False + +Both ``common_timezones`` and ``all_timezones`` are alphabetically +sorted: + +>>> common_timezones_dupe = common_timezones[:] +>>> common_timezones_dupe.sort() +>>> common_timezones == common_timezones_dupe +True +>>> all_timezones_dupe = all_timezones[:] +>>> all_timezones_dupe.sort() +>>> all_timezones == all_timezones_dupe +True + +``all_timezones`` and ``common_timezones`` are also available as sets. + +>>> from pytz import all_timezones_set, common_timezones_set +>>> 'US/Eastern' in all_timezones_set +True +>>> 'US/Eastern' in common_timezones_set +True +>>> 'Australia/Victoria' in common_timezones_set +False + +You can also retrieve lists of timezones used by particular countries +using the ``country_timezones()`` function. It requires an ISO-3166 +two letter country code. + +>>> from pytz import country_timezones +>>> print(' '.join(country_timezones('ch'))) +Europe/Zurich +>>> print(' '.join(country_timezones('CH'))) +Europe/Zurich + + +Internationalization - i18n/l10n +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Pytz is an interface to the IANA database, which uses ASCII names. The `Unicode Consortium's Unicode Locales (CLDR) `_ +project provides translations. Python packages such as +`Babel `_ +and Thomas Khyn's `l18n `_ package can be used +to access these translations from Python. + + +License +~~~~~~~ + +MIT license. + +This code is also available as part of Zope 3 under the Zope Public +License, Version 2.1 (ZPL). + +I'm happy to relicense this code if necessary for inclusion in other +open source projects. + + +Latest Versions +~~~~~~~~~~~~~~~ + +This package will be updated after releases of the Olson timezone +database. The latest version can be downloaded from the `Python Package +Index `_. The code that is used +to generate this distribution is hosted on Github and available +using git:: + + git clone https://github.com/stub42/pytz.git + +Announcements of new releases are made on +`Launchpad `_, and the +`Atom feed `_ +hosted there. + + +Bugs, Feature Requests & Patches +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Bugs should be reported on `Github `_. +Feature requests are unlikely to be considered, and efforts instead directed +to timezone support now built into Python or packages that work with it. + + +Security Issues +~~~~~~~~~~~~~~~ + +Reports about security issues can be made via `Tidelift `_. + + +Issues & Limitations +~~~~~~~~~~~~~~~~~~~~ + +- This project is in maintenance mode. Projects using Python 3.9 or later + are best served by using the timezone functionaly now included in core + Python and packages that work with it such as `tzdata `_. + +- Offsets from UTC are rounded to the nearest whole minute, so timezones + such as Europe/Amsterdam pre 1937 will be up to 30 seconds out. This + was a limitation of the Python datetime library. + +- If you think a timezone definition is incorrect, I probably can't fix + it. pytz is a direct translation of the Olson timezone database, and + changes to the timezone definitions need to be made to this source. + If you find errors they should be reported to the time zone mailing + list, linked from http://www.iana.org/time-zones. + + +Further Reading +~~~~~~~~~~~~~~~ + +More info than you want to know about timezones: +https://data.iana.org/time-zones/tz-link.html + + +Contact +~~~~~~~ + +Stuart Bishop diff --git a/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ff7b5d3017fcf1aa5e6b7f9bbc552d56f53e37a0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/RECORD @@ -0,0 +1,623 @@ +pytz-2026.1.post1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pytz-2026.1.post1.dist-info/LICENSE.txt,sha256=vosaN-vibFkqkPbA6zMQOn84POL010mMCvmlJpkKB7g,1088 +pytz-2026.1.post1.dist-info/METADATA,sha256=9i29NxHaxRyAmhe_K5AhqkvVKZnbITLfLji20JiD_Pw,22380 +pytz-2026.1.post1.dist-info/RECORD,, +pytz-2026.1.post1.dist-info/WHEEL,sha256=-G_t0oGuE7UD0DrSpVZnq1hHMBV9DD2XkS5v7XpmTnk,110 +pytz-2026.1.post1.dist-info/top_level.txt,sha256=6xRYlt934v1yHb1JIrXgHyGxn3cqACvd-yE8ski_kcc,5 +pytz-2026.1.post1.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +pytz/__init__.py,sha256=w4KuHtfQ7DGrXrvmSPKovOgkYMihYWmQJ50-mMpd8cU,35535 +pytz/__pycache__/__init__.cpython-312.pyc,, +pytz/__pycache__/exceptions.cpython-312.pyc,, +pytz/__pycache__/lazy.cpython-312.pyc,, +pytz/__pycache__/reference.cpython-312.pyc,, +pytz/__pycache__/tzfile.cpython-312.pyc,, +pytz/__pycache__/tzinfo.cpython-312.pyc,, +pytz/exceptions.py,sha256=434ZcuLlpLQY9mWoGq7zJMV1TyiYvVgpKBU1qZkbDjM,1571 +pytz/lazy.py,sha256=toeR5uDWKBj6ezsUZ4elNP6CEMtK7CO2jS9A30nsFbo,5404 +pytz/reference.py,sha256=zUtCki7JFEmrzrjNsfMD7YL0lWDxynKc1Ubo4iXSs74,3778 +pytz/tzfile.py,sha256=K2y7pZs4vydpZVftrfAA_-hgw17y1Szc7z_QCse6udU,4723 +pytz/tzinfo.py,sha256=XfaVOoO3KsCvtUYaCd0fvgBXWZ8tgevGYUoBh_uiE60,19340 +pytz/zoneinfo/Africa/Abidjan,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Accra,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Addis_Ababa,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Algiers,sha256=vaFpjNVCwObnbfu82rOQzdJvN6nVgmpXpQ1aqzfzsqY,735 +pytz/zoneinfo/Africa/Asmara,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Asmera,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Bamako,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Bangui,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Banjul,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Bissau,sha256=IjuxDP6EZiDHFvl_bHS6NN7sdRxLKXllooBC829poak,194 +pytz/zoneinfo/Africa/Blantyre,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Brazzaville,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Bujumbura,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Cairo,sha256=Lft-GCLQhaSJm9VqUmsEFoHIS1Vhfa7pFJn9GZCpifs,2399 +pytz/zoneinfo/Africa/Casablanca,sha256=4RqVbw_F3ZucopIC2ivAJ8WDwj5wRODAB67tBpdXcgA,2429 +pytz/zoneinfo/Africa/Ceuta,sha256=Cw-2_nFDGbN8WqIsVpcauyZooWX8j3Kmx2PnC0fHut8,2052 +pytz/zoneinfo/Africa/Conakry,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Dakar,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Dar_es_Salaam,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Djibouti,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Douala,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/El_Aaiun,sha256=UWCCqQLJxd8qsTYw82kz9W1suwW5TRgnZw31sDWDz20,2295 +pytz/zoneinfo/Africa/Freetown,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Gaborone,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Harare,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Johannesburg,sha256=bBvMdSZo53WFowiuhUO9C8zY6BOGViboCb-U8_49l34,246 +pytz/zoneinfo/Africa/Juba,sha256=UVnIqEPJwHLTMC-r5qZQHNv9opoYVsKdq-ta_5XUw_Q,679 +pytz/zoneinfo/Africa/Kampala,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Khartoum,sha256=MYWDoJ3AcCItZdApoeOgtWWDDxquwTon5v5TOGP70-o,679 +pytz/zoneinfo/Africa/Kigali,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Kinshasa,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Lagos,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Libreville,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Lome,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Luanda,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Lubumbashi,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Lusaka,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Malabo,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Maputo,sha256=RE7TpxBBS8a_Q-sn5ZHaSdO-PbFTRJpqDJRz9-Of28s,149 +pytz/zoneinfo/Africa/Maseru,sha256=bBvMdSZo53WFowiuhUO9C8zY6BOGViboCb-U8_49l34,246 +pytz/zoneinfo/Africa/Mbabane,sha256=bBvMdSZo53WFowiuhUO9C8zY6BOGViboCb-U8_49l34,246 +pytz/zoneinfo/Africa/Mogadishu,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Monrovia,sha256=-VsJW5cU4KdvfgYaQVv4lcuzmaKIVFMd42nO6RXOBdU,208 +pytz/zoneinfo/Africa/Nairobi,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Africa/Ndjamena,sha256=8T3A0Zm9Gj0Bvm6rd88t3GAXKiKdGUfHlIqYlkYI0KM,199 +pytz/zoneinfo/Africa/Niamey,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Nouakchott,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Ouagadougou,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Porto-Novo,sha256=z_6wKCzL1_ug5JP_hneh5abdUZeIUELkN_ladz-ESEY,235 +pytz/zoneinfo/Africa/Sao_Tome,sha256=MdjxpQ268uzJ7Zx1ZroFUtRUwqsJ6F_yY3AYV9FXw1I,254 +pytz/zoneinfo/Africa/Timbuktu,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Africa/Tripoli,sha256=W1dptGD70T7ppGoo0fczFQeDiIp0nultLNPV66MwB2c,625 +pytz/zoneinfo/Africa/Tunis,sha256=OFVMEM4eYT2Ez0beuhEUCTSIpcFldWxsV2uEoTZIUNI,689 +pytz/zoneinfo/Africa/Windhoek,sha256=xuhvudrMH4alnVmouSTQI8YL8F_HbgsF2EQ7AZKzuHs,955 +pytz/zoneinfo/America/Adak,sha256=IB1DhwJQAKbhPJ9jHLf8zW5Dad7HIkBS-dhv64E1OlM,2356 +pytz/zoneinfo/America/Anchorage,sha256=oZA1NSPS2BWdymYpnCHFO8BlYVS-ll5KLg2Ez9CbETs,2371 +pytz/zoneinfo/America/Anguilla,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Antigua,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Araguaina,sha256=G6v9wYFZ8EB4WQfIsqRbbiiKd2b27j7Zt5dFjBbzx2o,870 +pytz/zoneinfo/America/Argentina/Buenos_Aires,sha256=JmU8lBwmy29gR6OmeytvFdMRx6ObJKnYNHmLyMmXX2M,1062 +pytz/zoneinfo/America/Argentina/Catamarca,sha256=uMCJXXGYmNESHVvj5RYBZ0McrOdE14hwm17l25MgRW0,1062 +pytz/zoneinfo/America/Argentina/ComodRivadavia,sha256=uMCJXXGYmNESHVvj5RYBZ0McrOdE14hwm17l25MgRW0,1062 +pytz/zoneinfo/America/Argentina/Cordoba,sha256=uniNihhMHnr4XK4WpwiPUnrAT0YPmvzqB6f0hRLtXvY,1062 +pytz/zoneinfo/America/Argentina/Jujuy,sha256=PGmAehypCxj0XCenCSWqylDIPbKLK0DlrwJK_24D590,1034 +pytz/zoneinfo/America/Argentina/La_Rioja,sha256=Um6XoVXhsr62ad1mWuebe6NY0ZHauBdR9tMGDgqCOHg,1076 +pytz/zoneinfo/America/Argentina/Mendoza,sha256=xcOVtvRyVYFAU90y2QYwpyQhpMLyAp7-Fxvku4kgl0c,1062 +pytz/zoneinfo/America/Argentina/Rio_Gallegos,sha256=F9ZKR4o8gLHX7QBuIjMapGIdmzJxpqwbouPgZ5MqDpY,1062 +pytz/zoneinfo/America/Argentina/Salta,sha256=h1KYrDNIapvDkYhi1PaB8WD1qWOe4vhhgDJWDCGV4jc,1034 +pytz/zoneinfo/America/Argentina/San_Juan,sha256=AI2GltA80mPNzhHxYycuEwIbO1ANXyIqBQZMpjqKqdQ,1076 +pytz/zoneinfo/America/Argentina/San_Luis,sha256=2ItGRcLVK2wx8MyJsHbIBBeAkU4B-MN5x1ZxNyZ7UJE,1088 +pytz/zoneinfo/America/Argentina/Tucuman,sha256=twO-FqtNJV8XOzWTvFQ-xnEcWCoDUHY3gpVIG0Mzbf8,1090 +pytz/zoneinfo/America/Argentina/Ushuaia,sha256=A6IbpVlY9IIPoSKMFRR9DMROdwXUSDc2HsASueOSnqo,1062 +pytz/zoneinfo/America/Aruba,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Asuncion,sha256=9yfGiENhXNgd2_0xHVsF-hLeJkGSqRs-zD9O945KJWc,1644 +pytz/zoneinfo/America/Atikokan,sha256=kayA_pdpMcSQ0FjIzotdcf-m1JYfbKE-qcFT8LC8zqA,182 +pytz/zoneinfo/America/Atka,sha256=IB1DhwJQAKbhPJ9jHLf8zW5Dad7HIkBS-dhv64E1OlM,2356 +pytz/zoneinfo/America/Bahia,sha256=qi7dA6FofDhLxVMmd2L8bK3HeaQnc9X-jiijwyfhs3g,1010 +pytz/zoneinfo/America/Bahia_Banderas,sha256=MvrXGJ5LzaHOeguJqxszxjxMhVafGVbk-ojXEc7_YEI,1100 +pytz/zoneinfo/America/Barbados,sha256=ima-Qrrhazu4Qfvu2Z0-e6E-GTiYknuJBu6c2yVG9LE,436 +pytz/zoneinfo/America/Belem,sha256=aZMUgtFDdHNISpqyQRYbmS2IBD-BAS3CaJnhu6onLCY,562 +pytz/zoneinfo/America/Belize,sha256=pkfLY2KfPchbeJa1pWcXmWAwp4ZlRvxWLVezXnrbkws,1614 +pytz/zoneinfo/America/Blanc-Sablon,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Boa_Vista,sha256=dMtaG11kGlJrgJJgGWEDZZAmnO_HfT3L4X8pI72LLFY,618 +pytz/zoneinfo/America/Bogota,sha256=Z1ernZZGQxulE8KFWHYWcM3SV1jn2_QEc1Q0OJzHRak,232 +pytz/zoneinfo/America/Boise,sha256=7HQsNPJiUheQgFz5kVLvTnf5xhXAYaeANqDskxKz2Vs,2410 +pytz/zoneinfo/America/Buenos_Aires,sha256=JmU8lBwmy29gR6OmeytvFdMRx6ObJKnYNHmLyMmXX2M,1062 +pytz/zoneinfo/America/Cambridge_Bay,sha256=_4xRlX3WdVpEcqoT6myD7NeTCXnn9OYk_iH006bwULo,2254 +pytz/zoneinfo/America/Campo_Grande,sha256=gINiXg5i2e6Rh2Nbo2bFqhPAJL4F4cAqGnBankXTDXw,1430 +pytz/zoneinfo/America/Cancun,sha256=EdV0Nw2WjM7VnjFHoq5jsSbLuuE7eP1OE74utEyWJG4,864 +pytz/zoneinfo/America/Caracas,sha256=mUNMFdDzZLav_ePA1ocBdmqVBierkeEszTIFpNCm5J0,250 +pytz/zoneinfo/America/Catamarca,sha256=uMCJXXGYmNESHVvj5RYBZ0McrOdE14hwm17l25MgRW0,1062 +pytz/zoneinfo/America/Cayenne,sha256=4k7Iv1woX4atqePKrcvMQD2Vk9Tmma7rW_AW_R62pCc,184 +pytz/zoneinfo/America/Cayman,sha256=kayA_pdpMcSQ0FjIzotdcf-m1JYfbKE-qcFT8LC8zqA,182 +pytz/zoneinfo/America/Chicago,sha256=_roybr6I6sIAF6cYdIxGxoRpoef153Fty48dQ6bm9oY,3592 +pytz/zoneinfo/America/Chihuahua,sha256=3Ngzbedg8AzAqxsbQSG0jVRx-LxYlw1i3kx-Yzl-2Ic,1102 +pytz/zoneinfo/America/Ciudad_Juarez,sha256=ir4b27DiFrhL0H4fZQ92nEa-BBoPfLWIz3phU373dgE,1538 +pytz/zoneinfo/America/Coral_Harbour,sha256=kayA_pdpMcSQ0FjIzotdcf-m1JYfbKE-qcFT8LC8zqA,182 +pytz/zoneinfo/America/Cordoba,sha256=uniNihhMHnr4XK4WpwiPUnrAT0YPmvzqB6f0hRLtXvY,1062 +pytz/zoneinfo/America/Costa_Rica,sha256=74rYa6lrgIkyls9PkHo8SCYl9oOqiuG5S7MWdnJelP4,316 +pytz/zoneinfo/America/Coyhaique,sha256=beZXU6Lw5jx2Wp3dNRkFiofXGma2dM6DsqvJT9CSHdc,2126 +pytz/zoneinfo/America/Creston,sha256=illz0sYuLL8lIPK0Tkou6dL0Vck_D0W_3rRTOvFYRmQ,360 +pytz/zoneinfo/America/Cuiaba,sha256=GRJqkhRXNsOUcgjZddQxRIJdRYaw9pM_YLWbun88dkg,1402 +pytz/zoneinfo/America/Curacao,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Danmarkshavn,sha256=YRZAfUCoVtaL1L-MYMYMH1wyOaVQnfUo_gFnvMXSuzw,698 +pytz/zoneinfo/America/Dawson,sha256=rAHhyuMuyjf_eyA2SBG76MRBf_fj_xi5FAuiWVQgJhw,1614 +pytz/zoneinfo/America/Dawson_Creek,sha256=aJXCyP4j3ggE4wGCN-LrS9hpD_5zWHzQTeSAKTWEPUM,1050 +pytz/zoneinfo/America/Denver,sha256=MugZwApDs8NI9TnXANQlUE8guNBowWQY0m-ptpPndck,2460 +pytz/zoneinfo/America/Detroit,sha256=hecz8yqY2Cj5B61G3gLZdAVZvRgK9l0P90c_gN-uD5g,2230 +pytz/zoneinfo/America/Dominica,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Edmonton,sha256=-TkIfc3QlvaCf0p8COZ43Y1HRBAl-nARUi-JdXeK1vE,2332 +pytz/zoneinfo/America/Eirunepe,sha256=j5eExkjFaqtC-D8XK0rGzoF9yEgbSlTbPqVG9WKhEa8,642 +pytz/zoneinfo/America/El_Salvador,sha256=gvGN8Lkj-sGm2_rs8OUjAMf1oMtKp2Xes6UfWT0WqgU,224 +pytz/zoneinfo/America/Ensenada,sha256=jC57Mhcm5jRZEto5Z5a9s2cr_EvRqRxl7lizjgBNTKU,2906 +pytz/zoneinfo/America/Fort_Nelson,sha256=erfODr3DrSpz65kAdO7Ts2dGbZxvddEP6gx4BX3y2J0,2240 +pytz/zoneinfo/America/Fort_Wayne,sha256=kNKy9Kj9ICsiYYfCCbAggzMA7exf-GpGPMxoXocHUyw,1682 +pytz/zoneinfo/America/Fortaleza,sha256=rjiSB0q1cBuMDOM9orW_uwe5UOLBwTlfjFotwOYe1mU,702 +pytz/zoneinfo/America/Glace_Bay,sha256=G8DGLGCapH_aYCF_OhaL5Qonf7FOAgAPwelO5htCWBc,2192 +pytz/zoneinfo/America/Godthab,sha256=KGXrMN-YkYpVCgLdpcfwMFQ77EsRAGsjUCG3yAUvVfw,1889 +pytz/zoneinfo/America/Goose_Bay,sha256=JgaLueghSvX2g725FOfIgpgvsqxZGykWOhAZWGpQZRY,3210 +pytz/zoneinfo/America/Grand_Turk,sha256=4YOFEPK60Bel2_fCsY6vSZxUcMJKjiKtyOf_Q0khEwU,1834 +pytz/zoneinfo/America/Grenada,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Guadeloupe,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Guatemala,sha256=dugUgCd6QY52yHkHuUP4jRWzo5x439IQigaYCvEF46Q,280 +pytz/zoneinfo/America/Guayaquil,sha256=j2UuIo-4RgSOlTNfu77mhZ92waNTeKFSvmoVemJooT0,232 +pytz/zoneinfo/America/Guyana,sha256=R0bOvCRDC8SRIexmhsduPdHbbRPwI2GviD9otExiUrk,248 +pytz/zoneinfo/America/Halifax,sha256=TZpmc5PwWoLfTfQoQ_b3U17BE2iVKSeNkR0Ho8mbTn8,3424 +pytz/zoneinfo/America/Havana,sha256=HUQeAuKBsEkI5SLZjqynXICOUVOajkKzKH5r-Ov5Odc,2416 +pytz/zoneinfo/America/Hermosillo,sha256=ixYKestLmS7gWobk9Kq6FtLZo1yqbWActrFUKluzctw,388 +pytz/zoneinfo/America/Indiana/Indianapolis,sha256=kNKy9Kj9ICsiYYfCCbAggzMA7exf-GpGPMxoXocHUyw,1682 +pytz/zoneinfo/America/Indiana/Knox,sha256=CsvZ5BKw2qVav3x_F8CU9taJdDk7jX41Cfsqms6jXV8,2444 +pytz/zoneinfo/America/Indiana/Marengo,sha256=f3tQ-lgMSUA7nvn64pXhKtJL7mWzGajoCega5MEJSbI,1738 +pytz/zoneinfo/America/Indiana/Petersburg,sha256=A88OHuM0Rg3iMLHjKgXq_d2jZCdVSytUQs-9W0KcFyQ,1920 +pytz/zoneinfo/America/Indiana/Tell_City,sha256=4dWqAr9Y2BXfL4pAQk-81c3gGl2cNdHXOD7_wJhhhn8,1700 +pytz/zoneinfo/America/Indiana/Vevay,sha256=H7VR2G-_sD_C5Rm4P3g1iRC1FWCPg4m0MGD3P1PLzsk,1430 +pytz/zoneinfo/America/Indiana/Vincennes,sha256=62mAxT7APFCaoygflnEzdOpe-fuW1yObI6m6EUUcS7A,1710 +pytz/zoneinfo/America/Indiana/Winamac,sha256=aZGM2jR8CH9BHSUq7XygiweDd6dorXLPXg246XsbR6s,1794 +pytz/zoneinfo/America/Indianapolis,sha256=kNKy9Kj9ICsiYYfCCbAggzMA7exf-GpGPMxoXocHUyw,1682 +pytz/zoneinfo/America/Inuvik,sha256=6J-mapDnrk9A1LtswoE34tqSy_ufedcEBNxixkrEjIo,2074 +pytz/zoneinfo/America/Iqaluit,sha256=feOnxAN0N0r-M1qlkrA4JMyawoc0tqae0iiBCPDAs4k,2202 +pytz/zoneinfo/America/Jamaica,sha256=wlagieUPRf5-beie-h7QsONbNzjGsm8vMs8uf28pw28,482 +pytz/zoneinfo/America/Jujuy,sha256=PGmAehypCxj0XCenCSWqylDIPbKLK0DlrwJK_24D590,1034 +pytz/zoneinfo/America/Juneau,sha256=k7hxb0aGRnfnE-DBi3LkcjAzRPyAf0_Hw0vVFfjGeb0,2353 +pytz/zoneinfo/America/Kentucky/Louisville,sha256=tP072xV_n_vIQjxxcJ77AGeGj6yL1KPpn3fwids9g1U,2788 +pytz/zoneinfo/America/Kentucky/Monticello,sha256=LtdyCo85BrXQs6rlH61Ym-8KqWHH6PwAOjD0QxhIdzM,2368 +pytz/zoneinfo/America/Knox_IN,sha256=CsvZ5BKw2qVav3x_F8CU9taJdDk7jX41Cfsqms6jXV8,2444 +pytz/zoneinfo/America/Kralendijk,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/La_Paz,sha256=hqfD8LQHupdZhji2e93_9pOQAT-R7muzzjP0nyfbFXY,218 +pytz/zoneinfo/America/Lima,sha256=HHgTnDUnCZzibvL0MrG8qyOuvjmYYw3e3R5VbnxMZs8,392 +pytz/zoneinfo/America/Los_Angeles,sha256=aJd7ua1tGG_vxser02AQpm4wAI3LLTdgh6QcSYYecmg,2852 +pytz/zoneinfo/America/Louisville,sha256=tP072xV_n_vIQjxxcJ77AGeGj6yL1KPpn3fwids9g1U,2788 +pytz/zoneinfo/America/Lower_Princes,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Maceio,sha256=3R5DlSe32kQDmoSVIWpcyk2o7qohr-rliwqDSGFIMyQ,730 +pytz/zoneinfo/America/Managua,sha256=xBzF01AHn2E2fD8Qdy-DHFe36UqoeNpKPfChduBKWdk,430 +pytz/zoneinfo/America/Manaus,sha256=F6RLOOeOi9lymZiQmQ9pR8tFpPZ6EguNdPfOc6BhXDE,590 +pytz/zoneinfo/America/Marigot,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Martinique,sha256=fMs80kOU2YFvC0f9y2eje97JeAtTYBamXrnlTunNLzQ,232 +pytz/zoneinfo/America/Matamoros,sha256=fq-PqdmZrQ98UsFmHA9ivjBZv5GEBRTOuLQ5Cu5ajW8,1418 +pytz/zoneinfo/America/Mazatlan,sha256=BWH2NqVPA1PsyELPN_2BF8KllrsmQkqg1eujsQvnnx8,1060 +pytz/zoneinfo/America/Mendoza,sha256=xcOVtvRyVYFAU90y2QYwpyQhpMLyAp7-Fxvku4kgl0c,1062 +pytz/zoneinfo/America/Menominee,sha256=Arv9WLbfhNcpRsUjHDU757BEdwlp08Gt30AixG3gZ04,2274 +pytz/zoneinfo/America/Merida,sha256=SVNEHCazjomftnuPVBayFI-E-IQ0WmluHfTpHP0h3d0,1004 +pytz/zoneinfo/America/Metlakatla,sha256=twmieGTVY2V-U8nFxqvx7asYv8GVjeWdLtrOI7UApVI,1423 +pytz/zoneinfo/America/Mexico_City,sha256=Uog2-FMWz2o12jR6sK9vemJamLeo6OEFMQR3s0xTxkc,1222 +pytz/zoneinfo/America/Miquelon,sha256=l5txBJYe9HTRZlILcbSL_HNDYrjUb0ouecNy7QEkg9c,1652 +pytz/zoneinfo/America/Moncton,sha256=Wmv-bk9aKKcWWzOpc1UFu67HOfwaIk2Wmh3LgqGctys,3154 +pytz/zoneinfo/America/Monterrey,sha256=YixTESJubf6ZBUXy6g32hAM2gR4GXXPqOU4tv0L3kG0,1114 +pytz/zoneinfo/America/Montevideo,sha256=dQEBE4mjZPtyRjKXK6Z-bMHJdFqpwhIzxDH4x04rKYk,1496 +pytz/zoneinfo/America/Montreal,sha256=pYehoWB0Ofe6woPhgV8r26-5ZJpFPRjgbC5E5pltiI8,3494 +pytz/zoneinfo/America/Montserrat,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Nassau,sha256=pYehoWB0Ofe6woPhgV8r26-5ZJpFPRjgbC5E5pltiI8,3494 +pytz/zoneinfo/America/New_York,sha256=6e0H177gx2qdRC0JHvHwFmj-58TyYBTAqGixn-bBipU,3552 +pytz/zoneinfo/America/Nipigon,sha256=pYehoWB0Ofe6woPhgV8r26-5ZJpFPRjgbC5E5pltiI8,3494 +pytz/zoneinfo/America/Nome,sha256=2izM3-P-PqJ9za6MdhzFfMvPFNq7Gim69tAvEwPeY2s,2367 +pytz/zoneinfo/America/Noronha,sha256=feeRAijQqKylZgqe84nKhsFLycT5zIBm7mLIvdyGw4w,702 +pytz/zoneinfo/America/North_Dakota/Beulah,sha256=qtgbqNu8M3AkHF2n-_oSps1pYT4SxgclbkkPKbXaBHs,2396 +pytz/zoneinfo/America/North_Dakota/Center,sha256=9ZWbK9YKkquULyBUFS3Lr_idxbt7V7y4W4EO0Kn20sw,2396 +pytz/zoneinfo/America/North_Dakota/New_Salem,sha256=DH_bsQfuUnK2obdb06KgisO4XLqht12BXdrgUsZZveg,2396 +pytz/zoneinfo/America/Nuuk,sha256=KGXrMN-YkYpVCgLdpcfwMFQ77EsRAGsjUCG3yAUvVfw,1889 +pytz/zoneinfo/America/Ojinaga,sha256=b38Q_7VdkCZzaVwb7OXuddihJAzUKPTTqXcmpBm1ntE,1524 +pytz/zoneinfo/America/Panama,sha256=kayA_pdpMcSQ0FjIzotdcf-m1JYfbKE-qcFT8LC8zqA,182 +pytz/zoneinfo/America/Pangnirtung,sha256=feOnxAN0N0r-M1qlkrA4JMyawoc0tqae0iiBCPDAs4k,2202 +pytz/zoneinfo/America/Paramaribo,sha256=Z7UZvNlgd-qEUHjEPYXIkLNTgjMcCzk9EfUUEmUyd7M,248 +pytz/zoneinfo/America/Phoenix,sha256=illz0sYuLL8lIPK0Tkou6dL0Vck_D0W_3rRTOvFYRmQ,360 +pytz/zoneinfo/America/Port-au-Prince,sha256=09ZAJd4IOiMpfdpUuF1U44R_hRt6BvpAkFXOnYO9yOM,1434 +pytz/zoneinfo/America/Port_of_Spain,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Porto_Acre,sha256=0gpJUl46hQbp0P6Xj1S0NArIWeAryuuDXjsldvB5GHE,614 +pytz/zoneinfo/America/Porto_Velho,sha256=uSMV2hZWj-VyBhFBwC950wcThfN3jq6KlycESmQTLOA,562 +pytz/zoneinfo/America/Puerto_Rico,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Punta_Arenas,sha256=tR5uIf1351AWFqrqNtmXnhQWnKREmJaZqKBzaWRVMTQ,1902 +pytz/zoneinfo/America/Rainy_River,sha256=7P-_YQrneFcon7QKSTOnkiGjEppFDn3Z48MJ1qq8VBw,2868 +pytz/zoneinfo/America/Rankin_Inlet,sha256=nXgqjL3O2BV0em-Xk8qVRRZb_X0yQmHE6vmSSvI9Kzc,2066 +pytz/zoneinfo/America/Recife,sha256=bJ_HE0-JFio4-owpZ0pLO8U3ai0fiGu8QHL0DexLiLc,702 +pytz/zoneinfo/America/Regina,sha256=yjqT08pHbICYe83H8JmtaDBvCFqRv7Tfze3Y8xuXukw,980 +pytz/zoneinfo/America/Resolute,sha256=CnMU2dBI-63vt8-J0Q1Ropx-8b9pRCLjhvrycMIedGg,2066 +pytz/zoneinfo/America/Rio_Branco,sha256=0gpJUl46hQbp0P6Xj1S0NArIWeAryuuDXjsldvB5GHE,614 +pytz/zoneinfo/America/Rosario,sha256=uniNihhMHnr4XK4WpwiPUnrAT0YPmvzqB6f0hRLtXvY,1062 +pytz/zoneinfo/America/Santa_Isabel,sha256=jC57Mhcm5jRZEto5Z5a9s2cr_EvRqRxl7lizjgBNTKU,2906 +pytz/zoneinfo/America/Santarem,sha256=VmZP9S5pPucFxyqAOV908EmWXQZvgCgWLmlJJTUl0LE,588 +pytz/zoneinfo/America/Santiago,sha256=0CDw13dCMUsoquMupoJgupkzAUNhDK6E0lVxURA7osA,2515 +pytz/zoneinfo/America/Santo_Domingo,sha256=DKtaEj8fQ92ybITTWU4Bm160S9pzJmUVbjaWRnenxU4,458 +pytz/zoneinfo/America/Sao_Paulo,sha256=BMBnRO4_4HjvO4t3njjrMGZr-ZPmegkvyvL8KPY6ZM4,1430 +pytz/zoneinfo/America/Scoresbysund,sha256=K-qkiMCCFgOe8ccPMABA-lDjc9vb6wpluBOCVfiBdLI,1935 +pytz/zoneinfo/America/Shiprock,sha256=MugZwApDs8NI9TnXANQlUE8guNBowWQY0m-ptpPndck,2460 +pytz/zoneinfo/America/Sitka,sha256=aiS7Fk37hZpzZ9VkeJQeF-BqTLRC1QOTCgMAJwT8UxA,2329 +pytz/zoneinfo/America/St_Barthelemy,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/St_Johns,sha256=r1-17uKv27eZ3JsVkw_DLZQbo6wvjuuVu7C2pDsmOgI,3655 +pytz/zoneinfo/America/St_Kitts,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/St_Lucia,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/St_Thomas,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/St_Vincent,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Swift_Current,sha256=RRKOF7vZC8VvYxD8PP4J1_hUPayKBP7Lu80avRkfPDY,560 +pytz/zoneinfo/America/Tegucigalpa,sha256=EzOz7ntTlreMq69JZ2CcAb8Ps98V9bUMN480tpPIyw4,252 +pytz/zoneinfo/America/Thule,sha256=8xuPRaZU8RgO5ECqFYHYmnHioc81sBOailkVu8Y02i8,1502 +pytz/zoneinfo/America/Thunder_Bay,sha256=pYehoWB0Ofe6woPhgV8r26-5ZJpFPRjgbC5E5pltiI8,3494 +pytz/zoneinfo/America/Tijuana,sha256=jC57Mhcm5jRZEto5Z5a9s2cr_EvRqRxl7lizjgBNTKU,2906 +pytz/zoneinfo/America/Toronto,sha256=pYehoWB0Ofe6woPhgV8r26-5ZJpFPRjgbC5E5pltiI8,3494 +pytz/zoneinfo/America/Tortola,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Vancouver,sha256=sknKH0jSPWam-DHfM35qXs8Nam7d5TFlkUI9Sgxryyg,2892 +pytz/zoneinfo/America/Virgin,sha256=hJHlV_-AGoMGUWuMpZRv9fLmghrzFHfrR9fRkcxaZJc,246 +pytz/zoneinfo/America/Whitehorse,sha256=TrR6PCnYG-mSClBMohqlP8qnYhXMUsydI-L-quXFxyM,1614 +pytz/zoneinfo/America/Winnipeg,sha256=7P-_YQrneFcon7QKSTOnkiGjEppFDn3Z48MJ1qq8VBw,2868 +pytz/zoneinfo/America/Yakutat,sha256=tFwnKbvwhyyn4LNTAn5ye_JWDdxjCerNDt7oOwUwO2M,2305 +pytz/zoneinfo/America/Yellowknife,sha256=-TkIfc3QlvaCf0p8COZ43Y1HRBAl-nARUi-JdXeK1vE,2332 +pytz/zoneinfo/Antarctica/Casey,sha256=VeaLOxTfDyjfGXq5Ul95JEIMXNWHSW-0N3yOoS7VK-c,423 +pytz/zoneinfo/Antarctica/Davis,sha256=XB12dEq0Q-3XkzBNTNC7G1fzH-WxxctIuZqI3zp8ypI,283 +pytz/zoneinfo/Antarctica/DumontDUrville,sha256=nB36HBWZTdh3TlP0DLFNz1KRQ0aHIfHbp7LC4Urp9fA,172 +pytz/zoneinfo/Antarctica/Macquarie,sha256=ie7RlaU8RHTorVVj-MX8StKMqx_oXf4UH2PUqpzcwe0,2260 +pytz/zoneinfo/Antarctica/Mawson,sha256=EjIFbqRdr2ZJBaI1XvoWRptnnW1LFrlhydxDDuIQjSI,185 +pytz/zoneinfo/Antarctica/McMurdo,sha256=gADjoyPo_QISQU6UJrAgcHp3HDaMoOFRdH-d23uBSyc,2437 +pytz/zoneinfo/Antarctica/Palmer,sha256=HTZY0M8td7oUx5REPgRCHuqKg5V3fjJEi4lYBNL4Etg,1404 +pytz/zoneinfo/Antarctica/Rothera,sha256=_9NY-f8vkozQYrjbUHP5YjcICg0-LuyA9PnIeK123RU,150 +pytz/zoneinfo/Antarctica/South_Pole,sha256=gADjoyPo_QISQU6UJrAgcHp3HDaMoOFRdH-d23uBSyc,2437 +pytz/zoneinfo/Antarctica/Syowa,sha256=oCKH7uafN8R1o-ijXGoT5U1JZxwvoLzJu_2Cqyi2hUM,151 +pytz/zoneinfo/Antarctica/Troll,sha256=fjcYppwr1FnjEssee-RLgGOANzoUyfjse-RGK46PR2E,1148 +pytz/zoneinfo/Antarctica/Vostok,sha256=KfftwdzK6PkMDz0d-D3z4HKIBgY9KqsqHnTnqsPMrUg,213 +pytz/zoneinfo/Arctic/Longyearbyen,sha256=XuR19xoPwaMvrrhJ-MOcbnqmbW1B7HQrl7OnQ2s7BwE,2298 +pytz/zoneinfo/Asia/Aden,sha256=oCKH7uafN8R1o-ijXGoT5U1JZxwvoLzJu_2Cqyi2hUM,151 +pytz/zoneinfo/Asia/Almaty,sha256=lPLWXk2f1mWYRQZFkIrq_5HkhocsUBis0M-yhdDHcBQ,983 +pytz/zoneinfo/Asia/Amman,sha256=Qv4cXXw7KBQWE882cgj0kjQ3wh1vpV1orJ2v2Jjxr2U,1433 +pytz/zoneinfo/Asia/Anadyr,sha256=WqKnHo5IHSWZ08d2sS5ytHtv0MQMoczP3W9zbDDrbYU,1174 +pytz/zoneinfo/Asia/Aqtau,sha256=4n654FZtDssXSfhQszjZG5OmtbE2zo1KbiWcYrFJg00,969 +pytz/zoneinfo/Asia/Aqtobe,sha256=1oFHTb-ybcTqLXm0r1ZOVgdYMTHlGoNs-Pgvux50d3E,997 +pytz/zoneinfo/Asia/Ashgabat,sha256=-sfGnRumio7_Bs8w9YH4xRDWgjB3wBeW7c0C56Qqk64,605 +pytz/zoneinfo/Asia/Ashkhabad,sha256=-sfGnRumio7_Bs8w9YH4xRDWgjB3wBeW7c0C56Qqk64,605 +pytz/zoneinfo/Asia/Atyrau,sha256=_U8COUIE9nG_HKddZE1Q0sPuz3rMwfjwmfnVDY_vSmg,977 +pytz/zoneinfo/Asia/Baghdad,sha256=S-plKI4zCLqI0idGABEk3oRTazNyrIj2T98-EtWtZD8,969 +pytz/zoneinfo/Asia/Bahrain,sha256=wklGY3WPGp-z1OUwb_KOHzRTwBndt1RfDg9Uttt36G4,185 +pytz/zoneinfo/Asia/Baku,sha256=6_hq98SGG0j0JA8qYx96WcIMZSLW4w460QXh_OM_ccg,1213 +pytz/zoneinfo/Asia/Bangkok,sha256=hf_5PVegQcFSS60CjS80C7h-TGOrfQ4ncm83N8VmZkk,185 +pytz/zoneinfo/Asia/Barnaul,sha256=3zeUimLTMrIZE0vX6XHFvB3MoqExoVbE5CSm6GV0zf0,1207 +pytz/zoneinfo/Asia/Beirut,sha256=_Z_2ZAg_iL9vU51JDB8CB04uXBDrf1kLIis-JnXaS2o,2154 +pytz/zoneinfo/Asia/Bishkek,sha256=IOoUyjABILCkXu1rjCIqSwAufRYFklc5YAC4jdhVw6Q,969 +pytz/zoneinfo/Asia/Brunei,sha256=D5qtyWJ_SM8bTQeJJIYhqqojxlVKbrFC1EYMDU9GzXQ,469 +pytz/zoneinfo/Asia/Calcutta,sha256=6Qw0EDbLcgMgDik8s7UTJn4QSjmllPNeGVJU5rwKF88,285 +pytz/zoneinfo/Asia/Chita,sha256=LbSlS23swFkANUScg8zkNR0imANWNfOIaYd39HbLdIQ,1207 +pytz/zoneinfo/Asia/Choibalsan,sha256=qUkXRsTc_u7B90JxULSu7yzKbGtGfKcfEFIasGPC2ec,877 +pytz/zoneinfo/Asia/Chongqing,sha256=ZP_C5DqUQ1oEPAQNHTr36S0DGtx453N68YYbqk7u8-Y,561 +pytz/zoneinfo/Asia/Chungking,sha256=ZP_C5DqUQ1oEPAQNHTr36S0DGtx453N68YYbqk7u8-Y,561 +pytz/zoneinfo/Asia/Colombo,sha256=w52L7bgT4m5hcgRuevIPY83xytfkBmkLhnKMwp16KsY,358 +pytz/zoneinfo/Asia/Dacca,sha256=-xulJ2KVhvKp6rlZLMydpw7oXVirk-riEH-181xPE54,323 +pytz/zoneinfo/Asia/Damascus,sha256=EthGheaHWmy5IrLCc9NmM3jvASQFHt8TsBF07I1tgbg,1873 +pytz/zoneinfo/Asia/Dhaka,sha256=-xulJ2KVhvKp6rlZLMydpw7oXVirk-riEH-181xPE54,323 +pytz/zoneinfo/Asia/Dili,sha256=2A9uFmwSwoFA5o2ek1LA0ucohPnM42ghWvD9D5TdnJk,257 +pytz/zoneinfo/Asia/Dubai,sha256=pmdhPhaJRwKwONvxiZNGeFSICjlWzyY9JlFHv-H9upY,151 +pytz/zoneinfo/Asia/Dushanbe,sha256=koYnnYWuFsBXd1vJfZsGdpwnbFHEwvkGBmSrrx3KIss,577 +pytz/zoneinfo/Asia/Famagusta,sha256=CFrcygd8ude5x6OEtfM_Dw0KYHoxpPPzq46KoHVxjjc,2028 +pytz/zoneinfo/Asia/Gaza,sha256=t0YxcUQL53VNKnKbKijn0OE_MaryEynonabse-iTtzs,3844 +pytz/zoneinfo/Asia/Harbin,sha256=ZP_C5DqUQ1oEPAQNHTr36S0DGtx453N68YYbqk7u8-Y,561 +pytz/zoneinfo/Asia/Hebron,sha256=6Y0USHKx-xoCxCr_WpCuM3olP1vUGnzrcnGiyQFcqdQ,3872 +pytz/zoneinfo/Asia/Ho_Chi_Minh,sha256=Lnv1vpUNAXBo8v0b9d9AQpy-AEyO5Qa2Ig0PvDkjrmU,337 +pytz/zoneinfo/Asia/Hong_Kong,sha256=al_O4kPlq5JpgkLYjEaZzrcgiiLul9NC0R5B69JVWhc,1233 +pytz/zoneinfo/Asia/Hovd,sha256=Zn4PLGlD-URJDsbChor5bqWTzuAil2tbrGJW0j5TLbs,877 +pytz/zoneinfo/Asia/Irkutsk,sha256=IVuoXCwdeI-KIUfFkEt6yBjqYP3V9GTrF-_WLnffFzk,1229 +pytz/zoneinfo/Asia/Istanbul,sha256=Jk4wjndDta_uLWc8W1dWdjbavJJbsL5ROTmZboVnGKU,1933 +pytz/zoneinfo/Asia/Jakarta,sha256=TvEzBvSzfzFCdOsMAZ0QgR95JA5xf3kAZONhy5gEXRE,383 +pytz/zoneinfo/Asia/Jayapura,sha256=ihzUd-L8HUVqG-Na10MyPE-YYwjVFj-xerqjTN4EJZs,221 +pytz/zoneinfo/Asia/Jerusalem,sha256=JUuWQmW5Tha0pJjw61Q5aN7CX0z4D7ops9OOSnda6Dc,2388 +pytz/zoneinfo/Asia/Kabul,sha256=JZEbo8bSj_L7HnXUm2gAUlNlCvJlRJhFkSHCg5o3ggk,194 +pytz/zoneinfo/Asia/Kamchatka,sha256=KY1PlJvRSNkY_5hyJBxj5DDweeYVQaBK05ZgL3kdcCY,1152 +pytz/zoneinfo/Asia/Karachi,sha256=iB-mWMTXUyfBwAkZdz8_UmEw0xsgxIub-KNI7akzhkk,379 +pytz/zoneinfo/Asia/Kashgar,sha256=F1ZOdZZDsVHwDJinksR-hjcqPzqOljvdreZIWFulJxY,151 +pytz/zoneinfo/Asia/Kathmandu,sha256=_RsfeSWbCr8kM4YRJi7Xv6hAEiHW14IFhsXsfhbPjoM,198 +pytz/zoneinfo/Asia/Katmandu,sha256=_RsfeSWbCr8kM4YRJi7Xv6hAEiHW14IFhsXsfhbPjoM,198 +pytz/zoneinfo/Asia/Khandyga,sha256=bKfmw6k5qYDQsEHG3Mv-VYis3YhCeV7qijDxfxQNn_g,1257 +pytz/zoneinfo/Asia/Kolkata,sha256=6Qw0EDbLcgMgDik8s7UTJn4QSjmllPNeGVJU5rwKF88,285 +pytz/zoneinfo/Asia/Krasnoyarsk,sha256=D5KE_1wWSD2YdixDy8n3LBNaAlE1_y3TWXw6NrxFKKA,1193 +pytz/zoneinfo/Asia/Kuala_Lumpur,sha256=XmeVImeqcJ8hJzm7TjAti1nWJAxawOqq7jIzDnHX2hI,401 +pytz/zoneinfo/Asia/Kuching,sha256=D5qtyWJ_SM8bTQeJJIYhqqojxlVKbrFC1EYMDU9GzXQ,469 +pytz/zoneinfo/Asia/Kuwait,sha256=oCKH7uafN8R1o-ijXGoT5U1JZxwvoLzJu_2Cqyi2hUM,151 +pytz/zoneinfo/Asia/Macao,sha256=MvAkRyRsrA2r052ItlyF5bh2FheRjI0jPwg0uIiH2Yk,1227 +pytz/zoneinfo/Asia/Macau,sha256=MvAkRyRsrA2r052ItlyF5bh2FheRjI0jPwg0uIiH2Yk,1227 +pytz/zoneinfo/Asia/Magadan,sha256=HccEEXBQvMmLoC_JE-zP_MlLAZ1WmNLQLfM3tJt55M4,1208 +pytz/zoneinfo/Asia/Makassar,sha256=OhJtCqSTEU-u5n0opBVO5Bu-wQzcYPy9S_6aAhJXgOw,254 +pytz/zoneinfo/Asia/Manila,sha256=8xTSHFQuYVdW3ThdNqiWzVe6Fv75g_5rTQYURLvxrJ4,422 +pytz/zoneinfo/Asia/Muscat,sha256=pmdhPhaJRwKwONvxiZNGeFSICjlWzyY9JlFHv-H9upY,151 +pytz/zoneinfo/Asia/Nicosia,sha256=0Unm0IFT7HyGeQ7F3vTa_-klfysCgrulqFO6BD1plZU,2002 +pytz/zoneinfo/Asia/Novokuznetsk,sha256=pyxxtSUtYDeVmFk0Cg-F33laZS0iKtde9_GJnL9f0KM,1151 +pytz/zoneinfo/Asia/Novosibirsk,sha256=5K2-Gx15ThlHfolyW85S5zREtAcMjeHBYWK4E8x2LdY,1207 +pytz/zoneinfo/Asia/Omsk,sha256=HyXIWItJXBKVHUzWcQPi1Mmd6ZLmZk-QhRUo9Kv2XOI,1193 +pytz/zoneinfo/Asia/Oral,sha256=WQT4qRmC9RI_ll8zB9FvkAL8ezGb8qoqWd75GTlC7kQ,991 +pytz/zoneinfo/Asia/Phnom_Penh,sha256=hf_5PVegQcFSS60CjS80C7h-TGOrfQ4ncm83N8VmZkk,185 +pytz/zoneinfo/Asia/Pontianak,sha256=inOXwuKtjKv1z_eliPZSIqjSt6whtuxhPeG1YpjU_BQ,353 +pytz/zoneinfo/Asia/Pyongyang,sha256=_-g3GnDAtfDX4XAktXH9jFouLUDmOovnjoOfvRpUDsE,237 +pytz/zoneinfo/Asia/Qatar,sha256=wklGY3WPGp-z1OUwb_KOHzRTwBndt1RfDg9Uttt36G4,185 +pytz/zoneinfo/Asia/Qostanay,sha256=HIjln8QIPNRU6MkWzyPi6vDrjlmVZ4XzFxcUHtXMi7s,1025 +pytz/zoneinfo/Asia/Qyzylorda,sha256=JZLNN6NuLkqaWEeVaCZiW_gL6BrIFL9lr65iK7myVPg,1011 +pytz/zoneinfo/Asia/Rangoon,sha256=_YHASq4Z5YcUILIdhEzg27CGLzarUHPDHs1Dj0QgNGM,254 +pytz/zoneinfo/Asia/Riyadh,sha256=oCKH7uafN8R1o-ijXGoT5U1JZxwvoLzJu_2Cqyi2hUM,151 +pytz/zoneinfo/Asia/Saigon,sha256=Lnv1vpUNAXBo8v0b9d9AQpy-AEyO5Qa2Ig0PvDkjrmU,337 +pytz/zoneinfo/Asia/Sakhalin,sha256=xzAor82ihAe-yXEwC6OWiMzo9b6Z-oQl39NIkU5Hhbs,1188 +pytz/zoneinfo/Asia/Samarkand,sha256=zJKSRt3lEvd6Qvg9b49QAyO4cTJyVnTKyPYcyudpHxk,563 +pytz/zoneinfo/Asia/Seoul,sha256=LI9LsV3XcJC0l-KoQf8zI-y7rk-du57erS-N2Ptdi7Q,617 +pytz/zoneinfo/Asia/Shanghai,sha256=ZP_C5DqUQ1oEPAQNHTr36S0DGtx453N68YYbqk7u8-Y,561 +pytz/zoneinfo/Asia/Singapore,sha256=XmeVImeqcJ8hJzm7TjAti1nWJAxawOqq7jIzDnHX2hI,401 +pytz/zoneinfo/Asia/Srednekolymsk,sha256=efaaT8iFHrcccp-VZKNMvtTuPLNjG5V9JH5KKHhH3SI,1194 +pytz/zoneinfo/Asia/Taipei,sha256=DMmQwOpPql25ue3Nf8vAKKT4em06D1Z9rHbLIitxixk,761 +pytz/zoneinfo/Asia/Tashkent,sha256=apRPy251fSRy_ixsg3BOZNmUbHdO86P5-PdgC1Xws7U,577 +pytz/zoneinfo/Asia/Tbilisi,sha256=fT00i6obiTsjCJ01eBaWuRR9BwNPzKAqLMO1_WVX8Es,1007 +pytz/zoneinfo/Asia/Tehran,sha256=Lb2H9BCBXtz819FL6E3gBA7w2ROiIgPgx-f08XpqkVo,1248 +pytz/zoneinfo/Asia/Tel_Aviv,sha256=JUuWQmW5Tha0pJjw61Q5aN7CX0z4D7ops9OOSnda6Dc,2388 +pytz/zoneinfo/Asia/Thimbu,sha256=G2nTQVEMmKlWt0B74_fUAL7KQ3YAu__J6HciiYs2IyU,189 +pytz/zoneinfo/Asia/Thimphu,sha256=G2nTQVEMmKlWt0B74_fUAL7KQ3YAu__J6HciiYs2IyU,189 +pytz/zoneinfo/Asia/Tokyo,sha256=oCueZgRNxcNcX3ZGdif9y6Su4cyVhga4XHdwlcrYLOs,309 +pytz/zoneinfo/Asia/Tomsk,sha256=cr0ULZgWBnQfzDiJeYmqpA7Xo5QRzurvrHsrbZsnhOQ,1207 +pytz/zoneinfo/Asia/Ujung_Pandang,sha256=OhJtCqSTEU-u5n0opBVO5Bu-wQzcYPy9S_6aAhJXgOw,254 +pytz/zoneinfo/Asia/Ulaanbaatar,sha256=qUkXRsTc_u7B90JxULSu7yzKbGtGfKcfEFIasGPC2ec,877 +pytz/zoneinfo/Asia/Ulan_Bator,sha256=qUkXRsTc_u7B90JxULSu7yzKbGtGfKcfEFIasGPC2ec,877 +pytz/zoneinfo/Asia/Urumqi,sha256=F1ZOdZZDsVHwDJinksR-hjcqPzqOljvdreZIWFulJxY,151 +pytz/zoneinfo/Asia/Ust-Nera,sha256=zsG8kgnw0Fcs5N2WwNTVmvWkTlpwf7Oo8y68HcXjYyw,1238 +pytz/zoneinfo/Asia/Vientiane,sha256=hf_5PVegQcFSS60CjS80C7h-TGOrfQ4ncm83N8VmZkk,185 +pytz/zoneinfo/Asia/Vladivostok,sha256=XMQLMh5SPbI6C4R3UO4KhbnG4hWVkHNedzCQeqxFk6A,1194 +pytz/zoneinfo/Asia/Yakutsk,sha256=PPNrRGgg9jefOUM-6M8XqaIm-ElfmRZSWAtSGKLzNXQ,1193 +pytz/zoneinfo/Asia/Yangon,sha256=_YHASq4Z5YcUILIdhEzg27CGLzarUHPDHs1Dj0QgNGM,254 +pytz/zoneinfo/Asia/Yekaterinburg,sha256=4NyEW6Xjr4UsWPh63HIPI4G6GT_tVG1Xkgc2xbwGjzA,1229 +pytz/zoneinfo/Asia/Yerevan,sha256=FM0pUA4NbTWBb_CsJ5KCLVrLoNmad7njBKqFrJBDoxE,1137 +pytz/zoneinfo/Atlantic/Azores,sha256=66hDxaK8xFnktLMrpNxkD4r1gGkhS-PEpleuwzuGRA0,3442 +pytz/zoneinfo/Atlantic/Bermuda,sha256=LNGKfMsnYvwImjTyzXrLhMOHHDu7qI67RbYNKvvI15I,2396 +pytz/zoneinfo/Atlantic/Canary,sha256=ymK9ufqphvNjDK3hzikN4GfkcR3QeCBiPKyVc6FjlbA,1897 +pytz/zoneinfo/Atlantic/Cape_Verde,sha256=o92pLdLFX_b9vUiq3rNpca4tupIO3dx9rNrnPcA8474,256 +pytz/zoneinfo/Atlantic/Faeroe,sha256=NibdZPZtapnYR_myIZnMdTaSKGsOBGgujj0_T2NvAzs,1815 +pytz/zoneinfo/Atlantic/Faroe,sha256=NibdZPZtapnYR_myIZnMdTaSKGsOBGgujj0_T2NvAzs,1815 +pytz/zoneinfo/Atlantic/Jan_Mayen,sha256=XuR19xoPwaMvrrhJ-MOcbnqmbW1B7HQrl7OnQ2s7BwE,2298 +pytz/zoneinfo/Atlantic/Madeira,sha256=lYY85MC5-GUKExm353ixwtZDxasYavTTWELvv5RXLxE,3377 +pytz/zoneinfo/Atlantic/Reykjavik,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Atlantic/South_Georgia,sha256=I9SAcPPumy6Xf9P7dg2aE16oxwDIqyKFqinJTC-XsgM,150 +pytz/zoneinfo/Atlantic/St_Helena,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Atlantic/Stanley,sha256=siEjXTAuTum_4XGtS98MBE34XW_5xgXShEX5OMnSFjo,1200 +pytz/zoneinfo/Australia/ACT,sha256=QsOFdYWxbbL4_9R7oZ-qYPRzNA3o1P6TIOp76GFgWQY,2190 +pytz/zoneinfo/Australia/Adelaide,sha256=ld2EbxU75oVgmPe703z-I6aqLg0Kmv62ZcCGzkT5R20,2208 +pytz/zoneinfo/Australia/Brisbane,sha256=eW6Qzze2t0-speJmmvt1JMzbkSadIKdE84XHc7JUtGc,419 +pytz/zoneinfo/Australia/Broken_Hill,sha256=3k_3ljTvS5GSfo7Xh6w71UgR3aAwYPBsnCJ-mlEYCqQ,2229 +pytz/zoneinfo/Australia/Canberra,sha256=QsOFdYWxbbL4_9R7oZ-qYPRzNA3o1P6TIOp76GFgWQY,2190 +pytz/zoneinfo/Australia/Currie,sha256=GLQSzgIfsWxOvmKOrhpfofWqINQf6h36NYy3mcq6gcg,2358 +pytz/zoneinfo/Australia/Darwin,sha256=fn0IZhIW98FAnzLig-_GBtW5LA54jajdeeUzg4tCGvo,325 +pytz/zoneinfo/Australia/Eucla,sha256=i1-XGG8I6E0dXIdWGF4DlkfDLWhiAxJ_3gMpt-nm_u4,456 +pytz/zoneinfo/Australia/Hobart,sha256=GLQSzgIfsWxOvmKOrhpfofWqINQf6h36NYy3mcq6gcg,2358 +pytz/zoneinfo/Australia/LHI,sha256=oyPFQzmRqWPrSXt9pNHQmEi_PvX11k2clknziOS6ud8,1846 +pytz/zoneinfo/Australia/Lindeman,sha256=xM6Udx22oLNoLR1Y7GQhHOYov8nw3xQNqgc_NVQ2JK4,475 +pytz/zoneinfo/Australia/Lord_Howe,sha256=oyPFQzmRqWPrSXt9pNHQmEi_PvX11k2clknziOS6ud8,1846 +pytz/zoneinfo/Australia/Melbourne,sha256=lvx_MQcunMc6u2smIrl8X427bLsXvjkgpCSdjYCTNBM,2190 +pytz/zoneinfo/Australia/NSW,sha256=QsOFdYWxbbL4_9R7oZ-qYPRzNA3o1P6TIOp76GFgWQY,2190 +pytz/zoneinfo/Australia/North,sha256=fn0IZhIW98FAnzLig-_GBtW5LA54jajdeeUzg4tCGvo,325 +pytz/zoneinfo/Australia/Perth,sha256=Al1DOUh4U_ofMUQSeVlzSyD3x7SUjP9dchSaBUGmeWg,446 +pytz/zoneinfo/Australia/Queensland,sha256=eW6Qzze2t0-speJmmvt1JMzbkSadIKdE84XHc7JUtGc,419 +pytz/zoneinfo/Australia/South,sha256=ld2EbxU75oVgmPe703z-I6aqLg0Kmv62ZcCGzkT5R20,2208 +pytz/zoneinfo/Australia/Sydney,sha256=QsOFdYWxbbL4_9R7oZ-qYPRzNA3o1P6TIOp76GFgWQY,2190 +pytz/zoneinfo/Australia/Tasmania,sha256=GLQSzgIfsWxOvmKOrhpfofWqINQf6h36NYy3mcq6gcg,2358 +pytz/zoneinfo/Australia/Victoria,sha256=lvx_MQcunMc6u2smIrl8X427bLsXvjkgpCSdjYCTNBM,2190 +pytz/zoneinfo/Australia/West,sha256=Al1DOUh4U_ofMUQSeVlzSyD3x7SUjP9dchSaBUGmeWg,446 +pytz/zoneinfo/Australia/Yancowinna,sha256=3k_3ljTvS5GSfo7Xh6w71UgR3aAwYPBsnCJ-mlEYCqQ,2229 +pytz/zoneinfo/Brazil/Acre,sha256=0gpJUl46hQbp0P6Xj1S0NArIWeAryuuDXjsldvB5GHE,614 +pytz/zoneinfo/Brazil/DeNoronha,sha256=feeRAijQqKylZgqe84nKhsFLycT5zIBm7mLIvdyGw4w,702 +pytz/zoneinfo/Brazil/East,sha256=BMBnRO4_4HjvO4t3njjrMGZr-ZPmegkvyvL8KPY6ZM4,1430 +pytz/zoneinfo/Brazil/West,sha256=F6RLOOeOi9lymZiQmQ9pR8tFpPZ6EguNdPfOc6BhXDE,590 +pytz/zoneinfo/CET,sha256=gS9Vrrbozend9HhuFetCVrIegs9fXSjaG60X2UVwysA,2933 +pytz/zoneinfo/CST6CDT,sha256=_roybr6I6sIAF6cYdIxGxoRpoef153Fty48dQ6bm9oY,3592 +pytz/zoneinfo/Canada/Atlantic,sha256=TZpmc5PwWoLfTfQoQ_b3U17BE2iVKSeNkR0Ho8mbTn8,3424 +pytz/zoneinfo/Canada/Central,sha256=7P-_YQrneFcon7QKSTOnkiGjEppFDn3Z48MJ1qq8VBw,2868 +pytz/zoneinfo/Canada/Eastern,sha256=pYehoWB0Ofe6woPhgV8r26-5ZJpFPRjgbC5E5pltiI8,3494 +pytz/zoneinfo/Canada/Mountain,sha256=-TkIfc3QlvaCf0p8COZ43Y1HRBAl-nARUi-JdXeK1vE,2332 +pytz/zoneinfo/Canada/Newfoundland,sha256=r1-17uKv27eZ3JsVkw_DLZQbo6wvjuuVu7C2pDsmOgI,3655 +pytz/zoneinfo/Canada/Pacific,sha256=sknKH0jSPWam-DHfM35qXs8Nam7d5TFlkUI9Sgxryyg,2892 +pytz/zoneinfo/Canada/Saskatchewan,sha256=yjqT08pHbICYe83H8JmtaDBvCFqRv7Tfze3Y8xuXukw,980 +pytz/zoneinfo/Canada/Yukon,sha256=TrR6PCnYG-mSClBMohqlP8qnYhXMUsydI-L-quXFxyM,1614 +pytz/zoneinfo/Chile/Continental,sha256=0CDw13dCMUsoquMupoJgupkzAUNhDK6E0lVxURA7osA,2515 +pytz/zoneinfo/Chile/EasterIsland,sha256=QbubBs_xQlvKweAnurhyHjIK4ji77Gh4G-usXul6XVM,2219 +pytz/zoneinfo/Cuba,sha256=HUQeAuKBsEkI5SLZjqynXICOUVOajkKzKH5r-Ov5Odc,2416 +pytz/zoneinfo/EET,sha256=XDY-FBUddRyQHN8GxQLZ4awjuOlWlzlUdjv7OdXFNzA,2262 +pytz/zoneinfo/EST,sha256=kayA_pdpMcSQ0FjIzotdcf-m1JYfbKE-qcFT8LC8zqA,182 +pytz/zoneinfo/EST5EDT,sha256=6e0H177gx2qdRC0JHvHwFmj-58TyYBTAqGixn-bBipU,3552 +pytz/zoneinfo/Egypt,sha256=Lft-GCLQhaSJm9VqUmsEFoHIS1Vhfa7pFJn9GZCpifs,2399 +pytz/zoneinfo/Eire,sha256=QOjSocO1cihNo59vQkWxvIFPRSxE9apz0KARVx1czEM,3492 +pytz/zoneinfo/Etc/GMT,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/Etc/GMT+0,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/Etc/GMT+1,sha256=1Qzl2X9rQ_RXEf11yH09wQZCr_ph6UdFP7E0yu9s-IQ,116 +pytz/zoneinfo/Etc/GMT+10,sha256=JEQyQyQlkC0o6ZTdeVjZhCIOh6cK5TF7H00Pkls-sUI,117 +pytz/zoneinfo/Etc/GMT+11,sha256=tWvcvYMFCaE60nJVvDrrov7stJvs1KQYOyrhl3dzcUs,117 +pytz/zoneinfo/Etc/GMT+12,sha256=b70HEhErq8IJmq8x7cOZy4eR__3fq5uHHpjvPBEHqMA,117 +pytz/zoneinfo/Etc/GMT+2,sha256=T6Ep5zhslBKbYaECFUB6gUKh3iTZPyMoW1kjhonxrUo,116 +pytz/zoneinfo/Etc/GMT+3,sha256=QGoYrE04bUJ-OzL37dt2MZT5FxWNLpJDPVXgJbstYZA,116 +pytz/zoneinfo/Etc/GMT+4,sha256=RWrkNki-wV7X-coe0VvufBe6LrWVpkPJgia5QQYEnBo,116 +pytz/zoneinfo/Etc/GMT+5,sha256=oRmeC41dgYXT-zzyZIRKXN9IvdL2Da5nTuwmG2_prIA,116 +pytz/zoneinfo/Etc/GMT+6,sha256=d6dAnwiejyFI2n7AzFlFW0aFAT6zYNEjBIEG0uu0sbQ,116 +pytz/zoneinfo/Etc/GMT+7,sha256=TqjYbzd0YHpx1wisFg08J19wTpg6ztJLLongZY_lozs,116 +pytz/zoneinfo/Etc/GMT+8,sha256=th_8bIMmYgRPCesBrbmBhRr0jQO7whd70LiY9HfwJyk,116 +pytz/zoneinfo/Etc/GMT+9,sha256=Qq5E6iUS7JMJIymT7YoqlI8MtqtVy0mr9t6zWFtWc9Y,116 +pytz/zoneinfo/Etc/GMT-0,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/Etc/GMT-1,sha256=73F1eU8uAQGP3mcoB2q99CjfManGFHk3fefljp9pYC4,117 +pytz/zoneinfo/Etc/GMT-10,sha256=fKWWNwLBOp1OkKjtc1w9LIXJR1mTTD-JdvYflRy1IrU,118 +pytz/zoneinfo/Etc/GMT-11,sha256=D2S79n6psa9t9_2vj5wIrFpHH2OJLcCKP6vtwzFZINY,118 +pytz/zoneinfo/Etc/GMT-12,sha256=me4V6lmWI8gSr8H7N41WAD0Eww1anh_EF34Qr9UoSnI,118 +pytz/zoneinfo/Etc/GMT-13,sha256=xbmbG1BQA6Dlpa_iUwEGyJxW4a3t6lmawdPKAE8vbR8,118 +pytz/zoneinfo/Etc/GMT-14,sha256=PpXoREBh02qFpvxVMj2pV9IAzSQvBE7XPvnN9qSZ-Kc,118 +pytz/zoneinfo/Etc/GMT-2,sha256=ve6hWLdeuiLhqagaWLqMD6HNybS1chRwjudfTZ2bYBE,117 +pytz/zoneinfo/Etc/GMT-3,sha256=N77jILanuLDVkLsdujXZSu-dsHiwN5MIpwh7fMUifso,117 +pytz/zoneinfo/Etc/GMT-4,sha256=LSko5fVHqPl5zfwjGqkbMa_OFnvtpT6o_4xYxNz9n5o,117 +pytz/zoneinfo/Etc/GMT-5,sha256=uLaSR5Mb18HRTsAA5SveY9PAJ97dO8QzIWqNXe3wZb4,117 +pytz/zoneinfo/Etc/GMT-6,sha256=JSN-RUAphJ50fpIv7cYC6unrtrz9S1Wma-piDHlGe7c,117 +pytz/zoneinfo/Etc/GMT-7,sha256=vVAOF8xU9T9ESnw68c0SFXpcvkoopaiwTR0zbefHHSU,117 +pytz/zoneinfo/Etc/GMT-8,sha256=S7xFQbFMpiDZy4v5L4D9fCrjRIzzoLC5p8Se23xi7us,117 +pytz/zoneinfo/Etc/GMT-9,sha256=I5vHNmUK-Yyg_S1skFN44VGVzBgktjFgVQiDIKO4aMI,117 +pytz/zoneinfo/Etc/GMT0,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/Etc/Greenwich,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/Etc/UCT,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/Etc/UTC,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/Etc/Universal,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/Etc/Zulu,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/Europe/Amsterdam,sha256=gS9Vrrbozend9HhuFetCVrIegs9fXSjaG60X2UVwysA,2933 +pytz/zoneinfo/Europe/Andorra,sha256=gTB5jCQmvIw3JJi1_vAcOYuhtzPBR6RXUx9gVV6p6ug,1742 +pytz/zoneinfo/Europe/Astrakhan,sha256=ZeGDZjwVVRoeR-J642zEnN26BPL58ViTJLbwnk7pLXk,1151 +pytz/zoneinfo/Europe/Athens,sha256=XDY-FBUddRyQHN8GxQLZ4awjuOlWlzlUdjv7OdXFNzA,2262 +pytz/zoneinfo/Europe/Belfast,sha256=yFSVBw3KQmh99qHD7ngKJ8vLgvGER1Dqb2QoM6RNKbQ,3664 +pytz/zoneinfo/Europe/Belgrade,sha256=OpWtsGFWBE_S-mYoQcAmjCta9HwbGQANnSmVY9OHCTo,1920 +pytz/zoneinfo/Europe/Berlin,sha256=XuR19xoPwaMvrrhJ-MOcbnqmbW1B7HQrl7OnQ2s7BwE,2298 +pytz/zoneinfo/Europe/Bratislava,sha256=G9fdhUXmzx651BnyZ6V7AOYIV9EV5aMJMm44eJaLLZw,2301 +pytz/zoneinfo/Europe/Brussels,sha256=gS9Vrrbozend9HhuFetCVrIegs9fXSjaG60X2UVwysA,2933 +pytz/zoneinfo/Europe/Bucharest,sha256=nfg6-bU2D6DMEWb9EMIBR5kxnNsbDSx0UKfHH_ZzqFc,2184 +pytz/zoneinfo/Europe/Budapest,sha256=lNwqxWciBvw9ei81VQwIKHbC_ZDJjpgHU6HFg4wCUkY,2368 +pytz/zoneinfo/Europe/Busingen,sha256=K5QY7Ujj2VUchKR4bhhb0hgdAJhmwED71ykXDQOGKe8,1909 +pytz/zoneinfo/Europe/Chisinau,sha256=e0lBroLteVj4iX0Zi_k358z1RgBlysonKOKkccs-nZM,2424 +pytz/zoneinfo/Europe/Copenhagen,sha256=XuR19xoPwaMvrrhJ-MOcbnqmbW1B7HQrl7OnQ2s7BwE,2298 +pytz/zoneinfo/Europe/Dublin,sha256=QOjSocO1cihNo59vQkWxvIFPRSxE9apz0KARVx1czEM,3492 +pytz/zoneinfo/Europe/Gibraltar,sha256=a87WpaBlvxI4gAU9OpQOkN8VUJbirVWYf-VfFLTIoS4,3068 +pytz/zoneinfo/Europe/Guernsey,sha256=yFSVBw3KQmh99qHD7ngKJ8vLgvGER1Dqb2QoM6RNKbQ,3664 +pytz/zoneinfo/Europe/Helsinki,sha256=GEkB7LsVhmegt7YuuWheCDvDGC7b7Nw9bTdDGS9qkJc,1900 +pytz/zoneinfo/Europe/Isle_of_Man,sha256=yFSVBw3KQmh99qHD7ngKJ8vLgvGER1Dqb2QoM6RNKbQ,3664 +pytz/zoneinfo/Europe/Istanbul,sha256=Jk4wjndDta_uLWc8W1dWdjbavJJbsL5ROTmZboVnGKU,1933 +pytz/zoneinfo/Europe/Jersey,sha256=yFSVBw3KQmh99qHD7ngKJ8vLgvGER1Dqb2QoM6RNKbQ,3664 +pytz/zoneinfo/Europe/Kaliningrad,sha256=s7GXSe1YvMcs7AiUhHNTA6I4nAOQn_Kmz_ZqJYO-LMM,1493 +pytz/zoneinfo/Europe/Kiev,sha256=-wrpG9jPuIKFP1NgBVvnxsMRf9L_h5z3J6Q3jj1AwNM,2120 +pytz/zoneinfo/Europe/Kirov,sha256=P7T2Zf5Eo6o4L4Dbg_BfiFjUgTj0dQXlrwY-QZ1eBVk,1185 +pytz/zoneinfo/Europe/Kyiv,sha256=-wrpG9jPuIKFP1NgBVvnxsMRf9L_h5z3J6Q3jj1AwNM,2120 +pytz/zoneinfo/Europe/Lisbon,sha256=krB8skaJImv5NDCNHxvTPDBqpNphDFLNW84lB3lgUCw,3527 +pytz/zoneinfo/Europe/Ljubljana,sha256=OpWtsGFWBE_S-mYoQcAmjCta9HwbGQANnSmVY9OHCTo,1920 +pytz/zoneinfo/Europe/London,sha256=yFSVBw3KQmh99qHD7ngKJ8vLgvGER1Dqb2QoM6RNKbQ,3664 +pytz/zoneinfo/Europe/Luxembourg,sha256=gS9Vrrbozend9HhuFetCVrIegs9fXSjaG60X2UVwysA,2933 +pytz/zoneinfo/Europe/Madrid,sha256=mkLX03rW3t0tmzKBIPe_noUvaFDErwC6_5ZPZZsWHOo,2614 +pytz/zoneinfo/Europe/Malta,sha256=EhKcbPL47765tWAiQ57cusaK2TaIQqZCgtJoEZs3Ud0,2620 +pytz/zoneinfo/Europe/Mariehamn,sha256=GEkB7LsVhmegt7YuuWheCDvDGC7b7Nw9bTdDGS9qkJc,1900 +pytz/zoneinfo/Europe/Minsk,sha256=KgPm0fHycntgd3xbTmmDl4O13Xh_9e2zUnd8XFSU29o,1307 +pytz/zoneinfo/Europe/Monaco,sha256=q3ehSIot1GZ6TyMHIjbg0oRf4ghAXuwbSDSYVim6evg,2962 +pytz/zoneinfo/Europe/Moscow,sha256=KmkofRcj6T8Ph28PJChm8JVp13uRvef6TZ0GuPzUiDw,1535 +pytz/zoneinfo/Europe/Nicosia,sha256=0Unm0IFT7HyGeQ7F3vTa_-klfysCgrulqFO6BD1plZU,2002 +pytz/zoneinfo/Europe/Oslo,sha256=XuR19xoPwaMvrrhJ-MOcbnqmbW1B7HQrl7OnQ2s7BwE,2298 +pytz/zoneinfo/Europe/Paris,sha256=q3ehSIot1GZ6TyMHIjbg0oRf4ghAXuwbSDSYVim6evg,2962 +pytz/zoneinfo/Europe/Podgorica,sha256=OpWtsGFWBE_S-mYoQcAmjCta9HwbGQANnSmVY9OHCTo,1920 +pytz/zoneinfo/Europe/Prague,sha256=G9fdhUXmzx651BnyZ6V7AOYIV9EV5aMJMm44eJaLLZw,2301 +pytz/zoneinfo/Europe/Riga,sha256=hJ2_0m1taW9IuA-hMyP5n-WX7YOrR0heKszJhgljRWk,2198 +pytz/zoneinfo/Europe/Rome,sha256=1a3oLMSiMpSbh9QxV8hLLDVbZqash89iUO1urYC1AY8,2641 +pytz/zoneinfo/Europe/Samara,sha256=nXL0IxbT6qu10CNuaDHxx4W1OaAnaaKTtIJ9N9URMoU,1201 +pytz/zoneinfo/Europe/San_Marino,sha256=1a3oLMSiMpSbh9QxV8hLLDVbZqash89iUO1urYC1AY8,2641 +pytz/zoneinfo/Europe/Sarajevo,sha256=OpWtsGFWBE_S-mYoQcAmjCta9HwbGQANnSmVY9OHCTo,1920 +pytz/zoneinfo/Europe/Saratov,sha256=ygwjvXN13TgaWxjg6ysWEnHWNxwrVtkEbrk8t9bzVVw,1169 +pytz/zoneinfo/Europe/Simferopol,sha256=tzl7xdNVSZprNCul4YE5LSpoR9JoujmOq8VbbB8wHic,1469 +pytz/zoneinfo/Europe/Skopje,sha256=OpWtsGFWBE_S-mYoQcAmjCta9HwbGQANnSmVY9OHCTo,1920 +pytz/zoneinfo/Europe/Sofia,sha256=hCQKXfMNrnA5xHNw_uzTjKzVw4-Bvsq5oGO4yUCv5tY,2077 +pytz/zoneinfo/Europe/Stockholm,sha256=XuR19xoPwaMvrrhJ-MOcbnqmbW1B7HQrl7OnQ2s7BwE,2298 +pytz/zoneinfo/Europe/Tallinn,sha256=4a6JC0aIpMzqIV7O35zoG0LLJwkQq5AoXZ2ivkic6-w,2148 +pytz/zoneinfo/Europe/Tirane,sha256=ztlZyCS9WCXeVW8nBun3Tyi5HUY0EtFbiBbEc1gucuw,2084 +pytz/zoneinfo/Europe/Tiraspol,sha256=e0lBroLteVj4iX0Zi_k358z1RgBlysonKOKkccs-nZM,2424 +pytz/zoneinfo/Europe/Ulyanovsk,sha256=c8Ad5p7CKj_1cCA7lVRpcPqbQXGYaX83cuu6uIFx-Bg,1253 +pytz/zoneinfo/Europe/Uzhgorod,sha256=-wrpG9jPuIKFP1NgBVvnxsMRf9L_h5z3J6Q3jj1AwNM,2120 +pytz/zoneinfo/Europe/Vaduz,sha256=K5QY7Ujj2VUchKR4bhhb0hgdAJhmwED71ykXDQOGKe8,1909 +pytz/zoneinfo/Europe/Vatican,sha256=1a3oLMSiMpSbh9QxV8hLLDVbZqash89iUO1urYC1AY8,2641 +pytz/zoneinfo/Europe/Vienna,sha256=ZmI3kADE6bnrJEccqh73XXBY36L1G4DkpiTQImtNrUk,2200 +pytz/zoneinfo/Europe/Vilnius,sha256=UFzRX3orCTB8d9IzlxJPy5eUA2oBPuCu1UJl-2D7C3U,2162 +pytz/zoneinfo/Europe/Volgograd,sha256=RgFvt7mzZ-TtIKL9BVHmoNZLIeLIuiDdXeY10g2_vks,1193 +pytz/zoneinfo/Europe/Warsaw,sha256=TiLDPbeVF0ckgLVEkaSeDaKZ8wctdJDOl_HE_Wd5rKs,2654 +pytz/zoneinfo/Europe/Zagreb,sha256=OpWtsGFWBE_S-mYoQcAmjCta9HwbGQANnSmVY9OHCTo,1920 +pytz/zoneinfo/Europe/Zaporozhye,sha256=-wrpG9jPuIKFP1NgBVvnxsMRf9L_h5z3J6Q3jj1AwNM,2120 +pytz/zoneinfo/Europe/Zurich,sha256=K5QY7Ujj2VUchKR4bhhb0hgdAJhmwED71ykXDQOGKe8,1909 +pytz/zoneinfo/Factory,sha256=aFFlKx93HXoJoF4SSuTlD8cZtJA-ne5oKzAa6eX2V4k,116 +pytz/zoneinfo/GB,sha256=yFSVBw3KQmh99qHD7ngKJ8vLgvGER1Dqb2QoM6RNKbQ,3664 +pytz/zoneinfo/GB-Eire,sha256=yFSVBw3KQmh99qHD7ngKJ8vLgvGER1Dqb2QoM6RNKbQ,3664 +pytz/zoneinfo/GMT,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/GMT+0,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/GMT-0,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/GMT0,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/Greenwich,sha256=bZ83iIPAefhsA4elVHqSxEmGnYBuB94QCEqwTwJJAY0,114 +pytz/zoneinfo/HST,sha256=fwPRv1Jk56sCOi75uZfd_Iy2k2aSQHx3B2K5xUlSPzM,329 +pytz/zoneinfo/Hongkong,sha256=al_O4kPlq5JpgkLYjEaZzrcgiiLul9NC0R5B69JVWhc,1233 +pytz/zoneinfo/Iceland,sha256=0u-sTl8j2IyV1ywdtCgHFw9S9D3ZiiBa9akqkbny2Zc,148 +pytz/zoneinfo/Indian/Antananarivo,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Indian/Chagos,sha256=2errXzKdFIcpU0L-XRhSHxhNabIzbI5lXV3Pq6lt40Y,185 +pytz/zoneinfo/Indian/Christmas,sha256=hf_5PVegQcFSS60CjS80C7h-TGOrfQ4ncm83N8VmZkk,185 +pytz/zoneinfo/Indian/Cocos,sha256=_YHASq4Z5YcUILIdhEzg27CGLzarUHPDHs1Dj0QgNGM,254 +pytz/zoneinfo/Indian/Comoro,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Indian/Kerguelen,sha256=F73ffVfBoUoHre0-DwsiQrYJcLpPOW-JJGk3n88lM5U,185 +pytz/zoneinfo/Indian/Mahe,sha256=pmdhPhaJRwKwONvxiZNGeFSICjlWzyY9JlFHv-H9upY,151 +pytz/zoneinfo/Indian/Maldives,sha256=F73ffVfBoUoHre0-DwsiQrYJcLpPOW-JJGk3n88lM5U,185 +pytz/zoneinfo/Indian/Mauritius,sha256=Znqrc1chimlciJsYBOl0NvIHnrNdCxncGxWczq1PBeI,227 +pytz/zoneinfo/Indian/Mayotte,sha256=yJsuJTqJJqbOz37_NOS_zbf-JNr_IthHGMMN7sDqSWg,265 +pytz/zoneinfo/Indian/Reunion,sha256=pmdhPhaJRwKwONvxiZNGeFSICjlWzyY9JlFHv-H9upY,151 +pytz/zoneinfo/Iran,sha256=Lb2H9BCBXtz819FL6E3gBA7w2ROiIgPgx-f08XpqkVo,1248 +pytz/zoneinfo/Israel,sha256=JUuWQmW5Tha0pJjw61Q5aN7CX0z4D7ops9OOSnda6Dc,2388 +pytz/zoneinfo/Jamaica,sha256=wlagieUPRf5-beie-h7QsONbNzjGsm8vMs8uf28pw28,482 +pytz/zoneinfo/Japan,sha256=oCueZgRNxcNcX3ZGdif9y6Su4cyVhga4XHdwlcrYLOs,309 +pytz/zoneinfo/Kwajalein,sha256=TmZ_0f-ySQ-saBAlRXV0f49Itwne51VBXn6rWcrWqHQ,302 +pytz/zoneinfo/Libya,sha256=W1dptGD70T7ppGoo0fczFQeDiIp0nultLNPV66MwB2c,625 +pytz/zoneinfo/MET,sha256=gS9Vrrbozend9HhuFetCVrIegs9fXSjaG60X2UVwysA,2933 +pytz/zoneinfo/MST,sha256=illz0sYuLL8lIPK0Tkou6dL0Vck_D0W_3rRTOvFYRmQ,360 +pytz/zoneinfo/MST7MDT,sha256=MugZwApDs8NI9TnXANQlUE8guNBowWQY0m-ptpPndck,2460 +pytz/zoneinfo/Mexico/BajaNorte,sha256=jC57Mhcm5jRZEto5Z5a9s2cr_EvRqRxl7lizjgBNTKU,2906 +pytz/zoneinfo/Mexico/BajaSur,sha256=BWH2NqVPA1PsyELPN_2BF8KllrsmQkqg1eujsQvnnx8,1060 +pytz/zoneinfo/Mexico/General,sha256=Uog2-FMWz2o12jR6sK9vemJamLeo6OEFMQR3s0xTxkc,1222 +pytz/zoneinfo/NZ,sha256=gADjoyPo_QISQU6UJrAgcHp3HDaMoOFRdH-d23uBSyc,2437 +pytz/zoneinfo/NZ-CHAT,sha256=xhexVc5lfJ_qAv2d3HrII6lfRSxKZYBAjY2zpYkCGE8,2054 +pytz/zoneinfo/Navajo,sha256=MugZwApDs8NI9TnXANQlUE8guNBowWQY0m-ptpPndck,2460 +pytz/zoneinfo/PRC,sha256=ZP_C5DqUQ1oEPAQNHTr36S0DGtx453N68YYbqk7u8-Y,561 +pytz/zoneinfo/PST8PDT,sha256=aJd7ua1tGG_vxser02AQpm4wAI3LLTdgh6QcSYYecmg,2852 +pytz/zoneinfo/Pacific/Apia,sha256=M3QKsp75Q7H1X3aeE_9ZqQli9aEkNCCQctZQ5sEKu00,598 +pytz/zoneinfo/Pacific/Auckland,sha256=gADjoyPo_QISQU6UJrAgcHp3HDaMoOFRdH-d23uBSyc,2437 +pytz/zoneinfo/Pacific/Bougainville,sha256=hWE86eXnNx-vABbp7-YSIqWyecHPMIWLftVloAoPhL8,254 +pytz/zoneinfo/Pacific/Chatham,sha256=xhexVc5lfJ_qAv2d3HrII6lfRSxKZYBAjY2zpYkCGE8,2054 +pytz/zoneinfo/Pacific/Chuuk,sha256=nB36HBWZTdh3TlP0DLFNz1KRQ0aHIfHbp7LC4Urp9fA,172 +pytz/zoneinfo/Pacific/Easter,sha256=QbubBs_xQlvKweAnurhyHjIK4ji77Gh4G-usXul6XVM,2219 +pytz/zoneinfo/Pacific/Efate,sha256=oSxNcQYx5-1FU2_yHzHI-hT-dMJcPxzy4XmdI1UxXAo,524 +pytz/zoneinfo/Pacific/Enderbury,sha256=HNTAKrsH_R2W3QRlKcmNld5KcXdP0ygXCjEovc1i-6Q,220 +pytz/zoneinfo/Pacific/Fakaofo,sha256=qOodpTMKjztvZIXVLe_f_kZ6WcHl9fCLE9ZsyvdFKLI,186 +pytz/zoneinfo/Pacific/Fiji,sha256=jB5FbOsCnHVQQ2ohPiWEQUPhG6JybB3Nog3qT6WJQ0I,564 +pytz/zoneinfo/Pacific/Funafuti,sha256=UyaKimsR8LjgL8Z2g65I0HTvr3tMZuA2wUeBB6_Zp9c,152 +pytz/zoneinfo/Pacific/Galapagos,sha256=_GJUYOjSiIjoNBO2qdq23isLMJ4NCVk3DKIRGeDc8BA,224 +pytz/zoneinfo/Pacific/Gambier,sha256=gAS7gr1HH_re0uYnL6eWo5KGJ-B5QaiM8mV2cY5mQxE,150 +pytz/zoneinfo/Pacific/Guadalcanal,sha256=M4kTWqaSQaV1AMhyLSvmwoBJF7X9icrILbvQJwp940g,152 +pytz/zoneinfo/Pacific/Guam,sha256=Ex9znmf6rNfGze6gNpZJCMr1TT4rkl2SnrhecrdJufI,494 +pytz/zoneinfo/Pacific/Honolulu,sha256=fwPRv1Jk56sCOi75uZfd_Iy2k2aSQHx3B2K5xUlSPzM,329 +pytz/zoneinfo/Pacific/Johnston,sha256=fwPRv1Jk56sCOi75uZfd_Iy2k2aSQHx3B2K5xUlSPzM,329 +pytz/zoneinfo/Pacific/Kanton,sha256=HNTAKrsH_R2W3QRlKcmNld5KcXdP0ygXCjEovc1i-6Q,220 +pytz/zoneinfo/Pacific/Kiritimati,sha256=hYk1Ooz-Lj1PuZCbNV2WJIvOLtCwSwq2u63cb1Z-3NQ,224 +pytz/zoneinfo/Pacific/Kosrae,sha256=Q0jrb4zeDrd61bU4V8TqjMc0Iep8rWZyZqJ0uqsunxs,337 +pytz/zoneinfo/Pacific/Kwajalein,sha256=TmZ_0f-ySQ-saBAlRXV0f49Itwne51VBXn6rWcrWqHQ,302 +pytz/zoneinfo/Pacific/Majuro,sha256=UyaKimsR8LjgL8Z2g65I0HTvr3tMZuA2wUeBB6_Zp9c,152 +pytz/zoneinfo/Pacific/Marquesas,sha256=FTxPJTWtk48LVb3N2U64KLpLsmvu0DQBubTCg-dvyGM,159 +pytz/zoneinfo/Pacific/Midway,sha256=fCYrYphYY6rUfxOw712y5cyRe104AC3pouqD3bCINFg,175 +pytz/zoneinfo/Pacific/Nauru,sha256=9ASKgLHB-8nsTEK1ApzfTH0yQtbNAmGX-JI7uHZiqnA,238 +pytz/zoneinfo/Pacific/Niue,sha256=OllXxukncR7a-SMmdFox5az1xpIPMhbahQhtObmpuDM,189 +pytz/zoneinfo/Pacific/Norfolk,sha256=DMdX1Bm18lzNuiCWzwfeHUMRGXPS8v5AWnh-_EX_AZw,866 +pytz/zoneinfo/Pacific/Noumea,sha256=tkHxxnxsXTOqz3YzWi0mkhTCIONzg-W7EpSRMdPjKdQ,290 +pytz/zoneinfo/Pacific/Pago_Pago,sha256=fCYrYphYY6rUfxOw712y5cyRe104AC3pouqD3bCINFg,175 +pytz/zoneinfo/Pacific/Palau,sha256=aN2HbT0reqwKrtLKDK9M2zb0d0ikdNlTrrntVxdH66o,166 +pytz/zoneinfo/Pacific/Pitcairn,sha256=U4jAUuvsRNoy8XrPa16YpcXCcqHJY0u6JvCNgPEWO1c,188 +pytz/zoneinfo/Pacific/Pohnpei,sha256=M4kTWqaSQaV1AMhyLSvmwoBJF7X9icrILbvQJwp940g,152 +pytz/zoneinfo/Pacific/Ponape,sha256=M4kTWqaSQaV1AMhyLSvmwoBJF7X9icrILbvQJwp940g,152 +pytz/zoneinfo/Pacific/Port_Moresby,sha256=nB36HBWZTdh3TlP0DLFNz1KRQ0aHIfHbp7LC4Urp9fA,172 +pytz/zoneinfo/Pacific/Rarotonga,sha256=wPEsoXbyDnuhfzkgLvUqhSzrMx_FD42uAPluSPMh3Bc,589 +pytz/zoneinfo/Pacific/Saipan,sha256=Ex9znmf6rNfGze6gNpZJCMr1TT4rkl2SnrhecrdJufI,494 +pytz/zoneinfo/Pacific/Samoa,sha256=fCYrYphYY6rUfxOw712y5cyRe104AC3pouqD3bCINFg,175 +pytz/zoneinfo/Pacific/Tahiti,sha256=BRff9G3E-iWKhOWR1Wu02Z0iMgjrwDXV-XNrqItXdTY,151 +pytz/zoneinfo/Pacific/Tarawa,sha256=UyaKimsR8LjgL8Z2g65I0HTvr3tMZuA2wUeBB6_Zp9c,152 +pytz/zoneinfo/Pacific/Tongatapu,sha256=OppBZqTAZib9HY7U9AC-JavO7m6NxPGUtUfPQAl9oBY,358 +pytz/zoneinfo/Pacific/Truk,sha256=nB36HBWZTdh3TlP0DLFNz1KRQ0aHIfHbp7LC4Urp9fA,172 +pytz/zoneinfo/Pacific/Wake,sha256=UyaKimsR8LjgL8Z2g65I0HTvr3tMZuA2wUeBB6_Zp9c,152 +pytz/zoneinfo/Pacific/Wallis,sha256=UyaKimsR8LjgL8Z2g65I0HTvr3tMZuA2wUeBB6_Zp9c,152 +pytz/zoneinfo/Pacific/Yap,sha256=nB36HBWZTdh3TlP0DLFNz1KRQ0aHIfHbp7LC4Urp9fA,172 +pytz/zoneinfo/Poland,sha256=TiLDPbeVF0ckgLVEkaSeDaKZ8wctdJDOl_HE_Wd5rKs,2654 +pytz/zoneinfo/Portugal,sha256=krB8skaJImv5NDCNHxvTPDBqpNphDFLNW84lB3lgUCw,3527 +pytz/zoneinfo/ROC,sha256=DMmQwOpPql25ue3Nf8vAKKT4em06D1Z9rHbLIitxixk,761 +pytz/zoneinfo/ROK,sha256=LI9LsV3XcJC0l-KoQf8zI-y7rk-du57erS-N2Ptdi7Q,617 +pytz/zoneinfo/Singapore,sha256=XmeVImeqcJ8hJzm7TjAti1nWJAxawOqq7jIzDnHX2hI,401 +pytz/zoneinfo/Turkey,sha256=Jk4wjndDta_uLWc8W1dWdjbavJJbsL5ROTmZboVnGKU,1933 +pytz/zoneinfo/UCT,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/US/Alaska,sha256=oZA1NSPS2BWdymYpnCHFO8BlYVS-ll5KLg2Ez9CbETs,2371 +pytz/zoneinfo/US/Aleutian,sha256=IB1DhwJQAKbhPJ9jHLf8zW5Dad7HIkBS-dhv64E1OlM,2356 +pytz/zoneinfo/US/Arizona,sha256=illz0sYuLL8lIPK0Tkou6dL0Vck_D0W_3rRTOvFYRmQ,360 +pytz/zoneinfo/US/Central,sha256=_roybr6I6sIAF6cYdIxGxoRpoef153Fty48dQ6bm9oY,3592 +pytz/zoneinfo/US/East-Indiana,sha256=kNKy9Kj9ICsiYYfCCbAggzMA7exf-GpGPMxoXocHUyw,1682 +pytz/zoneinfo/US/Eastern,sha256=6e0H177gx2qdRC0JHvHwFmj-58TyYBTAqGixn-bBipU,3552 +pytz/zoneinfo/US/Hawaii,sha256=fwPRv1Jk56sCOi75uZfd_Iy2k2aSQHx3B2K5xUlSPzM,329 +pytz/zoneinfo/US/Indiana-Starke,sha256=CsvZ5BKw2qVav3x_F8CU9taJdDk7jX41Cfsqms6jXV8,2444 +pytz/zoneinfo/US/Michigan,sha256=hecz8yqY2Cj5B61G3gLZdAVZvRgK9l0P90c_gN-uD5g,2230 +pytz/zoneinfo/US/Mountain,sha256=MugZwApDs8NI9TnXANQlUE8guNBowWQY0m-ptpPndck,2460 +pytz/zoneinfo/US/Pacific,sha256=aJd7ua1tGG_vxser02AQpm4wAI3LLTdgh6QcSYYecmg,2852 +pytz/zoneinfo/US/Samoa,sha256=fCYrYphYY6rUfxOw712y5cyRe104AC3pouqD3bCINFg,175 +pytz/zoneinfo/UTC,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/Universal,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/W-SU,sha256=KmkofRcj6T8Ph28PJChm8JVp13uRvef6TZ0GuPzUiDw,1535 +pytz/zoneinfo/WET,sha256=krB8skaJImv5NDCNHxvTPDBqpNphDFLNW84lB3lgUCw,3527 +pytz/zoneinfo/Zulu,sha256=i4WEZ5GrLIpUY8g6W-PAQ-JXDXRIQ01BOYlp7Ufj5vI,114 +pytz/zoneinfo/iso3166.tab,sha256=g3yAeFCAyEM_2dTqh-ePFhrHpAOJMBxRU9T5AZi66yo,4841 +pytz/zoneinfo/leapseconds,sha256=1sjAMwUn2ZXeXlCvnAe5Kfqdadkucjz7YjtK5vrm07U,3698 +pytz/zoneinfo/tzdata.zi,sha256=VtoH132ah5m2MaCHPE5wReox6DNV2cK81FsBvdsA4PQ,107480 +pytz/zoneinfo/zone.tab,sha256=WGtCB-bHZyLegq3Npr9J12H2aFF_RaZz9k2oOzM-7MQ,18822 +pytz/zoneinfo/zone1970.tab,sha256=6dn-MJQqiA91a3P2SWZ9hkeh7PITEUlEXZzCTGXk7o8,17605 +pytz/zoneinfo/zonenow.tab,sha256=o8efh6WitkdI4Qb5lOL5ecBP2UFt57kqFmnDnU7YSww,7926 diff --git a/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..4724c45738f6ac125bb3a21787855562e6870440 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: true +Tag: py2-none-any +Tag: py3-none-any + diff --git a/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/top_level.txt b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..af44f198c687e245aada835efbab2f75ed2c9baf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/top_level.txt @@ -0,0 +1 @@ +pytz diff --git a/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/zip-safe b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pytz-2026.1.post1.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..702ee6da5865b50b297705b077ea7d5904fead58 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/METADATA @@ -0,0 +1,59 @@ +Metadata-Version: 2.4 +Name: PyYAML +Version: 6.0.3 +Summary: YAML parser and emitter for Python +Home-page: https://pyyaml.org/ +Download-URL: https://pypi.org/project/PyYAML/ +Author: Kirill Simonov +Author-email: xi@resolvent.net +License: MIT +Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues +Project-URL: CI, https://github.com/yaml/pyyaml/actions +Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation +Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core +Project-URL: Source Code, https://github.com/yaml/pyyaml +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup +Requires-Python: >=3.8 +License-File: LICENSE +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: download-url +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: project-url +Dynamic: requires-python +Dynamic: summary + +YAML is a data serialization format designed for human readability +and interaction with scripting languages. PyYAML is a YAML parser +and emitter for Python. + +PyYAML features a complete YAML 1.1 parser, Unicode support, pickle +support, capable extension API, and sensible error messages. PyYAML +supports standard YAML tags and provides Python-specific tags that +allow to represent an arbitrary Python object. + +PyYAML is applicable for a broad range of tasks from complex +configuration files to object serialization and persistence. diff --git a/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..74d1aff5ba4d324f852e78629e85f25202fd9155 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/RECORD @@ -0,0 +1,43 @@ +_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402 +_yaml/__pycache__/__init__.cpython-312.pyc,, +pyyaml-6.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pyyaml-6.0.3.dist-info/METADATA,sha256=A8O0Fe040J-u3Ek2DpMHabQMWPaFhebeAOLkkWqFjTQ,2351 +pyyaml-6.0.3.dist-info/RECORD,, +pyyaml-6.0.3.dist-info/WHEEL,sha256=V1loQ6TpxABu1APUg0MoTRBOzSKT5xVc3skizX-ovCU,136 +pyyaml-6.0.3.dist-info/licenses/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101 +pyyaml-6.0.3.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11 +yaml/__init__.py,sha256=sZ38wzPWp139cwc5ARZFByUvJxtB07X32FUQAzoFR6c,12311 +yaml/__pycache__/__init__.cpython-312.pyc,, +yaml/__pycache__/composer.cpython-312.pyc,, +yaml/__pycache__/constructor.cpython-312.pyc,, +yaml/__pycache__/cyaml.cpython-312.pyc,, +yaml/__pycache__/dumper.cpython-312.pyc,, +yaml/__pycache__/emitter.cpython-312.pyc,, +yaml/__pycache__/error.cpython-312.pyc,, +yaml/__pycache__/events.cpython-312.pyc,, +yaml/__pycache__/loader.cpython-312.pyc,, +yaml/__pycache__/nodes.cpython-312.pyc,, +yaml/__pycache__/parser.cpython-312.pyc,, +yaml/__pycache__/reader.cpython-312.pyc,, +yaml/__pycache__/representer.cpython-312.pyc,, +yaml/__pycache__/resolver.cpython-312.pyc,, +yaml/__pycache__/scanner.cpython-312.pyc,, +yaml/__pycache__/serializer.cpython-312.pyc,, +yaml/__pycache__/tokens.cpython-312.pyc,, +yaml/_yaml.cpython-312-darwin.so,sha256=4i4gyboJIq6hYVjYOaZRtYIm6w6GVEh5t9X1IpE12Sg,381768 +yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883 +yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639 +yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851 +yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837 +yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006 +yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533 +yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445 +yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061 +yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440 +yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495 +yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794 +yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190 +yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004 +yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279 +yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165 +yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573 diff --git a/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..266c700f088ad9a4a4c34fe86f09b5a7336eddad --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-macosx_11_0_arm64 +Generator: delocate 0.13.0 + diff --git a/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/top_level.txt b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6475e911f628412049bc4090d86f23ac403adde --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/pyyaml-6.0.3.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_yaml +yaml diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/INSTALLER b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/LICENSE.txt b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..4aa1cdf245553ae4a714aed40311ad61885c555d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/LICENSE.txt @@ -0,0 +1,934 @@ +Copyright (c) 2001-2002 Enthought, Inc. 2003, SciPy 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: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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. + +---- + +This binary distribution of SciPy can also bundle the following software +(depending on the build): + + +Name: OpenBLAS +Files: scipy/.dylibs/libscipy_openblas*.so +Description: bundled as a dynamically linked library +Availability: https://github.com/OpenMathLib/OpenBLAS/ +License: BSD-3-Clause + Copyright (c) 2011-2014, The OpenBLAS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. 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. + 3. Neither the name of the OpenBLAS project 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. + + +Name: LAPACK +Files: scipy/.dylibs/libscipy_openblas*.so +Description: bundled in OpenBLAS +Availability: https://github.com/OpenMathLib/OpenBLAS/ +License: BSD-3-Clause-Open-MPI + Copyright (c) 1992-2013 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. + Copyright (c) 2000-2013 The University of California Berkeley. All + rights reserved. + Copyright (c) 2006-2013 The University of Colorado Denver. All rights + reserved. + + $COPYRIGHT$ + + Additional copyrights may follow + + $HEADER$ + + 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 listed + in this license in the documentation and/or other materials + provided with the distribution. + + - Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + The copyright holders provide no reassurances that the source code + provided does not infringe any patent, copyright, or any other + intellectual property rights of third parties. The copyright holders + disclaim any liability to any recipient for claims brought against + recipient by any third party for infringement of that parties + intellectual property rights. + + 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. + + +Name: GCC runtime library +Files: scipy/.dylibs/libgfortran*, scipy/.dylibs/libgcc* +Description: dynamically linked to files compiled with gcc +Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran +License: GPL-3.0-or-later WITH GCC-exception-3.1 + Copyright (C) 2002-2017 Free Software Foundation, Inc. + + Libgfortran is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + Libgfortran 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 General Public License for more details. + + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. + + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING3 and COPYING.RUNTIME respectively. If not, see + . + +---- + +Full text of license texts referred to above follows (that they are +listed below does not necessarily imply the conditions apply to the +present binary release): + +---- + +GCC RUNTIME LIBRARY EXCEPTION + +Version 3.1, 31 March 2009 + +Copyright (C) 2009 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +This GCC Runtime Library Exception ("Exception") is an additional +permission under section 7 of the GNU General Public License, version +3 ("GPLv3"). It applies to a given file (the "Runtime Library") that +bears a notice placed by the copyright holder of the file stating that +the file is governed by GPLv3 along with this Exception. + +When you use GCC to compile a program, GCC may combine portions of +certain GCC header files and runtime libraries with the compiled +program. The purpose of this Exception is to allow compilation of +non-GPL (including proprietary) programs to use, in this way, the +header files and runtime libraries covered by this Exception. + +0. Definitions. + +A file is an "Independent Module" if it either requires the Runtime +Library for execution after a Compilation Process, or makes use of an +interface provided by the Runtime Library, but is not otherwise based +on the Runtime Library. + +"GCC" means a version of the GNU Compiler Collection, with or without +modifications, governed by version 3 (or a specified later version) of +the GNU General Public License (GPL) with the option of using any +subsequent versions published by the FSF. + +"GPL-compatible Software" is software whose conditions of propagation, +modification and use would permit combination with GCC in accord with +the license of GCC. + +"Target Code" refers to output from any compiler for a real or virtual +target processor architecture, in executable form or suitable for +input to an assembler, loader, linker and/or execution +phase. Notwithstanding that, Target Code does not include data in any +format that is used as a compiler intermediate representation, or used +for producing a compiler intermediate representation. + +The "Compilation Process" transforms code entirely represented in +non-intermediate languages designed for human-written code, and/or in +Java Virtual Machine byte code, into Target Code. Thus, for example, +use of source code generators and preprocessors need not be considered +part of the Compilation Process, since the Compilation Process can be +understood as starting with the output of the generators or +preprocessors. + +A Compilation Process is "Eligible" if it is done using GCC, alone or +with other GPL-compatible software, or if it is done without using any +work based on GCC. For example, using non-GPL-compatible Software to +optimize any GCC intermediate representations would not qualify as an +Eligible Compilation Process. + +1. Grant of Additional Permission. + +You have permission to propagate a work of Target Code formed by +combining the Runtime Library with Independent Modules, even if such +propagation would otherwise violate the terms of GPLv3, provided that +all Target Code was generated by Eligible Compilation Processes. You +may then convey such a combination under terms of your choice, +consistent with the licensing of the Independent Modules. + +2. No Weakening of GCC Copyleft. + +The availability of this Exception does not imply any general +presumption that third-party software is unaffected by the copyleft +requirements of the license of GCC. + +---- + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + + +Name: libquadmath +Files: scipy/.dylibs/libquadmath*.so +Description: dynamically linked to files compiled with gcc +Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath +License: LGPL-2.1-or-later + + GCC Quad-Precision Math Library + Copyright (C) 2010-2019 Free Software Foundation, Inc. + Written by Francois-Xavier Coudert + + This file is part of the libquadmath library. + Libquadmath is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + Libquadmath 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. + https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/METADATA b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3fae2a783a0eca8e69f212fdfa984208ecce9225 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/METADATA @@ -0,0 +1,1086 @@ +Metadata-Version: 2.1 +Name: scipy +Version: 1.17.1 +Summary: Fundamental algorithms for scientific computing in Python +Maintainer-Email: SciPy Developers +License: Copyright (c) 2001-2002 Enthought, Inc. 2003, SciPy 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: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. 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. + + 3. Neither the name of the copyright holder 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. + + ---- + + This binary distribution of SciPy can also bundle the following software + (depending on the build): + + + Name: OpenBLAS + Files: scipy/.dylibs/libscipy_openblas*.so + Description: bundled as a dynamically linked library + Availability: https://github.com/OpenMathLib/OpenBLAS/ + License: BSD-3-Clause + Copyright (c) 2011-2014, The OpenBLAS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. 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. + 3. Neither the name of the OpenBLAS project 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. + + + Name: LAPACK + Files: scipy/.dylibs/libscipy_openblas*.so + Description: bundled in OpenBLAS + Availability: https://github.com/OpenMathLib/OpenBLAS/ + License: BSD-3-Clause-Open-MPI + Copyright (c) 1992-2013 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. + Copyright (c) 2000-2013 The University of California Berkeley. All + rights reserved. + Copyright (c) 2006-2013 The University of Colorado Denver. All rights + reserved. + + $COPYRIGHT$ + + Additional copyrights may follow + + $HEADER$ + + 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 listed + in this license in the documentation and/or other materials + provided with the distribution. + + - Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + The copyright holders provide no reassurances that the source code + provided does not infringe any patent, copyright, or any other + intellectual property rights of third parties. The copyright holders + disclaim any liability to any recipient for claims brought against + recipient by any third party for infringement of that parties + intellectual property rights. + + 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. + + + Name: GCC runtime library + Files: scipy/.dylibs/libgfortran*, scipy/.dylibs/libgcc* + Description: dynamically linked to files compiled with gcc + Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libgfortran + License: GPL-3.0-or-later WITH GCC-exception-3.1 + Copyright (C) 2002-2017 Free Software Foundation, Inc. + + Libgfortran is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + Libgfortran 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 General Public License for more details. + + Under Section 7 of GPL version 3, you are granted additional + permissions described in the GCC Runtime Library Exception, version + 3.1, as published by the Free Software Foundation. + + You should have received a copy of the GNU General Public License and + a copy of the GCC Runtime Library Exception along with this program; + see the files COPYING3 and COPYING.RUNTIME respectively. If not, see + . + + ---- + + Full text of license texts referred to above follows (that they are + listed below does not necessarily imply the conditions apply to the + present binary release): + + ---- + + GCC RUNTIME LIBRARY EXCEPTION + + Version 3.1, 31 March 2009 + + Copyright (C) 2009 Free Software Foundation, Inc. + + Everyone is permitted to copy and distribute verbatim copies of this + license document, but changing it is not allowed. + + This GCC Runtime Library Exception ("Exception") is an additional + permission under section 7 of the GNU General Public License, version + 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that + bears a notice placed by the copyright holder of the file stating that + the file is governed by GPLv3 along with this Exception. + + When you use GCC to compile a program, GCC may combine portions of + certain GCC header files and runtime libraries with the compiled + program. The purpose of this Exception is to allow compilation of + non-GPL (including proprietary) programs to use, in this way, the + header files and runtime libraries covered by this Exception. + + 0. Definitions. + + A file is an "Independent Module" if it either requires the Runtime + Library for execution after a Compilation Process, or makes use of an + interface provided by the Runtime Library, but is not otherwise based + on the Runtime Library. + + "GCC" means a version of the GNU Compiler Collection, with or without + modifications, governed by version 3 (or a specified later version) of + the GNU General Public License (GPL) with the option of using any + subsequent versions published by the FSF. + + "GPL-compatible Software" is software whose conditions of propagation, + modification and use would permit combination with GCC in accord with + the license of GCC. + + "Target Code" refers to output from any compiler for a real or virtual + target processor architecture, in executable form or suitable for + input to an assembler, loader, linker and/or execution + phase. Notwithstanding that, Target Code does not include data in any + format that is used as a compiler intermediate representation, or used + for producing a compiler intermediate representation. + + The "Compilation Process" transforms code entirely represented in + non-intermediate languages designed for human-written code, and/or in + Java Virtual Machine byte code, into Target Code. Thus, for example, + use of source code generators and preprocessors need not be considered + part of the Compilation Process, since the Compilation Process can be + understood as starting with the output of the generators or + preprocessors. + + A Compilation Process is "Eligible" if it is done using GCC, alone or + with other GPL-compatible software, or if it is done without using any + work based on GCC. For example, using non-GPL-compatible Software to + optimize any GCC intermediate representations would not qualify as an + Eligible Compilation Process. + + 1. Grant of Additional Permission. + + You have permission to propagate a work of Target Code formed by + combining the Runtime Library with Independent Modules, even if such + propagation would otherwise violate the terms of GPLv3, provided that + all Target Code was generated by Eligible Compilation Processes. You + may then convey such a combination under terms of your choice, + consistent with the licensing of the Independent Modules. + + 2. No Weakening of GCC Copyleft. + + The availability of this Exception does not imply any general + presumption that third-party software is unaffected by the copyleft + requirements of the license of GCC. + + ---- + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for + software and other kinds of works. + + The licenses for most software and other practical works are designed + to take away your freedom to share and change the works. By contrast, + the GNU General Public License is intended to guarantee your freedom to + share and change all versions of a program--to make sure it remains free + software for all its users. We, the Free Software Foundation, use the + GNU General Public License for most of our software; it applies also to + any other work released this way by its authors. You can apply it to + your programs, too. + + When we speak of free software, we are referring to freedom, not + price. Our General Public Licenses are designed to make sure that you + have the freedom to distribute copies of free software (and charge for + them if you wish), that you receive source code or can get it if you + want it, that you can change the software or use pieces of it in new + free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you + these rights or asking you to surrender the rights. Therefore, you have + certain responsibilities if you distribute copies of the software, or if + you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether + gratis or for a fee, you must pass on to the recipients the same + freedoms that you received. You must make sure that they, too, receive + or can get the source code. And you must show them these terms so they + know their rights. + + Developers that use the GNU GPL protect your rights with two steps: + (1) assert copyright on the software, and (2) offer you this License + giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains + that there is no warranty for this free software. For both users' and + authors' sake, the GPL requires that modified versions be marked as + changed, so that their problems will not be attributed erroneously to + authors of previous versions. + + Some devices are designed to deny users access to install or run + modified versions of the software inside them, although the manufacturer + can do so. This is fundamentally incompatible with the aim of + protecting users' freedom to change the software. The systematic + pattern of such abuse occurs in the area of products for individuals to + use, which is precisely where it is most unacceptable. Therefore, we + have designed this version of the GPL to prohibit the practice for those + products. If such problems arise substantially in other domains, we + stand ready to extend this provision to those domains in future versions + of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. + States should not allow patents to restrict development and use of + software on general-purpose computers, but in those that do, we wish to + avoid the special danger that patents applied to a free program could + make it effectively proprietary. To prevent this, the GPL assures that + patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and + modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of + works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this + License. Each licensee is addressed as "you". "Licensees" and + "recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work + in a fashion requiring copyright permission, other than the making of an + exact copy. The resulting work is called a "modified version" of the + earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based + on the Program. + + To "propagate" a work means to do anything with it that, without + permission, would make you directly or secondarily liable for + infringement under applicable copyright law, except executing it on a + computer or modifying a private copy. Propagation includes copying, + distribution (with or without modification), making available to the + public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other + parties to make or receive copies. Mere interaction with a user through + a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" + to the extent that it includes a convenient and prominently visible + feature that (1) displays an appropriate copyright notice, and (2) + tells the user that there is no warranty for the work (except to the + extent that warranties are provided), that licensees may convey the + work under this License, and how to view a copy of this License. If + the interface presents a list of user commands or options, such as a + menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work + for making modifications to it. "Object code" means any non-source + form of a work. + + A "Standard Interface" means an interface that either is an official + standard defined by a recognized standards body, or, in the case of + interfaces specified for a particular programming language, one that + is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other + than the work as a whole, that (a) is included in the normal form of + packaging a Major Component, but which is not part of that Major + Component, and (b) serves only to enable use of the work with that + Major Component, or to implement a Standard Interface for which an + implementation is available to the public in source code form. A + "Major Component", in this context, means a major essential component + (kernel, window system, and so on) of the specific operating system + (if any) on which the executable work runs, or a compiler used to + produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all + the source code needed to generate, install, and (for an executable + work) run the object code and to modify the work, including scripts to + control those activities. However, it does not include the work's + System Libraries, or general-purpose tools or generally available free + programs which are used unmodified in performing those activities but + which are not part of the work. For example, Corresponding Source + includes interface definition files associated with source files for + the work, and the source code for shared libraries and dynamically + linked subprograms that the work is specifically designed to require, + such as by intimate data communication or control flow between those + subprograms and other parts of the work. + + The Corresponding Source need not include anything that users + can regenerate automatically from other parts of the Corresponding + Source. + + The Corresponding Source for a work in source code form is that + same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of + copyright on the Program, and are irrevocable provided the stated + conditions are met. This License explicitly affirms your unlimited + permission to run the unmodified Program. The output from running a + covered work is covered by this License only if the output, given its + content, constitutes a covered work. This License acknowledges your + rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not + convey, without conditions so long as your license otherwise remains + in force. You may convey covered works to others for the sole purpose + of having them make modifications exclusively for you, or provide you + with facilities for running those works, provided that you comply with + the terms of this License in conveying all material for which you do + not control copyright. Those thus making or running the covered works + for you must do so exclusively on your behalf, under your direction + and control, on terms that prohibit them from making any copies of + your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under + the conditions stated below. Sublicensing is not allowed; section 10 + makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological + measure under any applicable law fulfilling obligations under article + 11 of the WIPO copyright treaty adopted on 20 December 1996, or + similar laws prohibiting or restricting circumvention of such + measures. + + When you convey a covered work, you waive any legal power to forbid + circumvention of technological measures to the extent such circumvention + is effected by exercising rights under this License with respect to + the covered work, and you disclaim any intention to limit operation or + modification of the work as a means of enforcing, against the work's + users, your or third parties' legal rights to forbid circumvention of + technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you + receive it, in any medium, provided that you conspicuously and + appropriately publish on each copy an appropriate copyright notice; + keep intact all notices stating that this License and any + non-permissive terms added in accord with section 7 apply to the code; + keep intact all notices of the absence of any warranty; and give all + recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, + and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to + produce it from the Program, in the form of source code under the + terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent + works, which are not by their nature extensions of the covered work, + and which are not combined with it such as to form a larger program, + in or on a volume of a storage or distribution medium, is called an + "aggregate" if the compilation and its resulting copyright are not + used to limit the access or legal rights of the compilation's users + beyond what the individual works permit. Inclusion of a covered work + in an aggregate does not cause this License to apply to the other + parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms + of sections 4 and 5, provided that you also convey the + machine-readable Corresponding Source under the terms of this License, + in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded + from the Corresponding Source as a System Library, need not be + included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any + tangible personal property which is normally used for personal, family, + or household purposes, or (2) anything designed or sold for incorporation + into a dwelling. In determining whether a product is a consumer product, + doubtful cases shall be resolved in favor of coverage. For a particular + product received by a particular user, "normally used" refers to a + typical or common use of that class of product, regardless of the status + of the particular user or of the way in which the particular user + actually uses, or expects or is expected to use, the product. A product + is a consumer product regardless of whether the product has substantial + commercial, industrial or non-consumer uses, unless such uses represent + the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, + procedures, authorization keys, or other information required to install + and execute modified versions of a covered work in that User Product from + a modified version of its Corresponding Source. The information must + suffice to ensure that the continued functioning of the modified object + code is in no case prevented or interfered with solely because + modification has been made. + + If you convey an object code work under this section in, or with, or + specifically for use in, a User Product, and the conveying occurs as + part of a transaction in which the right of possession and use of the + User Product is transferred to the recipient in perpetuity or for a + fixed term (regardless of how the transaction is characterized), the + Corresponding Source conveyed under this section must be accompanied + by the Installation Information. But this requirement does not apply + if neither you nor any third party retains the ability to install + modified object code on the User Product (for example, the work has + been installed in ROM). + + The requirement to provide Installation Information does not include a + requirement to continue to provide support service, warranty, or updates + for a work that has been modified or installed by the recipient, or for + the User Product in which it has been modified or installed. Access to a + network may be denied when the modification itself materially and + adversely affects the operation of the network or violates the rules and + protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, + in accord with this section must be in a format that is publicly + documented (and with an implementation available to the public in + source code form), and must require no special password or key for + unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this + License by making exceptions from one or more of its conditions. + Additional permissions that are applicable to the entire Program shall + be treated as though they were included in this License, to the extent + that they are valid under applicable law. If additional permissions + apply only to part of the Program, that part may be used separately + under those permissions, but the entire Program remains governed by + this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option + remove any additional permissions from that copy, or from any part of + it. (Additional permissions may be written to require their own + removal in certain cases when you modify the work.) You may place + additional permissions on material, added by you to a covered work, + for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you + add to a covered work, you may (if authorized by the copyright holders of + that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further + restrictions" within the meaning of section 10. If the Program as you + received it, or any part of it, contains a notice stating that it is + governed by this License along with a term that is a further + restriction, you may remove that term. If a license document contains + a further restriction but permits relicensing or conveying under this + License, you may add to a covered work material governed by the terms + of that license document, provided that the further restriction does + not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you + must place, in the relevant source files, a statement of the + additional terms that apply to those files, or a notice indicating + where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the + form of a separately written license, or stated as exceptions; + the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly + provided under this License. Any attempt otherwise to propagate or + modify it is void, and will automatically terminate your rights under + this License (including any patent licenses granted under the third + paragraph of section 11). + + However, if you cease all violation of this License, then your + license from a particular copyright holder is reinstated (a) + provisionally, unless and until the copyright holder explicitly and + finally terminates your license, and (b) permanently, if the copyright + holder fails to notify you of the violation by some reasonable means + prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is + reinstated permanently if the copyright holder notifies you of the + violation by some reasonable means, this is the first time you have + received notice of violation of this License (for any work) from that + copyright holder, and you cure the violation prior to 30 days after + your receipt of the notice. + + Termination of your rights under this section does not terminate the + licenses of parties who have received copies or rights from you under + this License. If your rights have been terminated and not permanently + reinstated, you do not qualify to receive new licenses for the same + material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or + run a copy of the Program. Ancillary propagation of a covered work + occurring solely as a consequence of using peer-to-peer transmission + to receive a copy likewise does not require acceptance. However, + nothing other than this License grants you permission to propagate or + modify any covered work. These actions infringe copyright if you do + not accept this License. Therefore, by modifying or propagating a + covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically + receives a license from the original licensors, to run, modify and + propagate that work, subject to this License. You are not responsible + for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an + organization, or substantially all assets of one, or subdividing an + organization, or merging organizations. If propagation of a covered + work results from an entity transaction, each party to that + transaction who receives a copy of the work also receives whatever + licenses to the work the party's predecessor in interest had or could + give under the previous paragraph, plus a right to possession of the + Corresponding Source of the work from the predecessor in interest, if + the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the + rights granted or affirmed under this License. For example, you may + not impose a license fee, royalty, or other charge for exercise of + rights granted under this License, and you may not initiate litigation + (including a cross-claim or counterclaim in a lawsuit) alleging that + any patent claim is infringed by making, using, selling, offering for + sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this + License of the Program or a work on which the Program is based. The + work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims + owned or controlled by the contributor, whether already acquired or + hereafter acquired, that would be infringed by some manner, permitted + by this License, of making, using, or selling its contributor version, + but do not include claims that would be infringed only as a + consequence of further modification of the contributor version. For + purposes of this definition, "control" includes the right to grant + patent sublicenses in a manner consistent with the requirements of + this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free + patent license under the contributor's essential patent claims, to + make, use, sell, offer for sale, import and otherwise run, modify and + propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express + agreement or commitment, however denominated, not to enforce a patent + (such as an express permission to practice a patent or covenant not to + sue for patent infringement). To "grant" such a patent license to a + party means to make such an agreement or commitment not to enforce a + patent against the party. + + If you convey a covered work, knowingly relying on a patent license, + and the Corresponding Source of the work is not available for anyone + to copy, free of charge and under the terms of this License, through a + publicly available network server or other readily accessible means, + then you must either (1) cause the Corresponding Source to be so + available, or (2) arrange to deprive yourself of the benefit of the + patent license for this particular work, or (3) arrange, in a manner + consistent with the requirements of this License, to extend the patent + license to downstream recipients. "Knowingly relying" means you have + actual knowledge that, but for the patent license, your conveying the + covered work in a country, or your recipient's use of the covered work + in a country, would infringe one or more identifiable patents in that + country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or + arrangement, you convey, or propagate by procuring conveyance of, a + covered work, and grant a patent license to some of the parties + receiving the covered work authorizing them to use, propagate, modify + or convey a specific copy of the covered work, then the patent license + you grant is automatically extended to all recipients of the covered + work and works based on it. + + A patent license is "discriminatory" if it does not include within + the scope of its coverage, prohibits the exercise of, or is + conditioned on the non-exercise of one or more of the rights that are + specifically granted under this License. You may not convey a covered + work if you are a party to an arrangement with a third party that is + in the business of distributing software, under which you make payment + to the third party based on the extent of your activity of conveying + the work, and under which the third party grants, to any of the + parties who would receive the covered work from you, a discriminatory + patent license (a) in connection with copies of the covered work + conveyed by you (or copies made from those copies), or (b) primarily + for and in connection with specific products or compilations that + contain the covered work, unless you entered into that arrangement, + or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting + any implied license or other defenses to infringement that may + otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or + otherwise) that contradict the conditions of this License, they do not + excuse you from the conditions of this License. If you cannot convey a + covered work so as to satisfy simultaneously your obligations under this + License and any other pertinent obligations, then as a consequence you may + not convey it at all. For example, if you agree to terms that obligate you + to collect a royalty for further conveying from those to whom you convey + the Program, the only way you could satisfy both those terms and this + License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have + permission to link or combine any covered work with a work licensed + under version 3 of the GNU Affero General Public License into a single + combined work, and to convey the resulting work. The terms of this + License will continue to apply to the part which is the covered work, + but the special requirements of the GNU Affero General Public License, + section 13, concerning interaction through a network will apply to the + combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of + the GNU General Public License from time to time. Such new versions will + be similar in spirit to the present version, but may differ in detail to + address new problems or concerns. + + Each version is given a distinguishing version number. If the + Program specifies that a certain numbered version of the GNU General + Public License "or any later version" applies to it, you have the + option of following the terms and conditions either of that numbered + version or of any later version published by the Free Software + Foundation. If the Program does not specify a version number of the + GNU General Public License, you may choose any version ever published + by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future + versions of the GNU General Public License can be used, that proxy's + public statement of acceptance of a version permanently authorizes you + to choose that version for the Program. + + Later license versions may give you additional or different + permissions. However, no additional obligations are imposed on any + author or copyright holder as a result of your choosing to follow a + later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY + APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT + HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY + OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM + IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF + ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING + WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS + THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY + GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE + USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF + DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD + PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), + EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF + SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided + above cannot be given local legal effect according to their terms, + reviewing courts shall apply local law that most closely approximates + an absolute waiver of all civil liability in connection with the + Program, unless a warranty or assumption of liability accompanies a + copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest + possible use to the public, the best way to achieve this is to make it + free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest + to attach them to the start of each source file to most effectively + state the exclusion of warranty; and each file should have at least + the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short + notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + + The hypothetical commands `show w' and `show c' should show the appropriate + parts of the General Public License. Of course, your program's commands + might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, + if any, to sign a "copyright disclaimer" for the program, if necessary. + For more information on this, and how to apply and follow the GNU GPL, see + . + + The GNU General Public License does not permit incorporating your program + into proprietary programs. If your program is a subroutine library, you + may consider it more useful to permit linking proprietary applications with + the library. If this is what you want to do, use the GNU Lesser General + Public License instead of this License. But first, please read + . + + + Name: libquadmath + Files: scipy/.dylibs/libquadmath*.so + Description: dynamically linked to files compiled with gcc + Availability: https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=libquadmath + License: LGPL-2.1-or-later + + GCC Quad-Precision Math Library + Copyright (C) 2010-2019 Free Software Foundation, Inc. + Written by Francois-Xavier Coudert + + This file is part of the libquadmath library. + Libquadmath is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + Libquadmath 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. + https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html + +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Science/Research +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: C +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Scientific/Engineering +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Operating System :: MacOS +Project-URL: homepage, https://scipy.org/ +Project-URL: documentation, https://docs.scipy.org/doc/scipy/ +Project-URL: source, https://github.com/scipy/scipy +Project-URL: download, https://github.com/scipy/scipy/releases +Project-URL: tracker, https://github.com/scipy/scipy/issues +Requires-Python: >=3.11 +Requires-Dist: numpy<2.7,>=1.26.4 +Provides-Extra: test +Requires-Dist: pytest>=8.0.0; extra == "test" +Requires-Dist: pytest-cov; extra == "test" +Requires-Dist: pytest-timeout; extra == "test" +Requires-Dist: pytest-xdist; extra == "test" +Requires-Dist: asv; extra == "test" +Requires-Dist: mpmath; extra == "test" +Requires-Dist: gmpy2; extra == "test" +Requires-Dist: threadpoolctl; extra == "test" +Requires-Dist: scikit-umfpack; extra == "test" +Requires-Dist: pooch; extra == "test" +Requires-Dist: hypothesis>=6.30; extra == "test" +Requires-Dist: array-api-strict>=2.3.1; extra == "test" +Requires-Dist: Cython; extra == "test" +Requires-Dist: meson; extra == "test" +Requires-Dist: ninja; sys_platform != "emscripten" and extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx<8.2.0,>=5.0.0; extra == "doc" +Requires-Dist: intersphinx_registry; extra == "doc" +Requires-Dist: pydata-sphinx-theme>=0.15.2; extra == "doc" +Requires-Dist: sphinx-copybutton; extra == "doc" +Requires-Dist: sphinx-design>=0.4.0; extra == "doc" +Requires-Dist: matplotlib>=3.5; extra == "doc" +Requires-Dist: numpydoc; extra == "doc" +Requires-Dist: jupytext; extra == "doc" +Requires-Dist: myst-nb>=1.2.0; extra == "doc" +Requires-Dist: pooch; extra == "doc" +Requires-Dist: jupyterlite-sphinx>=0.19.1; extra == "doc" +Requires-Dist: jupyterlite-pyodide-kernel; extra == "doc" +Requires-Dist: linkify-it-py; extra == "doc" +Requires-Dist: tabulate; extra == "doc" +Provides-Extra: dev +Requires-Dist: click<8.3.0; extra == "dev" +Requires-Dist: spin; extra == "dev" +Requires-Dist: mypy==1.10.0; extra == "dev" +Requires-Dist: typing_extensions; extra == "dev" +Requires-Dist: types-psutil; extra == "dev" +Requires-Dist: pycodestyle; extra == "dev" +Requires-Dist: ruff>=0.12.0; extra == "dev" +Requires-Dist: cython-lint>=0.12.2; extra == "dev" +Description-Content-Type: text/x-rst + +.. image:: https://raw.githubusercontent.com/scipy/scipy/main/doc/source/_static/logo.svg + :target: https://scipy.org + :width: 110 + :height: 110 + :align: left + +.. image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A + :target: https://numfocus.org + +.. image:: https://img.shields.io/pypi/dm/scipy.svg?label=Pypi%20downloads + :target: https://pypi.org/project/scipy/ + +.. image:: https://img.shields.io/conda/dn/conda-forge/scipy.svg?label=Conda%20downloads + :target: https://anaconda.org/conda-forge/scipy + +.. image:: https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg + :target: https://stackoverflow.com/questions/tagged/scipy + +.. image:: https://img.shields.io/badge/DOI-10.1038%2Fs41592--019--0686--2-blue.svg + :target: https://www.nature.com/articles/s41592-019-0686-2 + +.. image:: https://insights.linuxfoundation.org/api/badge/health-score?project=scipy + :target: https://insights.linuxfoundation.org/project/scipy + +SciPy (pronounced "Sigh Pie") is an open-source software for mathematics, +science, and engineering. It includes modules for statistics, optimization, +integration, linear algebra, Fourier transforms, signal and image processing, +ODE solvers, and more. + +- **Website:** https://scipy.org +- **Documentation:** https://docs.scipy.org/doc/scipy/ +- **Development version of the documentation:** https://scipy.github.io/devdocs +- **SciPy development forum:** https://discuss.scientific-python.org/c/contributor/scipy +- **Stack Overflow:** https://stackoverflow.com/questions/tagged/scipy +- **Source code:** https://github.com/scipy/scipy +- **Contributing:** https://scipy.github.io/devdocs/dev/index.html +- **Bug reports:** https://github.com/scipy/scipy/issues +- **Code of Conduct:** https://docs.scipy.org/doc/scipy/dev/conduct/code_of_conduct.html +- **Report a security vulnerability:** https://tidelift.com/docs/security +- **Citing in your work:** https://www.scipy.org/citing-scipy/ + +SciPy is built to work with +NumPy arrays, and provides many user-friendly and efficient numerical routines, +such as routines for numerical integration and optimization. Together, they +run on all popular operating systems, are quick to install, and are free of +charge. NumPy and SciPy are easy to use, but powerful enough to be depended +upon by some of the world's leading scientists and engineers. If you need to +manipulate numbers on a computer and display or publish the results, give +SciPy a try! + +For the installation instructions, see `our install +guide `__. + + +Call for Contributions +---------------------- + +We appreciate and welcome contributions. Small improvements or fixes are always appreciated; issues labeled as "good +first issue" may be a good starting point. Have a look at `our contributing +guide `__. + +Writing code isn’t the only way to contribute to SciPy. You can also: + +- review pull requests +- triage issues +- develop tutorials, presentations, and other educational materials +- maintain and improve `our website `__ +- develop graphic design for our brand assets and promotional materials +- help with outreach and onboard new contributors +- write grant proposals and help with other fundraising efforts + +If you’re unsure where to start or how your skills fit in, reach out! You can +ask on the `forum `__ +or here, on GitHub, by leaving a comment on a relevant issue that is already +open. + +If you are new to contributing to open source, `this +guide `__ helps explain why, what, +and how to get involved. diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/RECORD b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7f7c529e8c369f67c694184072f3028d5d8aa519 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/RECORD @@ -0,0 +1,2397 @@ +scipy-1.17.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +scipy-1.17.1.dist-info/LICENSE.txt,sha256=YKfQXXKe1cdjhSoyShy0Ij1mXUrT9LigwTCuXGDJPkk,46841 +scipy-1.17.1.dist-info/METADATA,sha256=sc0seE9uADxsca9MXuV_Y3DuRn0XtlYlDZ_TjPV519A,62145 +scipy-1.17.1.dist-info/RECORD,, +scipy-1.17.1.dist-info/WHEEL,sha256=JnJiRvkXFaFU4HlzyoqCApZ07jy6hpFKd_LkfBpWZzk,122 +scipy/.dylibs/libgcc_s.1.1.dylib,sha256=Z4HOH3ncEOIRulMrdmsKhEJldn0zQ_ApoIESgCRQpzA,183040 +scipy/.dylibs/libgfortran.5.dylib,sha256=hpplVaeH_VWQ4sRAzLTYLZY1hhaGWfvzNU4VcOPxC8w,1901520 +scipy/.dylibs/libquadmath.0.dylib,sha256=Z22G5Ro5UPdbQZRadYvbAr4cEf709KRbGZTUgyKOJQQ,363936 +scipy/__config__.py,sha256=5oFiAr8o-luIMww4vwFElg_LtJUau-4luw9jDWKi--I,5353 +scipy/__init__.py,sha256=M1vG4KmQncdTT5Vpo2haktyAAcuMY6baTCOYSf8C1NA,4063 +scipy/__pycache__/__config__.cpython-312.pyc,, +scipy/__pycache__/__init__.cpython-312.pyc,, +scipy/__pycache__/_distributor_init.cpython-312.pyc,, +scipy/__pycache__/conftest.cpython-312.pyc,, +scipy/__pycache__/version.cpython-312.pyc,, +scipy/_cyutility.cpython-312-darwin.so,sha256=uRI8PgwVFjF_5kboBnaU7U01-H68EARGkaQ_W9HXzmc,169968 +scipy/_distributor_init.py,sha256=zJThN3Fvof09h24804pNDPd2iN-lCHV3yPlZylSefgQ,611 +scipy/_lib/__init__.py,sha256=CXrH_YBpZ-HImHHrqXIhQt_vevp4P5NXClp7hnFMVLM,353 +scipy/_lib/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/__pycache__/_array_api.cpython-312.pyc,, +scipy/_lib/__pycache__/_array_api_compat_vendor.cpython-312.pyc,, +scipy/_lib/__pycache__/_array_api_docs_tables.cpython-312.pyc,, +scipy/_lib/__pycache__/_array_api_no_0d.cpython-312.pyc,, +scipy/_lib/__pycache__/_array_api_override.cpython-312.pyc,, +scipy/_lib/__pycache__/_bunch.cpython-312.pyc,, +scipy/_lib/__pycache__/_ccallback.cpython-312.pyc,, +scipy/_lib/__pycache__/_disjoint_set.cpython-312.pyc,, +scipy/_lib/__pycache__/_docscrape.cpython-312.pyc,, +scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-312.pyc,, +scipy/_lib/__pycache__/_gcutils.cpython-312.pyc,, +scipy/_lib/__pycache__/_pep440.cpython-312.pyc,, +scipy/_lib/__pycache__/_public_api.cpython-312.pyc,, +scipy/_lib/__pycache__/_sparse.cpython-312.pyc,, +scipy/_lib/__pycache__/_testutils.cpython-312.pyc,, +scipy/_lib/__pycache__/_tmpdirs.cpython-312.pyc,, +scipy/_lib/__pycache__/_util.cpython-312.pyc,, +scipy/_lib/__pycache__/deprecation.cpython-312.pyc,, +scipy/_lib/__pycache__/doccer.cpython-312.pyc,, +scipy/_lib/__pycache__/uarray.cpython-312.pyc,, +scipy/_lib/_array_api.py,sha256=57bQj4d0VrnSavgIJnJj9B8ocCYZUaGdn_EzMB0V4eI,37765 +scipy/_lib/_array_api_compat_vendor.py,sha256=4_s2kL0PK-57lDOQPRKUD9A1-rUK23tjbvUcwWUu1v8,402 +scipy/_lib/_array_api_docs_tables.py,sha256=28SLvfv6kvjpl8zKkyLED_IYCnT75I_oGkJcnC9UrGg,10959 +scipy/_lib/_array_api_no_0d.py,sha256=zVB7D070dZ9Rc-7mXvlkqpv75TgcvCy_7PL0q6yZsbg,4453 +scipy/_lib/_array_api_override.py,sha256=9VjrVzlIB1-l0Rt3GAUW-xJGuS7yyQ6kUz-EWnBlpyk,5239 +scipy/_lib/_bunch.py,sha256=KV-kCN6lXFOp7HSiiVGSmDSwzKUITtuy8WWnO_rWLRo,8305 +scipy/_lib/_ccallback.py,sha256=N9CO7kJYzk6IWQR5LHf_YA1-Oq48R38UIhJFIlJ2Qyc,7087 +scipy/_lib/_ccallback_c.cpython-312-darwin.so,sha256=wqdei46Z3cHe1J1n66GyKy_CRZ2k_qNDu-1NqwQ5Q8w,114640 +scipy/_lib/_disjoint_set.py,sha256=o_EUHZwnnI1m8nitEf8bSkF7TWZ65RSiklBN4daFruA,6160 +scipy/_lib/_docscrape.py,sha256=Jm2QPPIqNiAgKqoR5fX0P-bsBofYAtJhHbX2h1A63j0,23807 +scipy/_lib/_elementwise_iterative_method.py,sha256=fC1ou8u6XHCpMnTRKsqwyP5_zW0gDu0TzGqw-nqWEAU,15023 +scipy/_lib/_fpumode.cpython-312-darwin.so,sha256=FCAUmAbVLZYEm5lBmIGlngpwkdQq7jsvOA6GigO5UqY,50208 +scipy/_lib/_gcutils.py,sha256=hajQd-HUw9ckK7QeBaqXVRpmnxPgyXO3QqqniEh7tRk,2669 +scipy/_lib/_pep440.py,sha256=vo3nxbfjtMfGq1ektYzHIzRbj8W-NHOMp5WBRjPlDTg,14005 +scipy/_lib/_public_api.py,sha256=b-_Gi7cCEC_J8YjJtRcVq1hVpccTxCokxB3OCkaafgM,1610 +scipy/_lib/_sparse.py,sha256=Ifbhhdja4dpNNpsaO0VcjgRPcw2hqqHXOBF9eXRGsbE,875 +scipy/_lib/_test_ccallback.cpython-312-darwin.so,sha256=yT7cdVD7kapQylSVcN2Q8ihI84NlUOuf5hz4cQBPHfI,53032 +scipy/_lib/_test_deprecation_call.cpython-312-darwin.so,sha256=0gJY9mOEMsG2C6czVPzj8c1UI31RXuS0C3-Gf5PcTno,75104 +scipy/_lib/_test_deprecation_def.cpython-312-darwin.so,sha256=RcuVfdCqUCht6XsRYYbFAVvt1vyI5xhaEUcZiebiSjM,55096 +scipy/_lib/_testutils.py,sha256=qIz1sYnGCQfIDumEHDYDoQdMTHXlY40-DqVfI9hg7qk,12279 +scipy/_lib/_tmpdirs.py,sha256=z3IYpzACnWdN_BMjOvqYbkTvYyUbfbQvfehq7idENSo,2374 +scipy/_lib/_uarray/LICENSE,sha256=yAw5tfzga6SJfhTgsKiLVEWDNNlR6xNhQC_60s-4Y7Q,1514 +scipy/_lib/_uarray/__init__.py,sha256=Rww7wLA7FH6Yong7oMgl_sHPpjcRslRaTjh61W_xVg4,4493 +scipy/_lib/_uarray/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/_uarray/__pycache__/_backend.cpython-312.pyc,, +scipy/_lib/_uarray/_backend.py,sha256=LZnSLJ2UK209jrMtocOMoc5grlNoob3tbb1HbW0XlAQ,20531 +scipy/_lib/_uarray/_uarray.cpython-312-darwin.so,sha256=kEfb14LU06lcM3pFlR6_oU38EVrhSzZrAo_gZ7hUmWE,120656 +scipy/_lib/_util.py,sha256=qf77wE1gX4irt7kFpyouUQrUIiP9z-BJpOoSyUVbiaI,48730 +scipy/_lib/array_api_compat/__init__.py,sha256=XbhBzRpMRAKRuPnzAfZD4kITuXxjgafIDX4veTHtO-U,992 +scipy/_lib/array_api_compat/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_compat/__pycache__/_internal.cpython-312.pyc,, +scipy/_lib/array_api_compat/_internal.py,sha256=tYJkaxIxVxELYvo9JK2UgCCJBMw01JiVmomTIjVpM5U,2072 +scipy/_lib/array_api_compat/common/__init__.py,sha256=4IcMWP5rARLYe2_pgXDWEuj2YpM0c1G6Pb5pkbQ0QS8,38 +scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-312.pyc,, +scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-312.pyc,, +scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-312.pyc,, +scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-312.pyc,, +scipy/_lib/array_api_compat/common/__pycache__/_typing.cpython-312.pyc,, +scipy/_lib/array_api_compat/common/_aliases.py,sha256=0fYL3vEwX0kRdpscJY3l7Q37kHfAlzmxUulkI-e9Sws,18988 +scipy/_lib/array_api_compat/common/_fft.py,sha256=ckCR2uHtz0iaOkcuvqVunhz1khIdxQNKuVU0x1bfrq8,4669 +scipy/_lib/array_api_compat/common/_helpers.py,sha256=1WFBA38HVEQCm9yiy3RtpxP0wIxmi2sfmYhyqgxMNBE,32556 +scipy/_lib/array_api_compat/common/_linalg.py,sha256=jsz7PpwAD2QeqJQCnYd3LwcTLm6YMjyla9_Ol70ifF4,6805 +scipy/_lib/array_api_compat/common/_typing.py,sha256=gFg3AvkvXQ0VVeiZtjejpaU5V4oCXnRlbGzNmHpLPFs,4498 +scipy/_lib/array_api_compat/cupy/__init__.py,sha256=u_lgOQrp7-pI24bZp8fNm4QfrlmcocpFL2fWX-2Tv_4,736 +scipy/_lib/array_api_compat/cupy/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_compat/cupy/__pycache__/_aliases.cpython-312.pyc,, +scipy/_lib/array_api_compat/cupy/__pycache__/_info.cpython-312.pyc,, +scipy/_lib/array_api_compat/cupy/__pycache__/_typing.cpython-312.pyc,, +scipy/_lib/array_api_compat/cupy/__pycache__/fft.cpython-312.pyc,, +scipy/_lib/array_api_compat/cupy/__pycache__/linalg.cpython-312.pyc,, +scipy/_lib/array_api_compat/cupy/_aliases.py,sha256=eoR2lVB45fCMsLtGm3PnczOivUxISxlFJ2K4yV_aiZM,5122 +scipy/_lib/array_api_compat/cupy/_info.py,sha256=g3DwO5ps4bSlFU2pc_f4XTaLrkCYuSDlCw0Ql2wuqM8,10125 +scipy/_lib/array_api_compat/cupy/_typing.py,sha256=L6RUNFoy-ZwLizEqCSqHN-6GC5chKYfQL8xW4FVksKA,607 +scipy/_lib/array_api_compat/cupy/fft.py,sha256=D5HJ6rclFA7-CO_NleuCZQy2Lz7InkFuE8CHTrxrXc0,872 +scipy/_lib/array_api_compat/cupy/linalg.py,sha256=G5zEzcmqVRv8Bs_LaOXd_1QkOvSQn4c3giYvCEtt3w4,1465 +scipy/_lib/array_api_compat/dask/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/_lib/array_api_compat/dask/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_compat/dask/array/__init__.py,sha256=2hRAArKNn6Zh67QpQ5yCjb3cTnJsom_85ShCFDZdz9A,677 +scipy/_lib/array_api_compat/dask/array/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_compat/dask/array/__pycache__/_aliases.cpython-312.pyc,, +scipy/_lib/array_api_compat/dask/array/__pycache__/_info.cpython-312.pyc,, +scipy/_lib/array_api_compat/dask/array/__pycache__/fft.cpython-312.pyc,, +scipy/_lib/array_api_compat/dask/array/__pycache__/linalg.cpython-312.pyc,, +scipy/_lib/array_api_compat/dask/array/_aliases.py,sha256=eJkzntr9_0ew0SFBeAEe3zd1vjdsXb7wpP_HOqVl_GM,10432 +scipy/_lib/array_api_compat/dask/array/_info.py,sha256=SSClqGR_1AeTOhUPvryTpUJb4ke5jykHB-LeXw9gQmA,12241 +scipy/_lib/array_api_compat/dask/array/fft.py,sha256=dJEAXxGtfP5Z_-oR8GNuiMwHG1-Hbwax02wxmN95QjQ,333 +scipy/_lib/array_api_compat/dask/array/linalg.py,sha256=-YEIM8c0I1CUidb0DTT5QMJJRzo87N2woPSs0XI8Xh4,2139 +scipy/_lib/array_api_compat/numpy/__init__.py,sha256=S5-VzRtXS6re5bOy4xtV3RfYKk9AQwJ74vMhiiQKxJY,1064 +scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-312.pyc,, +scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-312.pyc,, +scipy/_lib/array_api_compat/numpy/__pycache__/_typing.cpython-312.pyc,, +scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-312.pyc,, +scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-312.pyc,, +scipy/_lib/array_api_compat/numpy/_aliases.py,sha256=3FhudS9W4PofYTtsf6vTHEtTC_T_i2ecUE4eBMLyqrg,5666 +scipy/_lib/array_api_compat/numpy/_info.py,sha256=C7iKLQU8Q8AJCkf_ADv_UWgum8UdbagewvKGL_LmQ3I,10793 +scipy/_lib/array_api_compat/numpy/_typing.py,sha256=hXWLcYHogQcHzK1tR8B9difxm3UFlHhUUaXBHydqpyE,605 +scipy/_lib/array_api_compat/numpy/fft.py,sha256=gx6R3o_ehnMWpsvBI2y0mBNxwZP9KFLTuQ9uP4eSrMk,714 +scipy/_lib/array_api_compat/numpy/linalg.py,sha256=tZHdXpZnmWbsbeGYudpDEzDw0u65tziwya2JJd9m110,3914 +scipy/_lib/array_api_compat/torch/__init__.py,sha256=8ZAu0FQ6jpm6kVlNXD6UDIigBnyM4nC_LJTaAHz9QU0,633 +scipy/_lib/array_api_compat/torch/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_compat/torch/__pycache__/_aliases.cpython-312.pyc,, +scipy/_lib/array_api_compat/torch/__pycache__/_info.cpython-312.pyc,, +scipy/_lib/array_api_compat/torch/__pycache__/_typing.cpython-312.pyc,, +scipy/_lib/array_api_compat/torch/__pycache__/fft.cpython-312.pyc,, +scipy/_lib/array_api_compat/torch/__pycache__/linalg.cpython-312.pyc,, +scipy/_lib/array_api_compat/torch/_aliases.py,sha256=PRCqlNel5pCaGmfj_FxcCEr_zXvZbdBBKoagerPQObs,30503 +scipy/_lib/array_api_compat/torch/_info.py,sha256=-H2xD9z9SMf3GjIOW0jeRTUOvh4s8E9p9u_4LqawRZM,11889 +scipy/_lib/array_api_compat/torch/_typing.py,sha256=-uCkuTie1g9hb4vwPLK9eEnir9Zp67wAhrfaI_o-35E,108 +scipy/_lib/array_api_compat/torch/fft.py,sha256=ijW1aJaOys2EMkF04hu3vSMQMqd2ZLUpLvAZUQZf4Lw,1833 +scipy/_lib/array_api_compat/torch/linalg.py,sha256=x-qGeIVVbNsmk9ZLSV4JHWZE4WB8HqGeHlQrhNPMGJs,4560 +scipy/_lib/array_api_extra/__init__.py,sha256=RXDIahZUyopULk4yjXTSPrNDCuiNLIe17MQpD9jSL0c,867 +scipy/_lib/array_api_extra/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_extra/__pycache__/_delegation.cpython-312.pyc,, +scipy/_lib/array_api_extra/__pycache__/testing.cpython-312.pyc,, +scipy/_lib/array_api_extra/_delegation.py,sha256=Z3r-PwaQ3jW_vTKDhENkScxedgM18B6d10BluLJdggc,33403 +scipy/_lib/array_api_extra/_lib/__init__.py,sha256=Mht4YV9Rpkzg5kORPlgjOOXk4y7bvdngowS6KGSHqNE,36 +scipy/_lib/array_api_extra/_lib/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/__pycache__/_at.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/__pycache__/_backends.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/__pycache__/_funcs.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/__pycache__/_lazy.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/__pycache__/_testing.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/_at.py,sha256=JOZX0nw6UpyRKZIZRQDb1w_YSGeJ-4v1vJFdrISGI_k,15327 +scipy/_lib/array_api_extra/_lib/_backends.py,sha256=QPZvkbtVtcwr5WDseaTcTo0z6u1HqdCVd67G5ndcPwE,2168 +scipy/_lib/array_api_extra/_lib/_funcs.py,sha256=HZq1IQMtiPe34sXWKmI-_zrBXZZU8AhNXE8uBr6zaO0,23418 +scipy/_lib/array_api_extra/_lib/_lazy.py,sha256=RE1DzMqj0j7GpY6GKSLyBuTL9vQaWkLSn7h-iZ9eVd8,13811 +scipy/_lib/array_api_extra/_lib/_testing.py,sha256=GtIc8GIDEqw90nn5g72gt71flj5-1BP29ZKzwoduoSQ,10290 +scipy/_lib/array_api_extra/_lib/_utils/__init__.py,sha256=8ICffM2MprXpWZd8ia0-5ZTnKtDfeZD0gExLveDrXZs,49 +scipy/_lib/array_api_extra/_lib/_utils/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_compat.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_helpers.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/_utils/__pycache__/_typing.cpython-312.pyc,, +scipy/_lib/array_api_extra/_lib/_utils/_compat.py,sha256=4A5a_S4qo88_H8LKmQal2e_1PVQAY1eInKDZsCgPNYU,1812 +scipy/_lib/array_api_extra/_lib/_utils/_compat.pyi,sha256=6QexmJx0rPSEtvVQAt2HbS87F8njDMsD9UhyIJsen8c,1720 +scipy/_lib/array_api_extra/_lib/_utils/_helpers.py,sha256=sjeti2M-7OK-5GBdc45O_QlhwTTInnQQpSX98rgUiZc,19770 +scipy/_lib/array_api_extra/_lib/_utils/_typing.py,sha256=0NSYWpdXH58Dx9T7HsNPM0NW2iPlTZS6xOrR-5tFOYc,228 +scipy/_lib/array_api_extra/_lib/_utils/_typing.pyi,sha256=tfmj1bK5a1RWFc8qXR10FhLlXBwzyItFrN0zcXTWntM,4665 +scipy/_lib/array_api_extra/testing.py,sha256=s2BfjND8f9GxTg9eDChRsrjsfdlJ1wyNKM9RoU865WI,14653 +scipy/_lib/cobyqa/__init__.py,sha256=Uo9FFveH-XgEuhkleW5NIiBwp3YZ71r-Ybv3t2JnqE8,578 +scipy/_lib/cobyqa/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/cobyqa/__pycache__/framework.cpython-312.pyc,, +scipy/_lib/cobyqa/__pycache__/main.cpython-312.pyc,, +scipy/_lib/cobyqa/__pycache__/models.cpython-312.pyc,, +scipy/_lib/cobyqa/__pycache__/problem.cpython-312.pyc,, +scipy/_lib/cobyqa/__pycache__/settings.cpython-312.pyc,, +scipy/_lib/cobyqa/framework.py,sha256=lIeKCkDLxHbMmSTiMcyasvVe77jVvh_YTOYX0HnK4Qk,38900 +scipy/_lib/cobyqa/main.py,sha256=wz0M2iqFfzeTaZUq_j1TkF_9V_SJ1t73A-0fdH0eSs4,57527 +scipy/_lib/cobyqa/models.py,sha256=LGPk0teoVBse25bkIePklFgOUHo63VnbKLXh4gxZhSA,50694 +scipy/_lib/cobyqa/problem.py,sha256=SiPgmiFTxiW5yJ_FVf37Z9GQGo6Gx_fJ3RXMzhsrn40,40203 +scipy/_lib/cobyqa/settings.py,sha256=ogfiShxuPHsMfW16OGSwB9-mIPRiuWZSGXBOCO2HDvw,3826 +scipy/_lib/cobyqa/subsolvers/__init__.py,sha256=VmFBpi-_tNa8yzNmu_fufewmPTnCU6ycNCGcN34UBcc,341 +scipy/_lib/cobyqa/subsolvers/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/cobyqa/subsolvers/__pycache__/geometry.cpython-312.pyc,, +scipy/_lib/cobyqa/subsolvers/__pycache__/optim.cpython-312.pyc,, +scipy/_lib/cobyqa/subsolvers/geometry.py,sha256=dgS-C0QBUhkzPhHULFIRbnbFOIEB005GyPYE-i-cuFY,14173 +scipy/_lib/cobyqa/subsolvers/optim.py,sha256=hIseVqrPyI3ezICGNXkCtKlpqvAO2W6ZQe0n7sxfkss,45512 +scipy/_lib/cobyqa/utils/__init__.py,sha256=sw6g402vXaXwX7rMhxrNl5PD5OBs89l5f3XNcYApRHs,359 +scipy/_lib/cobyqa/utils/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/cobyqa/utils/__pycache__/exceptions.cpython-312.pyc,, +scipy/_lib/cobyqa/utils/__pycache__/math.cpython-312.pyc,, +scipy/_lib/cobyqa/utils/__pycache__/versions.cpython-312.pyc,, +scipy/_lib/cobyqa/utils/exceptions.py,sha256=N1JdmUxHnME95wEZHyeeF_M6GXPEqH5t3qzuXig49YE,483 +scipy/_lib/cobyqa/utils/math.py,sha256=beT-Tib41TJWZecjnKhSfu4foOLLaHlWj5CcyRhdSl4,1611 +scipy/_lib/cobyqa/utils/versions.py,sha256=eBOlEGAKFCfjFqVprdali3M1G7l0k_kxb7ku-Lz2bU0,1465 +scipy/_lib/deprecation.py,sha256=2KeqTdCUmSAcv3QLoTzCK5vkBWcmJl5Wawz1FVxuJ3Q,9854 +scipy/_lib/doccer.py,sha256=W1HgV3SpTFpZJ0oyiN9Yn4vuX5pwxx27anH-sGNv19Y,10721 +scipy/_lib/messagestream.cpython-312-darwin.so,sha256=uJderxyApJRzxH2Wv_SqHhgIro1un3Snq4RYFMxG2rE,96880 +scipy/_lib/pyprima/__init__.py,sha256=YakFMfftDrq3fBu2-_O3FWjeu41511VEPDTtzJ0IKX0,8461 +scipy/_lib/pyprima/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/_lib/pyprima/cobyla/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/__pycache__/cobyla.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/__pycache__/cobylb.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/__pycache__/geometry.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/__pycache__/initialize.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/__pycache__/trustregion.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/__pycache__/update.cpython-312.pyc,, +scipy/_lib/pyprima/cobyla/cobyla.py,sha256=YiuAhtZ5u13uDciL7sc0qxVVpH5t5IKJ2R0X7qTFMwo,22146 +scipy/_lib/pyprima/cobyla/cobylb.py,sha256=T9ZRYBYZdAYvRLJ9sjAYyQb3vdcRxMmj3AukIidw9L0,40764 +scipy/_lib/pyprima/cobyla/geometry.py,sha256=84zrSvKNCr-WnXqFrnnb-nE11yVAI_CME79nhVc4ZvM,10645 +scipy/_lib/pyprima/cobyla/initialize.py,sha256=ft98aJ03PvUUvIXluk-4IUZLbDQPF3ZLdFUhfpRh5Zg,9409 +scipy/_lib/pyprima/cobyla/trustregion.py,sha256=6UNiTytfEyxW1-qHpqBGzcegRyrnx0A82XwLS5b9N_U,25200 +scipy/_lib/pyprima/cobyla/update.py,sha256=PwDRKMY_VAhBKVSOkMUCOSMhGezpfiafIansW1vqI4I,13882 +scipy/_lib/pyprima/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/_lib/pyprima/common/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/_bounds.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/_linear_constraints.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/_nonlinear_constraints.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/_project.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/checkbreak.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/consts.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/evaluate.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/history.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/infos.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/linalg.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/message.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/powalg.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/preproc.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/present.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/ratio.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/redrho.cpython-312.pyc,, +scipy/_lib/pyprima/common/__pycache__/selectx.cpython-312.pyc,, +scipy/_lib/pyprima/common/_bounds.py,sha256=ZzvGVDJigjFkxb4Qkct89SRta7VPS7C_XFm0qKSy090,1636 +scipy/_lib/pyprima/common/_linear_constraints.py,sha256=SZHsoLLWFVtJ1TPPamd0CPXmKmVlnrgT-qCyYZo2CkQ,2162 +scipy/_lib/pyprima/common/_nonlinear_constraints.py,sha256=0OGZwFpa8JqtTm4rZKb2LL8oxx1Sld4ANwfH-00Qy4A,2150 +scipy/_lib/pyprima/common/_project.py,sha256=oX1l_vGwYod1knQ08t_j2MZ1hBOT_szT621GXfk67nE,7863 +scipy/_lib/pyprima/common/checkbreak.py,sha256=kDbwy_CG-0ZUlrfrQ_SKwlxyPjqZHH1-z0HTvXJq7G0,3451 +scipy/_lib/pyprima/common/consts.py,sha256=gw-JKckLhBHPXZLLp1qMrVsqNP9PJ-kcgtBvfCajk-g,1310 +scipy/_lib/pyprima/common/evaluate.py,sha256=aKVctlTqacdI_n329ipEH-ZTpQNwAX-01UavdsXlUeY,3150 +scipy/_lib/pyprima/common/history.py,sha256=c6vWe7XJ5JMzRm7TzaPfYhmHlaZGoUDZzEvLdfZNbAA,1361 +scipy/_lib/pyprima/common/infos.py,sha256=fcIk6zFWQrtUhtvOHYcYUzZCDmgEAY39fjRshjOb9M4,704 +scipy/_lib/pyprima/common/linalg.py,sha256=QwbXquUpao34qwFoQreJ7ocxacCs5pO_7p9Gn9TbB78,14280 +scipy/_lib/pyprima/common/message.py,sha256=D1UwykQhQ16hekF4-wxC1Xw1Qs9gsm_0hXG-yf3VK20,9663 +scipy/_lib/pyprima/common/powalg.py,sha256=BWD8urM3sF_T0e47iHZCKvjIZgcDxsDrLHMtDMcQoUE,6785 +scipy/_lib/pyprima/common/preproc.py,sha256=Ge0SyRxy3f47uf1anX8WmFjfkOdw82czkMgC8FlDiJs,13820 +scipy/_lib/pyprima/common/present.py,sha256=TvFOVG53WvXwjsTqz2tfZzgmV0Uv7dlX0DQ1e2IO92M,146 +scipy/_lib/pyprima/common/ratio.py,sha256=ePcZVLwu4NB29FgVx-qYr3Yvgf_9Wx16Lyz9qbjJDyM,1823 +scipy/_lib/pyprima/common/redrho.py,sha256=ES_D2yucGa_uMGcvlSL8-z4ZxPv2BKoK8mCMw1DZqvE,1258 +scipy/_lib/pyprima/common/selectx.py,sha256=8IYf6BB-OnOOnuxn8_9YsrllaLFLtIKQY5NqTHRc61Q,14120 +scipy/_lib/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/_lib/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test__gcutils.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test__pep440.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test__testutils.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test__util.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_array_api.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_bunch.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_ccallback.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_config.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_deprecation.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_doccer.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_import_cycles.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_public_api.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_scipy_version.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_tmpdirs.cpython-312.pyc,, +scipy/_lib/tests/__pycache__/test_warnings.cpython-312.pyc,, +scipy/_lib/tests/test__gcutils.py,sha256=Uadt4yXwuLDMCSbf4cpMszR_5NOeVQC1E_v4NZAeJR4,3729 +scipy/_lib/tests/test__pep440.py,sha256=u9hPoolK4AoIIS-Rq74Du5SJu5og2RxMwgaAvGgWvRo,2277 +scipy/_lib/tests/test__testutils.py,sha256=P4WDJpUgy19wD9tknQSjIivuQvZF7YUBGSBWlur2QRA,800 +scipy/_lib/tests/test__util.py,sha256=9zybOhYxYvQc81PLe_HIFNxHsT0C9oe-rV2Cr-fgBNk,23719 +scipy/_lib/tests/test_array_api.py,sha256=15tPmoYPl9eALgQGG0FsjgWsNcYES2kiXDva04dHlvc,16566 +scipy/_lib/tests/test_bunch.py,sha256=USL2wl6PT4gAuuNk5CipnNrG45GZPZ8y1B7BqtIDqKM,6389 +scipy/_lib/tests/test_ccallback.py,sha256=wQ0Bwewx7KWJWspmdTYTPjRgm8A3A5mZ1ssLIig5wfE,6040 +scipy/_lib/tests/test_config.py,sha256=j1Ppp6DCZy9wMxTmBEGxq4MScvsQXTQk7268EnNnPFQ,1244 +scipy/_lib/tests/test_deprecation.py,sha256=-7bcTKJauUjBjMpeiFtt5iGwIWlAVu-wZq81iqCePMQ,440 +scipy/_lib/tests/test_doccer.py,sha256=vhmDDKE2ZtfSYGBlF3hd5qL3YU9xqc4FgfgLoEL5qbI,4150 +scipy/_lib/tests/test_import_cycles.py,sha256=B9BwSx-9po3YQBeEjn7f1l4ytddO7W6ykC0Oo5_vFv8,843 +scipy/_lib/tests/test_public_api.py,sha256=isTpcGRdWlKU8uoR2olr8SDQJXsBfzMeVznOHPKhALc,17567 +scipy/_lib/tests/test_scipy_version.py,sha256=kVoxuBUidCHsVpvybRPoVJzkv2hUixRwuDAEAqPgpaA,918 +scipy/_lib/tests/test_tmpdirs.py,sha256=EQ4i2N4jzmkH_dxfra9zrXYk6Xzh2q1zhaHpWkBlXGM,1450 +scipy/_lib/tests/test_warnings.py,sha256=TMjFMSHiulDDrSEjXIjNwgaiRAa_2Qh3SJzsJVsBW14,5006 +scipy/_lib/uarray.py,sha256=4X0D3FBQR6HOYcwMftjH-38Kt1nkrS-eD4c5lWL5DGo,815 +scipy/cluster/__init__.py,sha256=pgzWiWR5smQ3rwud2dhnLn6dpkD5lju_moElQp_zhoE,880 +scipy/cluster/__pycache__/__init__.cpython-312.pyc,, +scipy/cluster/__pycache__/hierarchy.cpython-312.pyc,, +scipy/cluster/__pycache__/vq.cpython-312.pyc,, +scipy/cluster/_hierarchy.cpython-312-darwin.so,sha256=z0CSWFAPCmUWzyLTUl6Qid9h-fAH1z9NW5Hsdd5UIkE,220624 +scipy/cluster/_optimal_leaf_ordering.cpython-312-darwin.so,sha256=7YxLiyKdl95bqNUakZqRkVvRcYWWd8Y_VSOrNld4dL8,151904 +scipy/cluster/_vq.cpython-312-darwin.so,sha256=ei4rakpYRp9X6NPHe3v8i_4a7Y9MmMTwhm5lREyD7hs,111912 +scipy/cluster/hierarchy.py,sha256=zf3tEeKWzmGSvp3eczP-J0NvawzGD9YKsCtv32wsgcw,156594 +scipy/cluster/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/cluster/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-312.pyc,, +scipy/cluster/tests/__pycache__/test_disjoint_set.cpython-312.pyc,, +scipy/cluster/tests/__pycache__/test_hierarchy.cpython-312.pyc,, +scipy/cluster/tests/__pycache__/test_vq.cpython-312.pyc,, +scipy/cluster/tests/hierarchy_test_data.py,sha256=7syUYdIaDVr7hgvMliX0CW4386utjBJn1DOgX0USXls,6850 +scipy/cluster/tests/test_disjoint_set.py,sha256=EuHGBE3ZVEMnWFbCn8tjI-_6CWrNXfpnv5bUBa9qhWI,5525 +scipy/cluster/tests/test_hierarchy.py,sha256=zvtgsxBksJSrVrP6LGB8uUP257hiKgP-xT0RuCxzJMk,50225 +scipy/cluster/tests/test_vq.py,sha256=qZ26WI32gKbvYFyR70keKYoaHz0HSd4Yb8uqEP0H2Xo,18258 +scipy/cluster/vq.py,sha256=HKFZDBazq35WOj8_1Ofg875dG2mHioCDmQAB82sR6GY,30899 +scipy/conftest.py,sha256=MNicQEsguyB3ehyLIRi3Os_XTePqT3g6kAlWTOpqlyw,28827 +scipy/constants/__init__.py,sha256=1Iqylk8TvAxegNKIcFIUVXwiH5ItKpdKtCcVPhEBvPQ,14839 +scipy/constants/__pycache__/__init__.cpython-312.pyc,, +scipy/constants/__pycache__/_codata.cpython-312.pyc,, +scipy/constants/__pycache__/_constants.cpython-312.pyc,, +scipy/constants/__pycache__/codata.cpython-312.pyc,, +scipy/constants/__pycache__/constants.cpython-312.pyc,, +scipy/constants/_codata.py,sha256=AFMXvNXhGnz1xRQgoAJzmaXG45FJ86Ek4iOC3DhM0QI,202549 +scipy/constants/_constants.py,sha256=1BiP8rT7BdaAwCpLbpXQzrCVCcIJPmmc4oh1fg5WHOo,10571 +scipy/constants/codata.py,sha256=ThmW8ohzndi-4-WtyVXxSrW40MnLIz1XoqRcm2RgSHw,614 +scipy/constants/constants.py,sha256=w7sGxSidD2Q9Ged0Sn1pnL-qqD1ssEP1A8sZWeLWBeI,2250 +scipy/constants/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/constants/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/constants/tests/__pycache__/test_codata.cpython-312.pyc,, +scipy/constants/tests/__pycache__/test_constants.cpython-312.pyc,, +scipy/constants/tests/test_codata.py,sha256=gxakBdJjXuXFPPgJvJAj50s4IXCJH3whaeXZjEcso-g,2854 +scipy/constants/tests/test_constants.py,sha256=Gz5YfzcqFnZsHuuZDZ4QOcegWL-2IGIZwZ9cNp-ubTM,4247 +scipy/datasets/__init__.py,sha256=X_9AbefPK1_pg-eG7g3nn--JhoHeDsrEFbJfbI5Hyak,2802 +scipy/datasets/__pycache__/__init__.cpython-312.pyc,, +scipy/datasets/__pycache__/_download_all.cpython-312.pyc,, +scipy/datasets/__pycache__/_fetchers.cpython-312.pyc,, +scipy/datasets/__pycache__/_registry.cpython-312.pyc,, +scipy/datasets/__pycache__/_utils.cpython-312.pyc,, +scipy/datasets/_download_all.py,sha256=0EcULBirC2swuv5lyb5NcuSOkdE_ye-BW86tYNPb6Mw,2174 +scipy/datasets/_fetchers.py,sha256=pkPYiP2slFv-4XYbKDLdca74ScE7Z-IR9O7jmXQNEDA,7092 +scipy/datasets/_registry.py,sha256=br0KfyalEbh5yrQLznQ_QvBtmN4rMsm0UxOjnsJp4OQ,1072 +scipy/datasets/_utils.py,sha256=-g2ZHfgwk0_U6NdouBgZAUjy3ByTxmGR1uZ0QIEcyjI,3053 +scipy/datasets/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/datasets/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/datasets/tests/__pycache__/test_data.cpython-312.pyc,, +scipy/datasets/tests/test_data.py,sha256=6DJtyMDmwi_ghOrDuryVakZQExFq-MIKiuJi_Cr7kdM,4213 +scipy/differentiate/__init__.py,sha256=nZ3imDWtf1QzImE-xsrYHE4kuOa8tEuc99Hl0zAFqzI,621 +scipy/differentiate/__pycache__/__init__.cpython-312.pyc,, +scipy/differentiate/__pycache__/_differentiate.cpython-312.pyc,, +scipy/differentiate/_differentiate.py,sha256=PLdwWwhQ3Ec5kKGruwtuhNxBrXV5xwHEuEpFYUMST8w,51458 +scipy/differentiate/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/differentiate/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/differentiate/tests/__pycache__/test_differentiate.cpython-312.pyc,, +scipy/differentiate/tests/test_differentiate.py,sha256=6rE4bDGNyOPpVQa9DRExwXA4Zg3By3tLNW6KYfJAdtc,27724 +scipy/fft/__init__.py,sha256=0cjHIwyHnjoz1XUUe3OB70vrQR0-pFp8Uv34-U-FGRg,3632 +scipy/fft/__pycache__/__init__.cpython-312.pyc,, +scipy/fft/__pycache__/_backend.cpython-312.pyc,, +scipy/fft/__pycache__/_basic.cpython-312.pyc,, +scipy/fft/__pycache__/_basic_backend.cpython-312.pyc,, +scipy/fft/__pycache__/_debug_backends.cpython-312.pyc,, +scipy/fft/__pycache__/_fftlog.cpython-312.pyc,, +scipy/fft/__pycache__/_fftlog_backend.cpython-312.pyc,, +scipy/fft/__pycache__/_helper.cpython-312.pyc,, +scipy/fft/__pycache__/_realtransforms.cpython-312.pyc,, +scipy/fft/__pycache__/_realtransforms_backend.cpython-312.pyc,, +scipy/fft/_backend.py,sha256=QmcIF8mRvg13Hht5Rq_PKklnMwqdFcCbQkbrMJevd2E,6738 +scipy/fft/_basic.py,sha256=Cn3UMMIEvyllWsaP5yApNJrQgkCr-RxEhznDsiBZIR0,64353 +scipy/fft/_basic_backend.py,sha256=JLolZzpiiDT0CoKLrcvyQA1fEdLSSx1XDQZL_oF7boA,7443 +scipy/fft/_debug_backends.py,sha256=RlvyunZNqaDDsI3-I6QH6GSBz_faT6EN4OONWsvMtR8,598 +scipy/fft/_fftlog.py,sha256=Cth8ohZNXtZ8QurKG-OZbI5VxeJThcrPPOjKNczEIsM,7999 +scipy/fft/_fftlog_backend.py,sha256=n1QNDL1P8R4Q_jeuFezvnjYNFojRvxCWeH6vlE5b1Ao,5357 +scipy/fft/_helper.py,sha256=TFg6LmEt4kwkCgll5_uHB6q8uyW2TZZJ0fMOSdpeFtA,11514 +scipy/fft/_pocketfft/LICENSE.md,sha256=wlSytf0wrjyJ02ugYXMFY7l2D8oE8bdGobLDFX2ix4k,1498 +scipy/fft/_pocketfft/__init__.py,sha256=dROVDi9kRvkbSdynd3L09tp9_exzQ4QqG3xnNx78JeU,207 +scipy/fft/_pocketfft/__pycache__/__init__.cpython-312.pyc,, +scipy/fft/_pocketfft/__pycache__/basic.cpython-312.pyc,, +scipy/fft/_pocketfft/__pycache__/helper.cpython-312.pyc,, +scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-312.pyc,, +scipy/fft/_pocketfft/basic.py,sha256=4HR-eRDb6j4YR4sqKnTikFmG0tnUIXxa0uImnB6_JVs,8138 +scipy/fft/_pocketfft/helper.py,sha256=DFmGP6euSFWiRGUQota_tHtqbSpKWVDirEiPK_na33c,6959 +scipy/fft/_pocketfft/pypocketfft.cpython-312-darwin.so,sha256=yGMGZ7hn9SX-584nKyXPWTCxeAjYA9Uc97bpxTe6Buk,946368 +scipy/fft/_pocketfft/realtransforms.py,sha256=4TmqAkCDQK3gs1ddxXY4rOrVfvQqO8NyVtOzziUGw6E,3344 +scipy/fft/_pocketfft/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/fft/_pocketfft/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/fft/_pocketfft/tests/__pycache__/test_basic.cpython-312.pyc,, +scipy/fft/_pocketfft/tests/__pycache__/test_real_transforms.cpython-312.pyc,, +scipy/fft/_pocketfft/tests/test_basic.py,sha256=jsqSZLy8m3mJsFT39EonX7a0iKMjDzApyZTvowcKAuw,35633 +scipy/fft/_pocketfft/tests/test_real_transforms.py,sha256=rlDsGFXc9h2Z8_WCwd0nsKgaDWdeOOE4M-j-wHR2gXk,16864 +scipy/fft/_realtransforms.py,sha256=W1aqqoRdI6rFgipBXmAXsDZURiGQ3wTj9Xx6s89jylM,26450 +scipy/fft/_realtransforms_backend.py,sha256=u4y4nBGCxpTLVqxK1J7xV6tcpeC3-8iiSEXLOcRM9wI,2389 +scipy/fft/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/fft/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/fft/tests/__pycache__/mock_backend.cpython-312.pyc,, +scipy/fft/tests/__pycache__/test_backend.cpython-312.pyc,, +scipy/fft/tests/__pycache__/test_basic.cpython-312.pyc,, +scipy/fft/tests/__pycache__/test_fftlog.cpython-312.pyc,, +scipy/fft/tests/__pycache__/test_helper.cpython-312.pyc,, +scipy/fft/tests/__pycache__/test_multithreading.cpython-312.pyc,, +scipy/fft/tests/__pycache__/test_real_transforms.cpython-312.pyc,, +scipy/fft/tests/mock_backend.py,sha256=p17Hfg6xuoF6Ldxwe1PZ-79Lf_r9FyJUR00N4TokM8k,2685 +scipy/fft/tests/test_backend.py,sha256=DFJ6OKV6gRw4p9OuVfy1ENTeLJCbYS2GuppwpJnwQGQ,4285 +scipy/fft/tests/test_basic.py,sha256=kMHssdoGQcHlcAKPgYWovjNf8ferb37JAf2Igi3U7zY,23050 +scipy/fft/tests/test_fftlog.py,sha256=xxi01Q2gQEozFBgy-A5714FccESVWWvRF1M-hOeB-qs,7616 +scipy/fft/tests/test_helper.py,sha256=KaJHU9jEbFhQ0AYf6GzqZrTeReJrPzSaEA45WM4-tBI,19275 +scipy/fft/tests/test_multithreading.py,sha256=JMSXQocScFghpsy47zov03R5MbEY0Z3ROGt6GxFeWzo,2150 +scipy/fft/tests/test_real_transforms.py,sha256=5TT3lX9ZwqcIOmCxOXQNAyggIh0-5sgxfqGbjPQinBg,9705 +scipy/fftpack/__init__.py,sha256=rLCBFC5Dx5ij_wmL7ChiGmScYlgu0mhaWtrJaz_rBt0,3155 +scipy/fftpack/__pycache__/__init__.cpython-312.pyc,, +scipy/fftpack/__pycache__/_basic.cpython-312.pyc,, +scipy/fftpack/__pycache__/_helper.cpython-312.pyc,, +scipy/fftpack/__pycache__/_pseudo_diffs.cpython-312.pyc,, +scipy/fftpack/__pycache__/_realtransforms.cpython-312.pyc,, +scipy/fftpack/__pycache__/basic.cpython-312.pyc,, +scipy/fftpack/__pycache__/helper.cpython-312.pyc,, +scipy/fftpack/__pycache__/pseudo_diffs.cpython-312.pyc,, +scipy/fftpack/__pycache__/realtransforms.cpython-312.pyc,, +scipy/fftpack/_basic.py,sha256=Sk_gfswmWKb3za6wrU_mIrRVBl69qjzAu9ltznbDCKs,13098 +scipy/fftpack/_helper.py,sha256=8r6Hh2FA5qTzYyn8y4jfaG41FXMfqQyK6SN8x1dIbaE,3348 +scipy/fftpack/_pseudo_diffs.py,sha256=T39Owz8EgL4oqmViBT0ggen9DXOtNHWRxh-n6I7pLyw,15936 +scipy/fftpack/_realtransforms.py,sha256=2k91B3tSnFm6gKsQn-hRGx4J238CKvqwvQevKgDMuaQ,19222 +scipy/fftpack/basic.py,sha256=i2CMMS__L3UtFFqe57E0cs7AZ4U6VO-Ted1KhU7_wNc,577 +scipy/fftpack/convolve.cpython-312-darwin.so,sha256=gSNfD3kyfWQzZrZbUHRSbIPYPPM5P9H-2McHZiFGVO0,114288 +scipy/fftpack/helper.py,sha256=M7jTN4gQIRWpkArQR13bI7WN6WcW-AabxKgrOHRvfeQ,580 +scipy/fftpack/pseudo_diffs.py,sha256=h0vkjsSqAThy7OdTkYWVxQqZ3rILohg7MXJqf5CGMTE,658 +scipy/fftpack/realtransforms.py,sha256=9-mR-VV3W14oTaD6pB5-RIDV3vkTBQmGCcxfbA8GYH0,595 +scipy/fftpack/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/fftpack/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/fftpack/tests/__pycache__/test_basic.cpython-312.pyc,, +scipy/fftpack/tests/__pycache__/test_helper.cpython-312.pyc,, +scipy/fftpack/tests/__pycache__/test_import.cpython-312.pyc,, +scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-312.pyc,, +scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-312.pyc,, +scipy/fftpack/tests/fftw_double_ref.npz,sha256=pgxklBW2RSI5JNg0LMxcCXgByGkBKHo2nlP8kln17E4,162120 +scipy/fftpack/tests/fftw_longdouble_ref.npz,sha256=pAbL1NrQTQxZ3Tj1RBb7SUJMgiKcGgdLakTsDN4gAOM,296072 +scipy/fftpack/tests/fftw_single_ref.npz,sha256=J2qRQTGOb8NuSrb_VKYbZAVO-ISbZg8XNZ5fVBtDxSY,95144 +scipy/fftpack/tests/test.npz,sha256=Nt6ASiLY_eoFRZDOSd3zyFmDi32JGTxWs7y2YMv0N5c,11968 +scipy/fftpack/tests/test_basic.py,sha256=xq92TCdPbZbh6DStQ2dTc958GYSe453goeijDJoDGrQ,30472 +scipy/fftpack/tests/test_helper.py,sha256=8JaPSJOwsk5XXOf1zFahJ_ktUTfNGSk2-k3R6e420XI,1675 +scipy/fftpack/tests/test_import.py,sha256=dzyXQHtsdW2WL5ruVp_-MsqSQd_n-tuyq22okrzXlGw,1156 +scipy/fftpack/tests/test_pseudo_diffs.py,sha256=ZJU6AkkH6jKjebu_-Ant-dT6tUGwo1Jx9c5kou1floU,13733 +scipy/fftpack/tests/test_real_transforms.py,sha256=KxSsIxsMzdeif5Jej3MuERF3lC8Cyv_UZnJhLPuKpIU,24460 +scipy/integrate/LICENSE_DOP,sha256=7Zv1jG100_rZ2S0dZ9m_-BQdirYN54RRawcRNk_UM1c,3572 +scipy/integrate/__init__.py,sha256=CmPLfkF66jXhHsKyQPOsvFEc9nxicRYwl6WDAa7cfJk,4373 +scipy/integrate/__pycache__/__init__.cpython-312.pyc,, +scipy/integrate/__pycache__/_bvp.cpython-312.pyc,, +scipy/integrate/__pycache__/_cubature.cpython-312.pyc,, +scipy/integrate/__pycache__/_lebedev.cpython-312.pyc,, +scipy/integrate/__pycache__/_ode.cpython-312.pyc,, +scipy/integrate/__pycache__/_odepack_py.cpython-312.pyc,, +scipy/integrate/__pycache__/_quad_vec.cpython-312.pyc,, +scipy/integrate/__pycache__/_quadpack_py.cpython-312.pyc,, +scipy/integrate/__pycache__/_quadrature.cpython-312.pyc,, +scipy/integrate/__pycache__/_tanhsinh.cpython-312.pyc,, +scipy/integrate/__pycache__/dop.cpython-312.pyc,, +scipy/integrate/__pycache__/lsoda.cpython-312.pyc,, +scipy/integrate/__pycache__/odepack.cpython-312.pyc,, +scipy/integrate/__pycache__/quadpack.cpython-312.pyc,, +scipy/integrate/__pycache__/vode.cpython-312.pyc,, +scipy/integrate/_bvp.py,sha256=Wa__s2B7JyrnfzRthkKOQ-yjWf6Q8mBdpgqVceYJcNI,41294 +scipy/integrate/_cubature.py,sha256=DotC8hiRaXTpml88iHQjqMvFZ4OSGpviPYQ1wmPhi84,25783 +scipy/integrate/_dop.cpython-312-darwin.so,sha256=BZSGSoL-mGYxj8-zY6Hl4PmP8JOEvvTIolRPFXNL4b8,85368 +scipy/integrate/_ivp/__init__.py,sha256=gKFR_pPjr8fRLgAGY5sOzYKGUFu2nGX8x1RrXT-GZZc,256 +scipy/integrate/_ivp/__pycache__/__init__.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/base.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/bdf.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/common.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/ivp.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/lsoda.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/radau.cpython-312.pyc,, +scipy/integrate/_ivp/__pycache__/rk.cpython-312.pyc,, +scipy/integrate/_ivp/base.py,sha256=TnBAK0wJLgpQLboH4z-ReE4ebTZFcQzIqRb9bj6tdUg,10529 +scipy/integrate/_ivp/bdf.py,sha256=pbdaKuisouZsw17SaK9R2KloWHggnVz3ekTIzO87duY,17501 +scipy/integrate/_ivp/common.py,sha256=GVKTcx-QO7WPr2ejNAi94aEdMv03zFVOr24Q1w2rZ2I,15745 +scipy/integrate/_ivp/dop853_coefficients.py,sha256=OrYvW0Hu6X7sOh37FU58gNkgC77KVpYclewv_ARGMAE,7237 +scipy/integrate/_ivp/ivp.py,sha256=qhb0LMhfoCdp_wC_k7zbSLa_Vo4tn4zkj583jnbPjwk,31824 +scipy/integrate/_ivp/lsoda.py,sha256=WNQ_nNxLf8FbCT-EMcS-3gsMLq9Gvy4B5n_G4hie9KU,10162 +scipy/integrate/_ivp/radau.py,sha256=0KpFk0Me857geCXbbvAyTkqbrO8OI_2kLTdzGLpqYlY,19676 +scipy/integrate/_ivp/rk.py,sha256=-l1jAJF_T5SeaZsRb1muFHFZ1cYUfVXZQNydMwOJEFY,22800 +scipy/integrate/_ivp/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-312.pyc,, +scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-312.pyc,, +scipy/integrate/_ivp/tests/test_ivp.py,sha256=OaUmXnr2t7mAOsNd1cFOeDlc94U-wuZyN1JyKHGdtDI,42961 +scipy/integrate/_ivp/tests/test_rk.py,sha256=K9UxZghBzSL2BzmgLndPJcWOWV4Nr530TGKWakpsoeM,1326 +scipy/integrate/_lebedev.py,sha256=nf4kdsPOziZyaUu_navuh6MijsyvEjy-FfjRhBmNxNw,262106 +scipy/integrate/_ode.py,sha256=xTCs9IUtbtFcEsLa5n6kon-164nE6kbizgfj89yXAZc,50612 +scipy/integrate/_odepack.cpython-312-darwin.so,sha256=E9KnPzkEN6XqIFlGG8FeZnoK1nu3LSLMzMAlMxq7cgU,86624 +scipy/integrate/_odepack_py.py,sha256=9KMWur0vrdVrBsmPQRmkiC1U6HsUvEdZakGvxUjQoOE,11236 +scipy/integrate/_quad_vec.py,sha256=04YU451OTscxe1x2GNFa7WN-NXftT6oQl71VaOr2_6w,21663 +scipy/integrate/_quadpack.cpython-312-darwin.so,sha256=IZOeydNRTZJH--UPm-K8bqqMhGR9eooDNdGI5r1xs6I,104240 +scipy/integrate/_quadpack_py.py,sha256=hZW9ex9x82eAF-6vML56FkppXXz4h9IVi4fKyAqK6SM,54607 +scipy/integrate/_quadrature.py,sha256=xIOz961GKmYlq4yRavQ-RXy1IXyeiEGVTw1IFR6ReD0,49749 +scipy/integrate/_rules/__init__.py,sha256=JNlDLTPYR-FVDeWbm9BHOot47OA8tvOj22g2iJlEsBg,328 +scipy/integrate/_rules/__pycache__/__init__.cpython-312.pyc,, +scipy/integrate/_rules/__pycache__/_base.cpython-312.pyc,, +scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-312.pyc,, +scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-312.pyc,, +scipy/integrate/_rules/__pycache__/_genz_malik.cpython-312.pyc,, +scipy/integrate/_rules/_base.py,sha256=iwb872yqwq2Y9LbCTujUKI1CvwZurApCeJAlOR4wrnE,17927 +scipy/integrate/_rules/_gauss_kronrod.py,sha256=ULpHMJRd0J99IFwNufur9BYG8EQhxlGj-OdCBgnE8yk,8473 +scipy/integrate/_rules/_gauss_legendre.py,sha256=KJSMmztXRqTvpmkB-ky-WSVIqAMg_GcWoewTcRxJ1Cw,1733 +scipy/integrate/_rules/_genz_malik.py,sha256=104fosqAnmCI992oY-Z9V_QiuG2ruWLmGS2U_EdshEw,7308 +scipy/integrate/_tanhsinh.py,sha256=2PpDKsfAYbDhAipgbYOquA3By3bF_huijKWk1SKD8SY,61994 +scipy/integrate/_test_multivariate.cpython-312-darwin.so,sha256=wnWvm10C51M8H31OtK1C4rdaCMqu5CQHZ601INOWt14,50664 +scipy/integrate/_vode.cpython-312-darwin.so,sha256=WuH7POVUitZTlsAO6tk99kMIDydT4cbt3U8bTr-IQsg,120840 +scipy/integrate/dop.py,sha256=Kx5Ed_Te81X09bvGmBUq3-_kQNdTIsOdO7ykjEpEG9c,422 +scipy/integrate/lsoda.py,sha256=sDSCG4ZCdIZqraaFTAuwY21-dKGR5JK1kWBpZoaQ0Hk,438 +scipy/integrate/odepack.py,sha256=G5KiKninKFyYgF756_LtDGB68BGk7IwPidUOywFpLQo,545 +scipy/integrate/quadpack.py,sha256=vQNE5jQ-dFpH26er1i8LJSkylFVbeSgVGLwSRQawfYg,604 +scipy/integrate/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/integrate/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test__quad_vec.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test_banded_ode_solvers.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test_bvp.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test_cubature.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test_integrate.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test_quadpack.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test_quadrature.cpython-312.pyc,, +scipy/integrate/tests/__pycache__/test_tanhsinh.cpython-312.pyc,, +scipy/integrate/tests/test__quad_vec.py,sha256=j0vhUf6x2lPWWVn8h9hG02W9ZOzU_C9w8ZpJ9-ES5aI,7157 +scipy/integrate/tests/test_banded_ode_solvers.py,sha256=6XDqthVuZzB1tzMF610nBbsN-ylf77AzKl6eIesx4hw,9403 +scipy/integrate/tests/test_bvp.py,sha256=4hxpKpf03EVqxbFXkW5dgTynODyBLf1p9cICLo15hb0,20221 +scipy/integrate/tests/test_cubature.py,sha256=IM4bDXNfTDCujv7Bb25pUIgR4GPUxcTDl1Kt7zCOM1c,37039 +scipy/integrate/tests/test_integrate.py,sha256=U8xGoJdn12hTg5ChjHtKNJ_Za4XizUbAeAqIgMXFMCc,24823 +scipy/integrate/tests/test_quadpack.py,sha256=69NSMQWbVeIdFNgluwHzWODgqMsqJ94nrgv2OfRD7OI,29837 +scipy/integrate/tests/test_quadrature.py,sha256=zcZLRmUO5Zh97Bqlz5WQke_ncUBRx88qcBgOhHjU6UI,29681 +scipy/integrate/tests/test_tanhsinh.py,sha256=ugdJH-kNA4OvEmH5-c3ZaFC0OPl_MjaHYjndU_lZKc8,44339 +scipy/integrate/vode.py,sha256=DPRqm2oBQx6KKi5tl9dDVpXEdAO--W0WpRQEyLeQpf4,424 +scipy/interpolate/__init__.py,sha256=i0mcQWXv0KbAn44vld8w-9NrRy-z_w0xf5_kQnBTtK8,4073 +scipy/interpolate/__pycache__/__init__.cpython-312.pyc,, +scipy/interpolate/__pycache__/_bary_rational.cpython-312.pyc,, +scipy/interpolate/__pycache__/_bsplines.cpython-312.pyc,, +scipy/interpolate/__pycache__/_cubic.cpython-312.pyc,, +scipy/interpolate/__pycache__/_fitpack2.cpython-312.pyc,, +scipy/interpolate/__pycache__/_fitpack_impl.cpython-312.pyc,, +scipy/interpolate/__pycache__/_fitpack_py.cpython-312.pyc,, +scipy/interpolate/__pycache__/_fitpack_repro.cpython-312.pyc,, +scipy/interpolate/__pycache__/_interpolate.cpython-312.pyc,, +scipy/interpolate/__pycache__/_ndbspline.cpython-312.pyc,, +scipy/interpolate/__pycache__/_ndgriddata.cpython-312.pyc,, +scipy/interpolate/__pycache__/_pade.cpython-312.pyc,, +scipy/interpolate/__pycache__/_polyint.cpython-312.pyc,, +scipy/interpolate/__pycache__/_rbf.cpython-312.pyc,, +scipy/interpolate/__pycache__/_rbfinterp.cpython-312.pyc,, +scipy/interpolate/__pycache__/_rbfinterp_common.cpython-312.pyc,, +scipy/interpolate/__pycache__/_rbfinterp_np.cpython-312.pyc,, +scipy/interpolate/__pycache__/_rbfinterp_xp.cpython-312.pyc,, +scipy/interpolate/__pycache__/_rgi.cpython-312.pyc,, +scipy/interpolate/__pycache__/dfitpack.cpython-312.pyc,, +scipy/interpolate/__pycache__/fitpack.cpython-312.pyc,, +scipy/interpolate/__pycache__/fitpack2.cpython-312.pyc,, +scipy/interpolate/__pycache__/interpnd.cpython-312.pyc,, +scipy/interpolate/__pycache__/interpolate.cpython-312.pyc,, +scipy/interpolate/__pycache__/ndgriddata.cpython-312.pyc,, +scipy/interpolate/__pycache__/polyint.cpython-312.pyc,, +scipy/interpolate/__pycache__/rbf.cpython-312.pyc,, +scipy/interpolate/_bary_rational.py,sha256=7fXt48Jnqjpm1SxXMVa4Em7DwMG20ztDqhpLLDnLqec,29413 +scipy/interpolate/_bsplines.py,sha256=Grc2RwSO2a39bgDLUnWgmjLtw69FIgPlkttnkHuwkag,90686 +scipy/interpolate/_cubic.py,sha256=43ZTzXx8y814x9ENHkm-CoBj_EZvRlPjYMdMjVm9T60,40394 +scipy/interpolate/_dfitpack.cpython-312-darwin.so,sha256=qNJ34CqMeMSZnaA5FawyyIN7u8y53BA3x4zPjzihv-c,312368 +scipy/interpolate/_dierckx.cpython-312-darwin.so,sha256=0t67xIKypMigWcbGzRTvb7orNV_CsuZXwXLYkTxTpC4,109376 +scipy/interpolate/_fitpack.cpython-312-darwin.so,sha256=gYscXkozt-JjUclYkGI2rmLQAKZw690NdmH2OiFrIZc,121088 +scipy/interpolate/_fitpack2.py,sha256=JhjnBItSNgIwQxwEYFrRnLaOB-4RpzZlONM9Z-XiS6U,90341 +scipy/interpolate/_fitpack_impl.py,sha256=hILtqHWDVZLHMtn733teZhVQmB8JJTuSsG7Zatdtc7k,28887 +scipy/interpolate/_fitpack_py.py,sha256=XjU-kc64_r2sMqEKa83kVTz6yu4tVuYYNamd16FzWCA,32531 +scipy/interpolate/_fitpack_repro.py,sha256=sBfZSJbpVy9BfSDdwjxX1670WF9CSPXPcaLqiLgYhNc,52250 +scipy/interpolate/_interpnd.cpython-312-darwin.so,sha256=RD_bGdfKsaT6jcNliZBPi44d5bQ-rcvELZiKB_NLLm8,204672 +scipy/interpolate/_interpolate.py,sha256=qgtZ-9PzD3DRj2ouFbCvUXe0KU4z-A7MI4x4aLkm4oc,81898 +scipy/interpolate/_ndbspline.py,sha256=Cn59KG-OyS7dbf20aEkc9lhjmTivvAA5yeuYpdm1oOE,17831 +scipy/interpolate/_ndgriddata.py,sha256=EQO3oNjAUukmWOte4vV_4UiUvabNvk10qqP0oVqWPlg,12154 +scipy/interpolate/_pade.py,sha256=OBorKWc3vCSGlsWrajoF1_7WeNd9QtdbX0wOHLdRI2A,1827 +scipy/interpolate/_polyint.py,sha256=I7iJfOAgVlxazOAwVRRwg01nnT8xJwngdh6D1pGsEvI,39078 +scipy/interpolate/_ppoly.cpython-312-darwin.so,sha256=cIhml8muS_mO0e8P4begW48kGrcvIbDbTU5pjVvfHsQ,200208 +scipy/interpolate/_rbf.py,sha256=rKLmfGuZTVDJ3qWIyy_mqI7u5EYijMnFGJ9EUFqnT0g,11767 +scipy/interpolate/_rbfinterp.py,sha256=sk9PvSsWKmTtlpAzorTpZj0VjBGHIdrAiq-DiKF1T7c,19504 +scipy/interpolate/_rbfinterp_common.py,sha256=YSKWb68Lb9CXfwoCm1u71tq2il-0lxknFfwgufdkHKE,973 +scipy/interpolate/_rbfinterp_np.py,sha256=-N02r-8uoZ5I15YF2C4UvCJoA841SUtN8spyxpo22JE,3003 +scipy/interpolate/_rbfinterp_pythran.cpython-312-darwin.so,sha256=rYFfSwzdAVWwqnCPMwlAOUXCDWfB_JeLb3fSrDX7Z_o,303000 +scipy/interpolate/_rbfinterp_xp.py,sha256=A4r4GkCe7LJD4FzZl69FcuIgmrYr1tPlrO6I8dO0TFs,7654 +scipy/interpolate/_rgi.py,sha256=PCTaU97SQz6hdzvOlBLRu8dOhiWizTXkYBi_e8XSqfU,32343 +scipy/interpolate/_rgi_cython.cpython-312-darwin.so,sha256=nzqylQFhItAcWQmw-Ea3nVAbWuuazVk86xHU4LnMPro,116240 +scipy/interpolate/dfitpack.py,sha256=lRSKk1GcuWHJCyBXjRlg5lupLzugQHrR47tWL0vYvzc,594 +scipy/interpolate/fitpack.py,sha256=aCH6A3dRouuXW47tK5lEdd2pJa39LCkewY-1zTlI8Hc,702 +scipy/interpolate/fitpack2.py,sha256=P15_3gM5eZQYb_-K3c70xKdeIGM81u5WAkVhY8ei4N0,817 +scipy/interpolate/interpnd.py,sha256=3jlLsX7kgW7s2YPBkT-W-iA_qxTbbpm72YCIzZ_B4go,609 +scipy/interpolate/interpolate.py,sha256=Aiu_dJ_oxq-Y1VXns5N5u5K1Wng2hzCgRgRiDhTAiVI,754 +scipy/interpolate/ndgriddata.py,sha256=VbvvoDPdWmrk8871y5olPS9StX0S_B27j_oGMAyj8QQ,636 +scipy/interpolate/polyint.py,sha256=ek1EtbIbLLwehb8XDSKeNvIdjTfDQoQ9CSu4TbY8Vbo,672 +scipy/interpolate/rbf.py,sha256=6oBxdpsKY8bH36nQnRNiLB9C1bNri8b2PHz9IsUIr-w,519 +scipy/interpolate/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/interpolate/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_bary_rational.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_bsplines.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_fitpack.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_fitpack2.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_gil.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_interpnd.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_interpolate.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_ndgriddata.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_pade.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_polyint.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_rbf.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_rbfinterp.cpython-312.pyc,, +scipy/interpolate/tests/__pycache__/test_rgi.cpython-312.pyc,, +scipy/interpolate/tests/data/bug-1310.npz,sha256=jWgDwLOY8nBMI28dG56OXt4GvRZaCrsPIoKBq71FWuk,2648 +scipy/interpolate/tests/data/estimate_gradients_hang.npy,sha256=QGwQhXQX_16pjYzSiUXJ0OT1wk-SpIrQ6Pq5Vb8kd_E,35680 +scipy/interpolate/tests/data/gcvspl.npz,sha256=A86BVabLoMG_CiRBoQwigZH5Ft7DbLggcjQpgRKWu6g,3138 +scipy/interpolate/tests/test_bary_rational.py,sha256=FAVnCJp47GqLiyFvAwxdbTJ19tGtU5zlMn6Qe4Ce9zI,16910 +scipy/interpolate/tests/test_bsplines.py,sha256=rdOVoAnRO_uSxmvqNGrD3drg1yDzFXVFjHhGWUYbJM0,153446 +scipy/interpolate/tests/test_fitpack.py,sha256=acG5xw_5Aqq8nMsvIoZ1KPz7vRxMqcfB0WBcBkCgpkg,17399 +scipy/interpolate/tests/test_fitpack2.py,sha256=QjYhewXBSGk6HNwicBRz6kKgvuD9KneyYlg4Y1EMfyc,62605 +scipy/interpolate/tests/test_gil.py,sha256=BPC_Ig9lRg28mVHIqdSqWnwBKLukTXFkbrdqUYuskq4,1831 +scipy/interpolate/tests/test_interpnd.py,sha256=c9zFLhOMViZnMji86zTr6FYj-nAPixvKzT2weEMP6_Y,15527 +scipy/interpolate/tests/test_interpolate.py,sha256=SQjJ-Veo1RsFd7nMBbGgzgCSFSkVoGEoY69SCSf7JjY,102263 +scipy/interpolate/tests/test_ndgriddata.py,sha256=MqDsDmIoqT3dxQN-NN830zKwb8dPsmt6goT0AyOxRRk,10994 +scipy/interpolate/tests/test_pade.py,sha256=5gmdgTBoJGsY-d813it9JP5Uh8Wc88dz3vPQ2pRZdNk,3868 +scipy/interpolate/tests/test_polyint.py,sha256=cEV25IpJAnJIAL82EzTQSGse79D7qDR_fV4dOk62qvg,37482 +scipy/interpolate/tests/test_rbf.py,sha256=cg3vMfbKsBZDLCfVe7atEXHbhtaAfk_ks02vioLq3DE,7004 +scipy/interpolate/tests/test_rbfinterp.py,sha256=eZPUOhIfoPrB3_9Onje7bvE-_iuz9fb8r6n1sn2l1l8,20714 +scipy/interpolate/tests/test_rgi.py,sha256=le3DUXU6C3JcWKUViRUq9s5gRzhnIkiLoLjYdDu54kg,49988 +scipy/io/__init__.py,sha256=V7XGFwDG6dzpq6Yamyz82M6abAtHQ-XciEyNF8Rga-w,2775 +scipy/io/__pycache__/__init__.cpython-312.pyc,, +scipy/io/__pycache__/_fortran.cpython-312.pyc,, +scipy/io/__pycache__/_idl.cpython-312.pyc,, +scipy/io/__pycache__/_mmio.cpython-312.pyc,, +scipy/io/__pycache__/_netcdf.cpython-312.pyc,, +scipy/io/__pycache__/harwell_boeing.cpython-312.pyc,, +scipy/io/__pycache__/idl.cpython-312.pyc,, +scipy/io/__pycache__/mmio.cpython-312.pyc,, +scipy/io/__pycache__/netcdf.cpython-312.pyc,, +scipy/io/__pycache__/wavfile.cpython-312.pyc,, +scipy/io/_fast_matrix_market/__init__.py,sha256=jKXsxc05BZCedYkHhoqrSp3z6VSQ0VrFqeRvb8U1-eA,17238 +scipy/io/_fast_matrix_market/__pycache__/__init__.cpython-312.pyc,, +scipy/io/_fast_matrix_market/_fmm_core.cpython-312-darwin.so,sha256=Y8LKej8ue1fF6n8y06S78gp6QVXsjNwf6ekUZDZHG3Q,2178496 +scipy/io/_fortran.py,sha256=pgbB0LbOKEfPk07y-9IQXUyT7Kx_wHP0AyGPLtC53yM,10893 +scipy/io/_harwell_boeing/__init__.py,sha256=90qYbBzDEoTMG8ouVLGnTU2GMsY4BYOOtwJdoKT3Zz8,164 +scipy/io/_harwell_boeing/__pycache__/__init__.cpython-312.pyc,, +scipy/io/_harwell_boeing/__pycache__/_fortran_format_parser.cpython-312.pyc,, +scipy/io/_harwell_boeing/__pycache__/hb.cpython-312.pyc,, +scipy/io/_harwell_boeing/_fortran_format_parser.py,sha256=qvHmXonHRYMYTc-sV7TxRwxdrt4WRZk4rgawnwcleQ0,9003 +scipy/io/_harwell_boeing/hb.py,sha256=JM1Jh2EnA9zZsE7P3CcYmIc7n3hPzJ8yRKNWARGcSx4,19395 +scipy/io/_harwell_boeing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-312.pyc,, +scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-312.pyc,, +scipy/io/_harwell_boeing/tests/test_fortran_format.py,sha256=hPH4AmfUmyBrDU3C_Rx3j7yaGEjefQJOai4rfxMHuV0,2383 +scipy/io/_harwell_boeing/tests/test_hb.py,sha256=jYbRWktqO5bgXDh8i9O_u_KDTpYQcMx_blw7Pn66Nd0,2516 +scipy/io/_idl.py,sha256=sgL0II6EcAe6Mtp_SdqmAIvvMGq9UFsWeH7M8RTGvIY,27000 +scipy/io/_mmio.py,sha256=Z5aX35ByVM6wBw4V42v4DInsc9KPyY8yck9V0FnzkKk,32076 +scipy/io/_netcdf.py,sha256=YCXUusfyVs5f7sq-_xYCZS2HBYXs_1X1NAD8darpgFw,39676 +scipy/io/arff/__init__.py,sha256=czaV8hvY6JnmEn2qyU3_fzcy_P55aXVT09OzGnhJT9I,805 +scipy/io/arff/__pycache__/__init__.cpython-312.pyc,, +scipy/io/arff/__pycache__/_arffread.cpython-312.pyc,, +scipy/io/arff/__pycache__/arffread.cpython-312.pyc,, +scipy/io/arff/_arffread.py,sha256=RL7qcF1oAVhsVsJHsgo8zQdP8_7JFjl2y5u981xU_80,26143 +scipy/io/arff/arffread.py,sha256=KW6mASZrW2J1wmC3GYucy1EO7y-rg5MgcGDMyMTpfw4,575 +scipy/io/arff/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/io/arff/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/io/arff/tests/__pycache__/test_arffread.cpython-312.pyc,, +scipy/io/arff/tests/data/iris.arff,sha256=fTS6VWSX6dwoM16mYoo30dvLoJChriDcLenHAy0ZkVM,7486 +scipy/io/arff/tests/data/missing.arff,sha256=ga__Te95i1Yf-yu2kmYDBVTz0xpSTemz7jS74_OfI4I,120 +scipy/io/arff/tests/data/nodata.arff,sha256=DBXdnIe28vrbf4C-ar7ZgeFIa0kGD4pDBJ4YP-z4QHQ,229 +scipy/io/arff/tests/data/quoted_nominal.arff,sha256=01mPSc-_OpcjXFy3EoIzKdHCmzWSag4oK1Ek2tUc6_U,286 +scipy/io/arff/tests/data/quoted_nominal_spaces.arff,sha256=bcMOl-E0I5uTT27E7bDTbW2mYOp9jS8Yrj0NfFjQdKU,292 +scipy/io/arff/tests/data/test1.arff,sha256=nUFDXUbV3sIkur55rL4qvvBdqUTbzSRrTiIPwmtmG8I,191 +scipy/io/arff/tests/data/test10.arff,sha256=va7cXiWX_AnHf-_yz25ychD8hOgf7-sEMJITGwQla30,199009 +scipy/io/arff/tests/data/test11.arff,sha256=G-cbOUUxuc3859vVkRDNjcLRSnUu8-T-Y8n0dSpvweo,241 +scipy/io/arff/tests/data/test2.arff,sha256=COGWCYV9peOGLqlYWhqG4ANT2UqlAtoVehbJLW6fxHw,300 +scipy/io/arff/tests/data/test3.arff,sha256=jUTWGaZbzoeGBneCmKu6V6RwsRPp9_0sJaSCdBg6tyI,72 +scipy/io/arff/tests/data/test4.arff,sha256=mtyuSFKUeiRR2o3mNlwvDCxWq4DsHEBHj_8IthNzp-M,238 +scipy/io/arff/tests/data/test5.arff,sha256=2Q_prOBCfM_ggsGRavlOaJ_qnWPFf2akFXJFz0NtTIE,365 +scipy/io/arff/tests/data/test6.arff,sha256=V8FNv-WUdurutFXKTOq8DADtNDrzfW65gyOlv-lquOU,195 +scipy/io/arff/tests/data/test7.arff,sha256=rxsqdev8WeqC_nKJNwetjVYXA1-qCzWmaHlMvSaVRGk,559 +scipy/io/arff/tests/data/test8.arff,sha256=c34srlkU8hkXYpdKXVozEutiPryR8bf_5qEmiGQBoG4,429 +scipy/io/arff/tests/data/test9.arff,sha256=ZuXQQzprgmTXxENW7we3wBJTpByBlpakrvRgG8n7fUk,311 +scipy/io/arff/tests/test_arffread.py,sha256=bWB6uAqr6Iadm3fWhhlo6M2fM0WTKrLTC1BmXYKidJ4,13094 +scipy/io/harwell_boeing.py,sha256=BzISbfgVnrO3vYx-mP2xkLqh9r3oq64NNPbEY03P6v0,538 +scipy/io/idl.py,sha256=A1QV5h6xBa1cTIejjsc1NfjG0MqMbxqFqXicC2OLNrM,504 +scipy/io/matlab/__init__.py,sha256=PMqq8WBOEOPH_v5IVpuxrBTqXOFBJVuegOCml76pr1s,2247 +scipy/io/matlab/__pycache__/__init__.cpython-312.pyc,, +scipy/io/matlab/__pycache__/_byteordercodes.cpython-312.pyc,, +scipy/io/matlab/__pycache__/_mio.cpython-312.pyc,, +scipy/io/matlab/__pycache__/_mio4.cpython-312.pyc,, +scipy/io/matlab/__pycache__/_mio5.cpython-312.pyc,, +scipy/io/matlab/__pycache__/_mio5_params.cpython-312.pyc,, +scipy/io/matlab/__pycache__/_miobase.cpython-312.pyc,, +scipy/io/matlab/__pycache__/byteordercodes.cpython-312.pyc,, +scipy/io/matlab/__pycache__/mio.cpython-312.pyc,, +scipy/io/matlab/__pycache__/mio4.cpython-312.pyc,, +scipy/io/matlab/__pycache__/mio5.cpython-312.pyc,, +scipy/io/matlab/__pycache__/mio5_params.cpython-312.pyc,, +scipy/io/matlab/__pycache__/mio5_utils.cpython-312.pyc,, +scipy/io/matlab/__pycache__/mio_utils.cpython-312.pyc,, +scipy/io/matlab/__pycache__/miobase.cpython-312.pyc,, +scipy/io/matlab/__pycache__/streams.cpython-312.pyc,, +scipy/io/matlab/_byteordercodes.py,sha256=AUMjfdIARtCGqyMgDDJBGa_EncP5ioYrEzyZqXOLRxU,1983 +scipy/io/matlab/_mio.py,sha256=uKitl4DrzKwzk1mDXFFIZMHTZACww6zYGBqMZjwqHQc,13955 +scipy/io/matlab/_mio4.py,sha256=W9FaF7ryhbT10TEgHcuovZkm7w2zIU3tDtnb5gIlYlQ,20993 +scipy/io/matlab/_mio5.py,sha256=hBvVcnAUZX2hLZzQDfSnlUQVWtQlD53ur8w7VkpT9Qs,33989 +scipy/io/matlab/_mio5_params.py,sha256=skRcKG70vOlVMSb1TO67LB5312zuOUSrcOK7mOCcUss,8201 +scipy/io/matlab/_mio5_utils.cpython-312-darwin.so,sha256=6olBAHcf5w4oTYlOiyvHtWcsGegU4EHFxYphmY6edyo,206176 +scipy/io/matlab/_mio_utils.cpython-312-darwin.so,sha256=y1K5ZaHCrmzSLBcwEROLQKvt3e27G4MrJ3vVAugjG20,94544 +scipy/io/matlab/_miobase.py,sha256=AmMxD5puIqxYYv8MCSdF2wUDqwOTSoyo9I6hh51myaQ,13102 +scipy/io/matlab/_streams.cpython-312-darwin.so,sha256=DBJZ4wttU3CIBHD9P4J7Zz4keeIGbF69e-1RnSzEvCI,132992 +scipy/io/matlab/byteordercodes.py,sha256=fHZVESDgIeYzGYtRlknPQ2nUqscQQ_4FhQc_ClkjBvQ,528 +scipy/io/matlab/mio.py,sha256=2b0WwgQ0rBkoJ4X0hgPl889PpR7Q0i7ibSLtTQVuTto,539 +scipy/io/matlab/mio4.py,sha256=hkhpBa4p0euf2rUjJviBWJ4TJs1wkUads3mX1fgDYMc,508 +scipy/io/matlab/mio5.py,sha256=jEFeEEkXWOhziPreDt0SqfAtOo9JMauxoODAbbXHmoQ,638 +scipy/io/matlab/mio5_params.py,sha256=2RWROlfc8RmXmcXGyM-be107Tm55ibc_U7DztJ2b4fc,593 +scipy/io/matlab/mio5_utils.py,sha256=DYiQfx5BkyDVnK4nZ3xPa-5tbpZE7WRx4SIdBmPVfSI,520 +scipy/io/matlab/mio_utils.py,sha256=VZPx03BNFbrQjB1CNbDCvvXUuP0_VoNRFV1R0YoB2iw,518 +scipy/io/matlab/miobase.py,sha256=3qQoq8Y7ZQpHIufUCzg6RAeaLqU3qTAozmuYbaOd7BI,565 +scipy/io/matlab/streams.py,sha256=0Aww9GRGGnRmiAMBAzIAXsFGySu5YCUNG-cHP1omYjI,513 +scipy/io/matlab/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/io/matlab/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_byteordercodes.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_mio.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_mio5_utils.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_mio_funcs.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_mio_utils.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_miobase.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_pathological.cpython-312.pyc,, +scipy/io/matlab/tests/__pycache__/test_streams.cpython-312.pyc,, +scipy/io/matlab/tests/data/bad_miuint32.mat,sha256=CVkYHp_U4jxYKRRHSuZ5fREop4tJjnZcQ02DKfObkRA,272 +scipy/io/matlab/tests/data/bad_miutf8_array_name.mat,sha256=V-jfVMkYyy8qRGcOIsNGcoO0GCgTxchrsQUBGBnfWHE,208 +scipy/io/matlab/tests/data/big_endian.mat,sha256=2ttpiaH2B6nmHnq-gsFeMvZ2ZSLOlpzt0IJiqBTcc8M,273 +scipy/io/matlab/tests/data/broken_utf8.mat,sha256=nm8aotRl6NIxlM3IgPegKR3EeevYZoJCrYpV4Sa1T5I,216 +scipy/io/matlab/tests/data/corrupted_zlib_checksum.mat,sha256=X4dvE7K9DmGEF3D6I-48hC86W41jB54H7bD8KTXjtYA,276 +scipy/io/matlab/tests/data/corrupted_zlib_data.mat,sha256=DfE1YBH-pYw-dAaEeKA6wZcyKeo9GlEfrzZtql-fO_w,3451 +scipy/io/matlab/tests/data/debigged_m4.mat,sha256=8QbD-LzoYbKSfOYPRRw-oelDJscwufYp5cqLfZ1hB0c,1024 +scipy/io/matlab/tests/data/japanese_utf8.txt,sha256=rgxiBH7xmEKF91ZkB3oMLrqABBXINEMHPXDKdZXNBEY,270 +scipy/io/matlab/tests/data/little_endian.mat,sha256=FQP_2MNod-FFF-JefN7ZxovQ6QLCdHQ0DPL_qBCP44Y,265 +scipy/io/matlab/tests/data/logical_sparse.mat,sha256=qujUUpYewaNsFKAwGpYS05z7kdUv9TQZTHV5_lWhRrs,208 +scipy/io/matlab/tests/data/malformed1.mat,sha256=DTuTr1-IzpLMBf8u5DPb3HXmw9xJo1aWfayA5S_3zUI,2208 +scipy/io/matlab/tests/data/miuint32_for_miint32.mat,sha256=romrBP_BS46Sl2-pKWsUnxYDad2wehyjq4wwLaVqums,272 +scipy/io/matlab/tests/data/miutf8_array_name.mat,sha256=Vo8JptFr-Kg2f2cEoDg8LtELSjVNyccdJY74WP_kqtc,208 +scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat,sha256=bvdmj6zDDUIpOfIP8J4Klo107RYCDd5VK5gtOYx3GsU,8168 +scipy/io/matlab/tests/data/one_by_zero_char.mat,sha256=Z3QdZjTlOojjUpS0cfBP4XfNQI3GTjqU0n_pnAzgQhU,184 +scipy/io/matlab/tests/data/parabola.mat,sha256=ENWuWX_uwo4Av16dIGOwnbMReAMrShDhalkq8QUI8Rg,729 +scipy/io/matlab/tests/data/single_empty_string.mat,sha256=4uTmX0oydTjmtnhxqi9SyPWCG2I24gj_5LarS80bPik,171 +scipy/io/matlab/tests/data/some_functions.mat,sha256=JA736oG3s8PPdKhdsYK-BndLUsGrJCJAIRBseSIEZtM,1397 +scipy/io/matlab/tests/data/sqr.mat,sha256=3DtGl_V4wABKCDQ0P3He5qfOzpUTC-mINdK73MKS7AM,679 +scipy/io/matlab/tests/data/test3dmatrix_6.1_SOL2.mat,sha256=-odiBIQAbOLERg0Vg682QHGfs7C8MaA_gY77OWR8x78,232 +scipy/io/matlab/tests/data/test3dmatrix_6.5.1_GLNX86.mat,sha256=G5siwvZ-7Uv5KJ6h7AA3OHL6eiFsd8Lnjx4IcoByzCU,232 +scipy/io/matlab/tests/data/test3dmatrix_7.1_GLNX86.mat,sha256=EVj1wPnoyWGIdTpkSj3YAwqzTAm27eqZNxCaJAs3pwU,213 +scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat,sha256=S_Sd3sxorDd8tZ5CxD5_J8vXbfcksLWzhUQY5b82L9g,213 +scipy/io/matlab/tests/data/test_empty_struct.mat,sha256=WoC7g7TyXqNr2T0d5xE3IUq5PRzatE0mxXjqoHX5Xec,173 +scipy/io/matlab/tests/data/test_mat4_le_floats.mat,sha256=2xvn3Cg4039shJl62T-bH-VeVP_bKtwdqvGfIxv8FJ4,38 +scipy/io/matlab/tests/data/test_skip_variable.mat,sha256=pJLVpdrdEb-9SMZxaDu-uryShlIi90l5LfXhvpVipJ0,20225 +scipy/io/matlab/tests/data/testbool_8_WIN64.mat,sha256=_xBw_2oZA7u9Xs6GJItUpSIEV4jVdfdcwzmLNFWM6ow,185 +scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat,sha256=OWOBzNpWTyAHIcZABRytVMcABiRYgEoMyF9gDaIkFe4,536 +scipy/io/matlab/tests/data/testcell_6.5.1_GLNX86.mat,sha256=7111TN_sh1uMHmYx-bjd_v9uaAnWhJMhrQFAtAw6Nvk,536 +scipy/io/matlab/tests/data/testcell_7.1_GLNX86.mat,sha256=62p6LRW6PbM-Y16aUeGVhclTVqS5IxPUtsohe7MjrYo,283 +scipy/io/matlab/tests/data/testcell_7.4_GLNX86.mat,sha256=NkTA8UW98hIQ0t5hGx_leG-MzNroDelYwqx8MPnO63Q,283 +scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat,sha256=AeNaog8HUDCVrIuGICAXYu9SGDsvV6qeGjgvWHrVQho,568 +scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat,sha256=Gl4QA0yYwGxjiajjgWS939WVAM-W2ahNIm9wwMaT5oc,568 +scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat,sha256=CUGtkwIU9CBa0Slx13mbaM67_ec0p-unZdu8Z4YYM3c,228 +scipy/io/matlab/tests/data/testcellnest_7.4_GLNX86.mat,sha256=TeTk5yjl5j_bcnmIkpzuYHxGGQXNu-rK6xOsN4t6lX8,228 +scipy/io/matlab/tests/data/testcomplex_4.2c_SOL2.mat,sha256=WOwauWInSVUFBuOJ1Bo3spmUQ3UWUIlsIe4tYGlrU7o,176 +scipy/io/matlab/tests/data/testcomplex_6.1_SOL2.mat,sha256=GpAEccizI8WvlrBPdvlKUv6uKbZOo_cjUK3WVVb2lo4,352 +scipy/io/matlab/tests/data/testcomplex_6.5.1_GLNX86.mat,sha256=3MEbf0zJdQGAO7x-pzFCup2QptfYJHQG59z0vVOdxl4,352 +scipy/io/matlab/tests/data/testcomplex_7.1_GLNX86.mat,sha256=VNHV2AIEkvPuhae1kKIqt5t8AMgUyr0L_CAp-ykLxt4,247 +scipy/io/matlab/tests/data/testcomplex_7.4_GLNX86.mat,sha256=8rWGf5bqY7_2mcd5w5gTYgMkXVePlLL8qT7lh8kApn0,247 +scipy/io/matlab/tests/data/testdouble_4.2c_SOL2.mat,sha256=MzT7OYPEUXHYNPBrVkyKEaG5Cas2aOA0xvrO7l4YTrQ,103 +scipy/io/matlab/tests/data/testdouble_6.1_SOL2.mat,sha256=DpB-mVKx1gsjl-3IbxfxHNuzU5dnuku-MDQCA8kALVI,272 +scipy/io/matlab/tests/data/testdouble_6.5.1_GLNX86.mat,sha256=4hY5VEubavNEv5KvcqQnd7MWWvFUzHXXpYIqUuUt-50,272 +scipy/io/matlab/tests/data/testdouble_7.1_GLNX86.mat,sha256=N2QOOIXPyy0zPZZ_qY7xIDaodMGrTq3oXNBEHZEscw0,232 +scipy/io/matlab/tests/data/testdouble_7.4_GLNX86.mat,sha256=TrkJ4Xx_dC9YrPdewlsOvYs_xag7gT3cN4HkDsJmT8I,232 +scipy/io/matlab/tests/data/testemptycell_5.3_SOL2.mat,sha256=g96Vh9FpNhkiWKsRm4U6KqeKd1hNAEyYSD7IVzdzwsU,472 +scipy/io/matlab/tests/data/testemptycell_6.5.1_GLNX86.mat,sha256=2Zw-cMv-Mjbs2HkSl0ubmh_htFUEpkn7XVHG8iM32o0,472 +scipy/io/matlab/tests/data/testemptycell_7.1_GLNX86.mat,sha256=t5Ar8EgjZ7fkTUHIVpdXg-yYWo_MBaigMDJUGWEIrmU,218 +scipy/io/matlab/tests/data/testemptycell_7.4_GLNX86.mat,sha256=5PPvfOoL-_Q5ou_2nIzIrHgeaOZGFXGxAFdYzCQuwEQ,218 +scipy/io/matlab/tests/data/testfunc_7.4_GLNX86.mat,sha256=ScTKftENe78imbMc0I5ouBlIMcEEmZgu8HVKWAMNr58,381 +scipy/io/matlab/tests/data/testhdf5_7.4_GLNX86.mat,sha256=ZoVbGk38_MCppZ0LRr6OE07HL8ZB4rHXgMj9LwUBgGg,4168 +scipy/io/matlab/tests/data/testmatrix_4.2c_SOL2.mat,sha256=14YMiKAN9JCPTqSDXxa58BK6Un7EM4hEoSGAUuwKWGQ,151 +scipy/io/matlab/tests/data/testmatrix_6.1_SOL2.mat,sha256=ZdjNbcIE75V5Aht5EVBvJX26aabvNqbUH0Q9VBnxBS4,216 +scipy/io/matlab/tests/data/testmatrix_6.5.1_GLNX86.mat,sha256=OB82QgB6SwtsxT4t453OVSj-B777XrHGEGOMgMD1XGc,216 +scipy/io/matlab/tests/data/testmatrix_7.1_GLNX86.mat,sha256=-TYB0kREY7i7gt5x15fOYjXi410pXuDWUFxPYuMwywI,193 +scipy/io/matlab/tests/data/testmatrix_7.4_GLNX86.mat,sha256=l9psDc5K1bpxNeuFlyYIYauswLnOB6dTX6-jvelW0kU,193 +scipy/io/matlab/tests/data/testminus_4.2c_SOL2.mat,sha256=2914WYQajPc9-Guy3jDOLU3YkuE4OXC_63FUSDzJzX0,38 +scipy/io/matlab/tests/data/testminus_6.1_SOL2.mat,sha256=2X2fZKomz0ktBvibj7jvHbEvt2HRA8D6hN9qA1IDicw,200 +scipy/io/matlab/tests/data/testminus_6.5.1_GLNX86.mat,sha256=i364SgUCLSYRjQsyygvY1ArjEaO5uLip3HyU-R7zaLo,200 +scipy/io/matlab/tests/data/testminus_7.1_GLNX86.mat,sha256=gtYNC9_TciYdq8X9IwyGEjiw2f1uCVTGgiOPFOiQbJc,184 +scipy/io/matlab/tests/data/testminus_7.4_GLNX86.mat,sha256=eXcoTM8vKuh4tQnl92lwdDaqssGB6G9boSHh3FOCkng,184 +scipy/io/matlab/tests/data/testmulti_4.2c_SOL2.mat,sha256=Zhyu2KCsseSJ5NARdS00uwddCs4wmjcWNP2LJFns2-Q,240 +scipy/io/matlab/tests/data/testmulti_7.1_GLNX86.mat,sha256=KI3H58BVj6k6MFsj8icSbjy_0Z-jOesWN5cafStLPG8,276 +scipy/io/matlab/tests/data/testmulti_7.4_GLNX86.mat,sha256=Yr4YKCP27yMWlK5UOK3BAEOAyMr-m0yYGcj8v1tCx-I,276 +scipy/io/matlab/tests/data/testobject_6.1_SOL2.mat,sha256=kzLxy_1o1HclPXWyA-SX5gl6LsG1ioHuN4eS6x5iZio,800 +scipy/io/matlab/tests/data/testobject_6.5.1_GLNX86.mat,sha256=dq_6_n0v7cUz9YziXn-gZFNc9xYtNxZ8exTsziWIM7s,672 +scipy/io/matlab/tests/data/testobject_7.1_GLNX86.mat,sha256=3z-boFw0SC5142YPOLo2JqdusPItVzjCFMhXAQNaQUQ,306 +scipy/io/matlab/tests/data/testobject_7.4_GLNX86.mat,sha256=5OwLTMgCBlxsDfiEUzlVjqcSbVQG-X5mIw5JfW3wQXA,306 +scipy/io/matlab/tests/data/testonechar_4.2c_SOL2.mat,sha256=BCvppGhO19-j-vxAvbdsORIiyuJqzCuQog9Ao8V1lvA,40 +scipy/io/matlab/tests/data/testonechar_6.1_SOL2.mat,sha256=ThppTHGJFrUfal5tewS70DL00dSwk1otazuVdJrTioE,200 +scipy/io/matlab/tests/data/testonechar_6.5.1_GLNX86.mat,sha256=SBfN6e7Vz1rAdi8HLguYXcHUHk1viaXTYccdEyhhob4,200 +scipy/io/matlab/tests/data/testonechar_7.1_GLNX86.mat,sha256=m8W9GqvflfAsizkhgAfT0lLcxuegZIWCLNuHVX69Jac,184 +scipy/io/matlab/tests/data/testonechar_7.4_GLNX86.mat,sha256=t9ObKZOLy3vufnER8TlvQcUkd_wmXbJSdQoG4f3rVKY,184 +scipy/io/matlab/tests/data/testscalarcell_7.4_GLNX86.mat,sha256=5LX9sLH7Y6h_N_a1XRN2GuMgp_P7ECpPsXGDOypAJg0,194 +scipy/io/matlab/tests/data/testsimplecell.mat,sha256=Aoeh0PX2yiLDTwkxMEyZ_CNX2mJHZvyfuFJl817pA1c,220 +scipy/io/matlab/tests/data/testsparse_4.2c_SOL2.mat,sha256=dFUcB1gunfWqexgR4YDZ_Ec0w0HffM1DUE1C5PVfDDc,223 +scipy/io/matlab/tests/data/testsparse_6.1_SOL2.mat,sha256=9Sgd_SPkGNim7ZL0xgD71qml3DK0yDHYC7VSNLNQEXA,280 +scipy/io/matlab/tests/data/testsparse_6.5.1_GLNX86.mat,sha256=jp1ILNxLyV6XmCCGxAz529XoZ9dhCqGEO-ExPH70_Pg,328 +scipy/io/matlab/tests/data/testsparse_7.1_GLNX86.mat,sha256=k8QuQ_4Zu7FWTzHjRnHCVZ9Yu5vwNP0WyNzu6TuiY-4,229 +scipy/io/matlab/tests/data/testsparse_7.4_GLNX86.mat,sha256=QbZOCqIvnaK0XOH3kaSXBe-m_1_Rb33psq8E-WMSBTU,229 +scipy/io/matlab/tests/data/testsparsecomplex_4.2c_SOL2.mat,sha256=QMVoBXVyl9RBGvAjLoiW85kAXYJ-hHprUMegEG69A5w,294 +scipy/io/matlab/tests/data/testsparsecomplex_6.1_SOL2.mat,sha256=WfEroAT5YF4HGAKq3jTJxlFrKaTCh3rwlSlKu__VjwA,304 +scipy/io/matlab/tests/data/testsparsecomplex_6.5.1_GLNX86.mat,sha256=e0s6cyoKJeYMArdceHpnKDvtCVcw7XuB44OBDHpoa6U,400 +scipy/io/matlab/tests/data/testsparsecomplex_7.1_GLNX86.mat,sha256=kgHcuq-deI2y8hfkGwlMOkW7lntexdPHfuz0ar6b3jo,241 +scipy/io/matlab/tests/data/testsparsecomplex_7.4_GLNX86.mat,sha256=rYCaWNLXK7f_jjMc6_UvZz6ZDuMCuVRmJV5RyeXiDm8,241 +scipy/io/matlab/tests/data/testsparsefloat_7.4_GLNX86.mat,sha256=hnNV6GZazEeqTXuA9vcOUo4xam_UnKRYGYH9PUGTLv8,219 +scipy/io/matlab/tests/data/teststring_4.2c_SOL2.mat,sha256=cAhec51DlqIYfDXXGaumOE3Hqb3cFWM1UsUK3K_lDP8,375 +scipy/io/matlab/tests/data/teststring_6.1_SOL2.mat,sha256=ciFzNGMO7gjYecony-E8vtOwBY4vXIUhyug6Euaz3Kg,288 +scipy/io/matlab/tests/data/teststring_6.5.1_GLNX86.mat,sha256=yrJrpLiwLvU_LI1D6rw1Pk1qJK1YlC7Cmw7lwyJVLtw,288 +scipy/io/matlab/tests/data/teststring_7.1_GLNX86.mat,sha256=zo7sh-8dMpGqhoNxLEnfz3Oc7RonxiY5j0B3lxk0e8o,224 +scipy/io/matlab/tests/data/teststring_7.4_GLNX86.mat,sha256=igL_CvtAcNEa1nxunDjQZY5wS0rJOlzsUkBiDreJssk,224 +scipy/io/matlab/tests/data/teststringarray_4.2c_SOL2.mat,sha256=pRldk-R0ig1k3ouvaR9oVtBwZsQcDW_b4RBEDYu1-Vk,156 +scipy/io/matlab/tests/data/teststringarray_6.1_SOL2.mat,sha256=B9IdaSsyb0wxjyYyHOj_GDO0laAeWDEJhoEhC9xdm1E,232 +scipy/io/matlab/tests/data/teststringarray_6.5.1_GLNX86.mat,sha256=t4tKGJg2NEg_Ar5MkOjCoQb2hVL8Q_Jdh9FF4TPL_4g,232 +scipy/io/matlab/tests/data/teststringarray_7.1_GLNX86.mat,sha256=lpYkBZX8K-c4FO5z0P9DMfYc7Y-yzyg11J6m-19uYTU,203 +scipy/io/matlab/tests/data/teststringarray_7.4_GLNX86.mat,sha256=lG-c7U-5Bo8j8xZLpd0JAsMYwewT6cAw4eJCZH5xf6E,203 +scipy/io/matlab/tests/data/teststruct_6.1_SOL2.mat,sha256=3GJbA4O7LP57J6IYzmJqTPeSJrEaiNSk-rg7h0ANR1w,608 +scipy/io/matlab/tests/data/teststruct_6.5.1_GLNX86.mat,sha256=fRbqAnzTeOU3dTQx7O24MfMVFr6pM5u594FRrPPkYJE,552 +scipy/io/matlab/tests/data/teststruct_7.1_GLNX86.mat,sha256=mCtI_Yot08NazvWHvehOZbTV4bW_I4-D5jBgJ6T9EbI,314 +scipy/io/matlab/tests/data/teststruct_7.4_GLNX86.mat,sha256=52qaF4HRCtPl1jE6ljbkEl2mofZVAPpmBxrm-J5OTTI,314 +scipy/io/matlab/tests/data/teststructarr_6.1_SOL2.mat,sha256=vneCpWBwApBGfeKzdZcybyajxjR-ZYf64j0l08_hU84,528 +scipy/io/matlab/tests/data/teststructarr_6.5.1_GLNX86.mat,sha256=gqhRpSfNNB5SR9sCp-wWrvokr5VV_heGnvco6dmfOvY,472 +scipy/io/matlab/tests/data/teststructarr_7.1_GLNX86.mat,sha256=6VDU0mtTBEG0bBHqKP1p8xq846eMhSZ_WvBZv8MzE7M,246 +scipy/io/matlab/tests/data/teststructarr_7.4_GLNX86.mat,sha256=ejtyxeeX_W1a2rNrEUUiG9txPW8_UtSgt8IaDOxE2pg,246 +scipy/io/matlab/tests/data/teststructnest_6.1_SOL2.mat,sha256=sbi0wUwOrbU-gBq3lyDwhAbvchdtOJkflOR_MU7uGKA,496 +scipy/io/matlab/tests/data/teststructnest_6.5.1_GLNX86.mat,sha256=uTkKtrYBTuz4kICVisEaG7V5C2nJDKjy92mPDswTLPE,416 +scipy/io/matlab/tests/data/teststructnest_7.1_GLNX86.mat,sha256=o4F2jOhYyNpJCo-BMg6v_ITZQvjenXfXHLq94e7iwRo,252 +scipy/io/matlab/tests/data/teststructnest_7.4_GLNX86.mat,sha256=CNXO12O6tedEuMG0jNma4qfbTgCswAbHwh49a3uE3Yk,252 +scipy/io/matlab/tests/data/testunicode_7.1_GLNX86.mat,sha256=KV97FCW-1XZiXrwXJoZPbgyAht79oIFHa917W1KFLwE,357 +scipy/io/matlab/tests/data/testunicode_7.4_GLNX86.mat,sha256=9-8xzACZleBkMjZnbr8t4Ncs9B6mbzrONDblPnteBPU,357 +scipy/io/matlab/tests/data/testvec_4_GLNX86.mat,sha256=GQzR3mBVS266_NBfrRC9X0dLgmeu8Jl4r4ZYMOrn1V0,93 +scipy/io/matlab/tests/test_byteordercodes.py,sha256=FCHBAxeQZlhvTXw-AO-ukwTWvpN7NzmncBEDJ1P4de4,938 +scipy/io/matlab/tests/test_mio.py,sha256=jCSoZtHIe__LVPFfhia66BNzCiBQg0BBJpoL53YWJaE,47184 +scipy/io/matlab/tests/test_mio5_utils.py,sha256=eacgGg0TaQXOkG7iaeYovtWyjPgYCY50mHPoPjnHMTI,5389 +scipy/io/matlab/tests/test_mio_funcs.py,sha256=2BgaB9bSwy2M-4gUBrgKsD290UxjLmyuiI3gW4SbVyo,1390 +scipy/io/matlab/tests/test_mio_utils.py,sha256=GX85RuLqr2HxS5_f7ZgrxbhswJy2GPQQoQbiQYg0s14,1594 +scipy/io/matlab/tests/test_miobase.py,sha256=CGefrU6m_GpOwaKr_Q93Z5zKp5nuv791kjxcNNP8iiE,1460 +scipy/io/matlab/tests/test_pathological.py,sha256=-Efeq2x2yAaLK28EKpai1vh4HsZTCteF_hY_vEGWndA,1055 +scipy/io/matlab/tests/test_streams.py,sha256=R8OeacqgwexmDLRHO4eWXJjynD_4VeAdnv7vv6dOJfo,7543 +scipy/io/mmio.py,sha256=Dc5HqR8BXOD0wir63VTVczuZcLjSxEjbSbeZd4y27po,526 +scipy/io/netcdf.py,sha256=RKhmlybZwbFNKA4US6xLX6O2IUDCmdkToosPt4bAUX0,533 +scipy/io/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/io/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/io/tests/__pycache__/test_fortran.cpython-312.pyc,, +scipy/io/tests/__pycache__/test_idl.cpython-312.pyc,, +scipy/io/tests/__pycache__/test_mmio.cpython-312.pyc,, +scipy/io/tests/__pycache__/test_netcdf.cpython-312.pyc,, +scipy/io/tests/__pycache__/test_paths.cpython-312.pyc,, +scipy/io/tests/__pycache__/test_wavfile.cpython-312.pyc,, +scipy/io/tests/data/Transparent Busy.ani,sha256=vwoK3ysYo87-TwzvjerHjFjSPIGpw83jjiMDXcHPWjA,4362 +scipy/io/tests/data/array_float32_1d.sav,sha256=A_xXWkfS1sQCxP4ONezeEZvlKEXwZ1TPG2rCCFdmBNM,2628 +scipy/io/tests/data/array_float32_2d.sav,sha256=qJmN94pywXznXMHzt-L6DJgaIq_FfruVKJl_LMaI8UU,3192 +scipy/io/tests/data/array_float32_3d.sav,sha256=U7P6As7Nw6LdBY1pTOaW9C-O_NlXLXZwSgbT3H8Z8uk,13752 +scipy/io/tests/data/array_float32_4d.sav,sha256=Tl6erEw_Zq3dwVbVyPXRWqB83u_o4wkIVFOe3wQrSro,6616 +scipy/io/tests/data/array_float32_5d.sav,sha256=VmaBgCD854swYyLouDMHJf4LL6iUNgajEOQf0pUjHjg,7896 +scipy/io/tests/data/array_float32_6d.sav,sha256=lb7modI0OQDweJWbDxEV2OddffKgMgq1tvCy5EK6sOU,19416 +scipy/io/tests/data/array_float32_7d.sav,sha256=pqLWIoxev9sLCs9LLwxFlM4RCFwxHC4Q0dEEz578mpI,3288 +scipy/io/tests/data/array_float32_8d.sav,sha256=R8A004f9XLWvF6eKMNEqIrC6PGP1vLZr9sFqawqM8ZA,13656 +scipy/io/tests/data/array_float32_pointer_1d.sav,sha256=sV7qFNwHK-prG5vODa7m5HYK7HlH_lqdfsI5Y1RWDyg,2692 +scipy/io/tests/data/array_float32_pointer_2d.sav,sha256=b0brvK6xQeezoRuujmEcJNw2v6bfASLM3FSY9u5dMSg,3256 +scipy/io/tests/data/array_float32_pointer_3d.sav,sha256=a_Iyg1YjPBRh6B-N_n_BGIVjFje4K-EPibKV-bPbF7E,13816 +scipy/io/tests/data/array_float32_pointer_4d.sav,sha256=cXrkHHlPyoYstDL_OJ15-55sZOOeDNW2OJ3KWhBv-Kk,6680 +scipy/io/tests/data/array_float32_pointer_5d.sav,sha256=gRVAZ6jeqFZyIQI9JVBHed9Y0sjS-W4bLseb01rIcGs,7960 +scipy/io/tests/data/array_float32_pointer_6d.sav,sha256=9yic-CQiS0YR_ow2yUA2Nix0Nb_YCKMUsIgPhgcJT1c,19480 +scipy/io/tests/data/array_float32_pointer_7d.sav,sha256=Rp1s8RbW8eoEIRTqxba4opAyY0uhTuyy3YkwRlNspQU,3352 +scipy/io/tests/data/array_float32_pointer_8d.sav,sha256=Wk3Dd2ClAwWprXLKZon3blY7aMvMrJqz_NXzK0J5MFY,13720 +scipy/io/tests/data/example_1.nc,sha256=EkfC57dWXeljgXy5sidrJHJG12D1gmQUyPDK18WzlT4,1736 +scipy/io/tests/data/example_2.nc,sha256=wywMDspJ2QT431_sJUr_5DHqG3pt9VTvDJzfR9jeWCk,272 +scipy/io/tests/data/example_3_maskedvals.nc,sha256=P9N92jCJgKJo9VmNd7FeeJSvl4yUUFwBy6JpR4MeuME,1424 +scipy/io/tests/data/fortran-3x3d-2i.dat,sha256=oYCXgtY6qqIqLAhoh_46ob_RVQRcV4uu333pOiLKgRM,451 +scipy/io/tests/data/fortran-mixed.dat,sha256=zTi7RLEnyAat_DdC3iSEcSbyDtAu0aTKwUT-tExjasw,40 +scipy/io/tests/data/fortran-sf8-11x1x10.dat,sha256=KwaOrZOAe-wRhuxvmHIK-Wr59us40MmiA9QyWtIAUaA,888 +scipy/io/tests/data/fortran-sf8-15x10x22.dat,sha256=5ohvjjOUcIsGimSqDhpUUKwflyhVsfwKL5ElQe_SU0I,26408 +scipy/io/tests/data/fortran-sf8-1x1x1.dat,sha256=Djmoip8zn-UcxWGUPKV5wzKOYOf7pbU5L7HaR3BYlec,16 +scipy/io/tests/data/fortran-sf8-1x1x5.dat,sha256=Btgavm3w3c9md_5yFfq6Veo_5IK9KtlLF1JEPeHhZoU,48 +scipy/io/tests/data/fortran-sf8-1x1x7.dat,sha256=L0r9yAEMbfMwYQytzYsS45COqaVk-o_hi6zRY3yIiO4,64 +scipy/io/tests/data/fortran-sf8-1x3x5.dat,sha256=c2LTocHclwTIeaR1Pm3mVMyf5Pl_imfjIFwi4Lpv0Xs,128 +scipy/io/tests/data/fortran-si4-11x1x10.dat,sha256=OesvSIGsZjpKZlZsV74PNwy0Co0KH8-3gxL9-DWoa08,448 +scipy/io/tests/data/fortran-si4-15x10x22.dat,sha256=OJcKyw-GZmhHb8REXMsHDn7W5VP5bhmxgVPIAYG-Fj4,13208 +scipy/io/tests/data/fortran-si4-1x1x1.dat,sha256=1Lbx01wZPCOJHwg99MBDuc6QZKdMnccxNgICt4omfFM,12 +scipy/io/tests/data/fortran-si4-1x1x5.dat,sha256=L1St4yiHTA3v91JjnndYfUrdKfT1bWxckwnnrscEZXc,28 +scipy/io/tests/data/fortran-si4-1x1x7.dat,sha256=Dmqt-tD1v2DiPZkghGGZ9Ss-nJGfei-3yFXPO5Acpk4,36 +scipy/io/tests/data/fortran-si4-1x3x5.dat,sha256=3vl6q93m25jEcZVKD0CuKNHmhZwZKp-rv0tfHoPVP88,68 +scipy/io/tests/data/invalid_pointer.sav,sha256=JmgoISXC4r5fSmI5FqyapvmzQ4qpYLf-9N7_Et1p1HQ,1280 +scipy/io/tests/data/null_pointer.sav,sha256=P_3a_sU614F3InwM82jSMtWycSZkvqRn1apwd8XxbtE,2180 +scipy/io/tests/data/scalar_byte.sav,sha256=dNJbcE5OVDY_wHwN_UBUtfIRd13Oqu-RBEO74g5SsBA,2076 +scipy/io/tests/data/scalar_byte_descr.sav,sha256=DNTmDgDWOuzlQnrceER6YJ0NutUUwZ9tozVMBWQmuuY,2124 +scipy/io/tests/data/scalar_complex32.sav,sha256=NGd-EvmFZgt8Ko5MP3T_TLwyby6yS0BXM_OW8197hpU,2076 +scipy/io/tests/data/scalar_complex64.sav,sha256=gFBWtxuAajazupGFSbvlWUPDYK-JdWgZcEWih2-7IYU,2084 +scipy/io/tests/data/scalar_float32.sav,sha256=EwWQw2JTwq99CHVpDAh4R20R0jWaynXABaE2aTRmXrs,2072 +scipy/io/tests/data/scalar_float64.sav,sha256=iPcDlgF1t0HoabvNLWCbSiTPIa9rvVEbOGGmE_3Ilsk,2076 +scipy/io/tests/data/scalar_heap_pointer.sav,sha256=JXZbPmntXILsNOuLIKL8qdu8gDJekYrlN9DQxAWve0E,2204 +scipy/io/tests/data/scalar_int16.sav,sha256=kDBLbPYGo2pzmZDhyl8rlDv0l6TMEWLIoLtmgJXDMkk,2072 +scipy/io/tests/data/scalar_int32.sav,sha256=IzJwLvEoqWLO5JRaHp8qChfptlauU-ll3rb0TfDDM8Y,2072 +scipy/io/tests/data/scalar_int64.sav,sha256=-aSHQRiaE3wjAxINwuLX33_8qmWl4GUkTH45elTkA-8,2076 +scipy/io/tests/data/scalar_string.sav,sha256=AQ7iZ8dKk9QfnLdP9idKv1ojz0M_SwpL7XAUmbHodDQ,2124 +scipy/io/tests/data/scalar_uint16.sav,sha256=928fmxLsQM83ue4eUS3IEnsLSEzmHBklDA59JAUvGK8,2072 +scipy/io/tests/data/scalar_uint32.sav,sha256=X3RbPhS6_e-u-1S1gMyF7s9ys7oV6ZNwPrJqJ6zIJsk,2072 +scipy/io/tests/data/scalar_uint64.sav,sha256=ffVyS2oKn9PDtWjJdOjSRT2KZzy6Mscgd4u540MPHC4,2076 +scipy/io/tests/data/struct_arrays.sav,sha256=TzH-Gf0JgbP_OgeKYbV8ZbJXvWt1VetdUr6C_ziUlzg,2580 +scipy/io/tests/data/struct_arrays_byte_idl80.sav,sha256=oOmhTnmKlE60-JMJRRMv_zfFs4zqioMN8QA0ldlgQZo,1388 +scipy/io/tests/data/struct_arrays_replicated.sav,sha256=kXU8j9QI2Q8D22DVboH9fwwDQSLVvuWMJl3iIOhUAH8,2936 +scipy/io/tests/data/struct_arrays_replicated_3d.sav,sha256=s3ZUwhT6TfiVfk4AGBSyxYR4FRzo4sZQkTxFCJbIQMI,4608 +scipy/io/tests/data/struct_inherit.sav,sha256=4YajBZcIjqMQ4CI0lRUjXpYDY3rI5vzJJzOYpjWqOJk,2404 +scipy/io/tests/data/struct_pointer_arrays.sav,sha256=fkldO6-RO2uAN_AI9hM6SEaBPrBf8TfiodFGJpViaqg,2408 +scipy/io/tests/data/struct_pointer_arrays_replicated.sav,sha256=eKVerR0LoD9CuNlpwoBcn7BIdj3-8x56VNg--Qn7Hgc,2492 +scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav,sha256=vsqhGpn3YkZEYjQuI-GoX8Jg5Dv8A2uRtP0kzQkq4lg,2872 +scipy/io/tests/data/struct_pointers.sav,sha256=Zq6d5V9ZijpocxJpimrdFTQG827GADBkMB_-6AweDYI,2268 +scipy/io/tests/data/struct_pointers_replicated.sav,sha256=aIXPBIXTfPmd4IaLpYD5W_HUoIOdL5Y3Hj7WOeRM2sA,2304 +scipy/io/tests/data/struct_pointers_replicated_3d.sav,sha256=t1jhVXmhW6VotQMNZ0fv0sDO2pkN4EutGsx5No4VJQs,2456 +scipy/io/tests/data/struct_scalars.sav,sha256=LYICjERzGJ_VvYgtwJ_Up2svQTv8wBzNcVD3nsd_OPg,2316 +scipy/io/tests/data/struct_scalars_replicated.sav,sha256=lw3fC4kppi6BUWAd4n81h8_KgoUdiJl5UIt3CvJIuBs,2480 +scipy/io/tests/data/struct_scalars_replicated_3d.sav,sha256=xVAup6f1dSV_IsSwBQC3KVs0eLEZ6-o5EaZT9yUoDZI,3240 +scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav,sha256=h8CXsW5_ShKR197t_d-TUTlgDqOZ-7wK_EcVGucR-aY,74 +scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav,sha256=gjv__ng9xH_sm34hyxCbCgO4AP--PZAfDOArH5omkjM,3586 +scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav,sha256=H0LLyv2lc2guzYGnx4DWXU6vB57JrRX-G9Dd4qGh0hM,3586 +scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav,sha256=KKz9SXv_R3gX_AVeED2vyhYnj4BvD1uyDiKpCT3ulZ0,17720 +scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav,sha256=YX1g8qdCOAG16vX9G6q4SsfCj2ZVk199jzDQ8S0zWYI,72 +scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav,sha256=bFrsRqw0QXmsaDtjD6TFP8hZ5jEYMyaCmt-ka_C6GNk,1024 +scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav,sha256=zMnhvZvrP4kyOWKVKfbBneyv03xvzgqXYhHNxsAxDJ4,13 +scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav,sha256=GSJpCuezlvHbhP3Cr4jNWmz4zG46XZ6jci2fWtiMN0k,17756 +scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav,sha256=9qTCvpgdz3raecVN1ViggHPnQjBf47xmXod9iCDsEik,17720 +scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav,sha256=EqYBnEgTxTKvaTAtdA5HIl47CCFIje93y4hawR6Pyu0,7792 +scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav,sha256=hGYchxQFjrtvZCBo0ULi-xdZ8krqXcKdTl3NSUfqe8k,90 +scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav,sha256=BoUCDct3GiY_JJV_HoghF3mzAebT18j02c-MOn19KxU,70 +scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav,sha256=R6EJshvQp5YVR4GB9u4Khn5HM1VMfJUj082i8tkBIJ8,1644 +scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav,sha256=t2Mgri3h6JLQDekrwIhDBOaG46OUzHynUz0pKbvOpNU,90 +scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav,sha256=iSGyqouX53NaEB33tzKXa11NRIY97GG40_pqWF_k5LQ,126 +scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav,sha256=yCv0uh-ux_skJsxeOjzog0YBk3ZQO_kw5HJHMqtVyI0,90 +scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav,sha256=oiMVsQV9-qGBz_ZwsfAkgA9BZXNjXbH4zxCGvvdT0RY,120 +scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav,sha256=e97XoPrPGJDIh8nO6mii__ViY5yVlmt4OnPQoDN1djs,134 +scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav,sha256=wbonKlzvzQ_bQYyBsj-GwnihZOhn0uxfKhL_nENCGNc,150 +scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav,sha256=Uu5QPQcbtnFlnxOd4zFGxpiTC4wgdp6JOoYJ2VMZIU0,164 +scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav,sha256=1F67h8tr2xz0C5K21T9y9gspcGA0qnSOzsl2vjArAMs,116 +scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav,sha256=TJvGU7GpgXdCrdrjzMlDtpieDMnDK-lWMMqlWjT23BY,89 +scipy/io/tests/data/various_compressed.sav,sha256=H-7pc-RCQx5y6_IbHk1hB6OfnhvuPyW6EJq4EwI9iMc,1015 +scipy/io/tests/test_fortran.py,sha256=xpwrE71XkNWFhwNR6Bwvi9YXTZsCkAxArG5xQDRsBTo,11363 +scipy/io/tests/test_idl.py,sha256=WpLmp16ewO47m6od8oTtMKvVPasHuCoEwXqQJ0aBW7k,20531 +scipy/io/tests/test_mmio.py,sha256=6UwDD2Cb9AgZYWgsE0ttXaIEJUinWs5WYmDleIlp9ww,29188 +scipy/io/tests/test_netcdf.py,sha256=GgeIeBJNHfOTxGHAG-QSfHBzTgwpcvdKfRk_teaWrFM,19557 +scipy/io/tests/test_paths.py,sha256=3f12UO-N11JJjkw8jBgVAhz5KVrkokJbHrnvfklDhNA,3190 +scipy/io/tests/test_wavfile.py,sha256=Gy2si0t3bm74fAI4BWNI40oamULqByj2Ts6U_uJKqng,19094 +scipy/io/wavfile.py,sha256=sBoggGo4lHeKoFxmEIX3PrQCwuVo7CoWtGWrWkMS6GM,30691 +scipy/linalg/__init__.pxd,sha256=0MlO-o_Kr8gg--_ipXEHFGtB8pZdHX8VX4wLYe_UzPg,53 +scipy/linalg/__init__.py,sha256=iEBmLSZ-jQZQMSVgjGMz5fUAU3UPHiwnO2PlpsC3nBw,7426 +scipy/linalg/__pycache__/__init__.cpython-312.pyc,, +scipy/linalg/__pycache__/_basic.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_cholesky.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_cossin.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_ldl.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_lu.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_polar.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_qr.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_qz.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_schur.cpython-312.pyc,, +scipy/linalg/__pycache__/_decomp_svd.cpython-312.pyc,, +scipy/linalg/__pycache__/_expm_frechet.cpython-312.pyc,, +scipy/linalg/__pycache__/_matfuncs.cpython-312.pyc,, +scipy/linalg/__pycache__/_matfuncs_inv_ssq.cpython-312.pyc,, +scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-312.pyc,, +scipy/linalg/__pycache__/_misc.cpython-312.pyc,, +scipy/linalg/__pycache__/_procrustes.cpython-312.pyc,, +scipy/linalg/__pycache__/_sketches.cpython-312.pyc,, +scipy/linalg/__pycache__/_solvers.cpython-312.pyc,, +scipy/linalg/__pycache__/_special_matrices.cpython-312.pyc,, +scipy/linalg/__pycache__/_testutils.cpython-312.pyc,, +scipy/linalg/__pycache__/basic.cpython-312.pyc,, +scipy/linalg/__pycache__/blas.cpython-312.pyc,, +scipy/linalg/__pycache__/decomp.cpython-312.pyc,, +scipy/linalg/__pycache__/decomp_cholesky.cpython-312.pyc,, +scipy/linalg/__pycache__/decomp_lu.cpython-312.pyc,, +scipy/linalg/__pycache__/decomp_qr.cpython-312.pyc,, +scipy/linalg/__pycache__/decomp_schur.cpython-312.pyc,, +scipy/linalg/__pycache__/decomp_svd.cpython-312.pyc,, +scipy/linalg/__pycache__/interpolative.cpython-312.pyc,, +scipy/linalg/__pycache__/lapack.cpython-312.pyc,, +scipy/linalg/__pycache__/matfuncs.cpython-312.pyc,, +scipy/linalg/__pycache__/misc.cpython-312.pyc,, +scipy/linalg/__pycache__/special_matrices.cpython-312.pyc,, +scipy/linalg/_basic.py,sha256=gsLUOREyZ2Sy0VVlQJ-4F0qBuDLpajgJUVQtqdURIgw,88414 +scipy/linalg/_batched_linalg.cpython-312-darwin.so,sha256=WaAFYOPStegsmwVMgclJZq_gvwrlXssHULmGl-lAzfo,129672 +scipy/linalg/_blas_subroutines.h,sha256=B2Y9A7ejwt3PHSLLS5mX2VhF6jwP3XgKMmt53O3cowg,18174 +scipy/linalg/_cythonized_array_utils.cpython-312-darwin.so,sha256=XS_zSSmwHnG190hZUZx0SvkmerevHrYAZm8c9iZ-c1w,277776 +scipy/linalg/_cythonized_array_utils.pxd,sha256=OlWTbJt3gmdrfRFyx_Vz7GTmDTjr8dids5HA4TfC6R0,890 +scipy/linalg/_cythonized_array_utils.pyi,sha256=HZWXvJdpXGcydTEjkaL_kXIcxpcMqBBfFz7ZhscsRNo,340 +scipy/linalg/_decomp.py,sha256=PD0WiKh7YGdXMG617YHI5F4LbShnkgMdT_qotWp3M2E,62717 +scipy/linalg/_decomp_cholesky.py,sha256=_6nFa234U9YzppafGmUBfpPByu-f8x_gGDuMJ3H7YN0,14846 +scipy/linalg/_decomp_cossin.py,sha256=SP7prnWk9eqL4q2bXiBgHILa-21SDaJNCCk_hIw9Xcc,9605 +scipy/linalg/_decomp_interpolative.cpython-312-darwin.so,sha256=7h3X4jbrM7ZuN4UAbvcOndcgssiSvYOsDk6waxr8moU,550856 +scipy/linalg/_decomp_ldl.py,sha256=d5w6AAyDwxNwvV8EZOs144ZGUdF8II77NphA_f2k8Nc,12612 +scipy/linalg/_decomp_lu.py,sha256=ZsK-rPPluRtdAjlmWwLFH2Xo6CHkOQ5hGHsYLpXlQSM,13498 +scipy/linalg/_decomp_lu_cython.cpython-312-darwin.so,sha256=foEMAlnsghwWHIyGkMTGCbS7HFcmLGyeTP6bF-bz-SQ,113560 +scipy/linalg/_decomp_lu_cython.pyi,sha256=IAaDvMbX0WTWyOuKd1mWJqXq1bKusxj56HE1Npl_sCY,346 +scipy/linalg/_decomp_polar.py,sha256=RRNkQ7Vk6tEtvA6f1wTkP1t-FXQ_COU9lXguzbNpaK0,3654 +scipy/linalg/_decomp_qr.py,sha256=xD7J3UqwN3a9gyF9l_Za9t0ErP_1kmEA8gFiTK8Mofk,15506 +scipy/linalg/_decomp_qz.py,sha256=Yh7DffwloPn3c9Q3NPzVxfmMGd8f9vPL4UogYE_zxqk,16456 +scipy/linalg/_decomp_schur.py,sha256=h5eEIhz_KDorht-T_U8tBmtu6sP4S9mYi8IlQCjFCRk,12172 +scipy/linalg/_decomp_svd.py,sha256=gd6OX3KlZfXuMUOxtEUMjpIKOOByAdOXEP0Jp8OHAo8,17139 +scipy/linalg/_decomp_update.cpython-312-darwin.so,sha256=3wr_NGVFXDMZ1SrewWjqo_Clnem8UMFsQ6mWuCLKFSQ,233208 +scipy/linalg/_expm_frechet.py,sha256=_RvX6m1ntUhLlbeTUrbvv48a80UW4kCM4gFBBedxx58,12442 +scipy/linalg/_fblas.cpython-312-darwin.so,sha256=aLmSMPgw1Aca_HPHaXEIrRhAXgqDhP_HbQyu29TEKjs,553648 +scipy/linalg/_flapack.cpython-312-darwin.so,sha256=VEbdzfgXC2VsNn8iDAwHkRwqnMsva22Z_J8d1Byo3R8,1871104 +scipy/linalg/_lapack_subroutines.h,sha256=oTfgwlGeOWm1A9EL1ybTxS5cURQbHXnI3wQMuUr3fH0,239326 +scipy/linalg/_linalg_pythran.cpython-312-darwin.so,sha256=TkziI6zWtqSxa_9UaMk-j3RuomvKFFK4vZFjgLwn-Sk,144152 +scipy/linalg/_matfuncs.py,sha256=kA-I6LQJAPa398CBQrKRl5IQGQevkaYupuQAt-0B5Cs,32302 +scipy/linalg/_matfuncs_expm.cpython-312-darwin.so,sha256=9CnohzauNJTosDQkBbFEagrd0qFUX1KLhISwmi_MaGE,105304 +scipy/linalg/_matfuncs_expm.pyi,sha256=wZAZfVtEbB78ljXgQoiL0I4yaPhmHOqIpGBYGQPvS6k,178 +scipy/linalg/_matfuncs_inv_ssq.py,sha256=8dL7xD6DU8D4h2YyHcYjRhZQvv1pSOEzMuKlGP6zonw,28095 +scipy/linalg/_matfuncs_schur_sqrtm.cpython-312-darwin.so,sha256=-X6jlLAV-bRlJ811pi9G0ekvq-Ec16mgV6IQ32dCQaQ,70216 +scipy/linalg/_matfuncs_sqrtm.py,sha256=p7iyvXyiSXXRi2AKRK0EstG4FQi34uS4KCc0VKoYnPE,3423 +scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-darwin.so,sha256=a8s8ABfM5rdGotlcKPW9vM-U5Ufqr-QU_RWJYBE8xhI,98536 +scipy/linalg/_misc.py,sha256=udhvxGfEHxhS3ecQBuwQ65W9ezVQIaVBw8JOmfqH_oE,6301 +scipy/linalg/_procrustes.py,sha256=gipMvbQdlKU8HBAExamtJqFRyUtufO63hYPdi9Jwryc,3859 +scipy/linalg/_sketches.py,sha256=Ypwy2sttOoEIQRxAinpd8BGnGg5O8v2E-npMBLuK36I,7140 +scipy/linalg/_solve_toeplitz.cpython-312-darwin.so,sha256=0Ljsc4fVA_KPuR6dv4cDErKfmb2SgXXjzih8ahzOeik,115256 +scipy/linalg/_solvers.py,sha256=hhDUzv2taY3a52L8HkVbMsZ2ab5akqhiyhf7uUHi_cA,30154 +scipy/linalg/_special_matrices.py,sha256=9LrN_uk_Pmzadfx5QeohMeZGNupd9P3iyuGpA0iH5Gw,41201 +scipy/linalg/_testutils.py,sha256=IWA5vvdZ8yaHeXo2IxpQLqG9q54YIomHscYs85q9pd0,1807 +scipy/linalg/basic.py,sha256=AuNvDlH8mnAJScycj4mV-Iq1M0bXxidpY4Vud_lRJlM,753 +scipy/linalg/blas.py,sha256=MHaf2FuLbJggeFSwFpJtM_uaI0M8AFe9NQvCPww_8F8,11833 +scipy/linalg/cython_blas.cpython-312-darwin.so,sha256=EPKZuXO8cAfyItS-fCn1BhjQkuo9j4Db4Ove7PKtZjE,131520 +scipy/linalg/cython_blas.pxd,sha256=DCPBxNWP-BvdT_REj6_a4TjUrNaf6sCq_XoxU3pEbfc,15592 +scipy/linalg/cython_blas.pyx,sha256=OgjBmmw5YP51aWtU-1pFgWWH29XWcnFWwcZP3_1sELk,65288 +scipy/linalg/cython_lapack.cpython-312-darwin.so,sha256=a7Xwq1TE3V27OoorkuZ5OetpXPLCpeC1_2rNw7UssM0,373056 +scipy/linalg/cython_lapack.pxd,sha256=Ld5hPwcYxpOPahFNsfNomsp0_DY8BfG-W8TmZxh-iYM,204556 +scipy/linalg/cython_lapack.pyx,sha256=fDKWgTGV8swZzyxFvtHkeaQaVWzrze0t5lHYGu0GKgk,707005 +scipy/linalg/decomp.py,sha256=w9HTI1OxXpX_rL72qcmykc5dUWal7lTlAU8k-9Eq7Dg,708 +scipy/linalg/decomp_cholesky.py,sha256=1g45oc115ZZR3CfMW1bCPseF5ATz4Xf6Ih26NRqyjfs,649 +scipy/linalg/decomp_lu.py,sha256=FPo9NHe9wg1FhCaoVV1_4mdfNj0S4plT4dHr4vMl1U8,593 +scipy/linalg/decomp_qr.py,sha256=EJNpu6lSa36Eo-e4rbYu5kDlRTMse2mmGul_PLRFXHs,567 +scipy/linalg/decomp_schur.py,sha256=vkVK3y-055523Q__ptxVNatDebPBE1HD-DFBe7kEh3w,602 +scipy/linalg/decomp_svd.py,sha256=HrJqbmgde7d7EWxCsa9XkS9QuWgPYMFOHiF4NcAL_Qg,631 +scipy/linalg/interpolative.py,sha256=iukUVTQJL-Oep9j4B-5hhpdR9u_xjli9R4QFJwU3lRg,31169 +scipy/linalg/lapack.py,sha256=MFiuCD8ZVcYqUC1vz48Ep5LGmxtjSwYp9KFN-MYmJXQ,17505 +scipy/linalg/matfuncs.py,sha256=vYw39D2LukCRCFJpx0qx8tgHlRZEDZI2wZfZwhh-Ubo,744 +scipy/linalg/misc.py,sha256=uxpR80jJ5w5mslplWlL6tIathas8mEXvRIwDXYMcTOk,592 +scipy/linalg/special_matrices.py,sha256=FGEXV_qOxy6ZrAsKUwHiDlaSRsvYFaUgkMN1YSEetCo,749 +scipy/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/linalg/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_basic.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_batch.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_blas.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_cython_blas.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_cython_lapack.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_cythonized_array_utils.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_decomp.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_decomp_cholesky.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_decomp_cossin.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_decomp_ldl.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_decomp_lu.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_decomp_polar.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_decomp_update.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_extending.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_fblas.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_interpolative.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_lapack.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_matfuncs.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_matmul_toeplitz.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_procrustes.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_sketches.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_solve_toeplitz.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_solvers.cpython-312.pyc,, +scipy/linalg/tests/__pycache__/test_special_matrices.cpython-312.pyc,, +scipy/linalg/tests/_cython_examples/extending.pyx,sha256=scunPSonBTtsidhd2hLtg-DPWoFkvzWcXDMYEO9iygo,887 +scipy/linalg/tests/_cython_examples/meson.build,sha256=DzG1UVjBrYOrtvgnaOVL0amQulrI8HTyYgryw2AhiKI,846 +scipy/linalg/tests/data/carex_15_data.npz,sha256=E_PhSRqHa79Z1-oQrSnB-bWZaiq5khbzHVv81lkBLB4,34462 +scipy/linalg/tests/data/carex_18_data.npz,sha256=Wfg5Rn8nUrffb7bUCUOW7dMqWSm3ZPf_oeZmZDHmysY,161487 +scipy/linalg/tests/data/carex_19_data.npz,sha256=OOj8ewQd8LI9flyhXq0aBl5kZ2Ee-ahIzH25P4Ct_Yc,34050 +scipy/linalg/tests/data/carex_20_data.npz,sha256=FOIi00pxGMcoShZ1xv7O7ne4TflRpca6Kl7p_zBU-h0,31231 +scipy/linalg/tests/data/carex_6_data.npz,sha256=GyoHNrVB6_XEubTADW2rKB5zyfuZE8biWBp4Gze2Avk,15878 +scipy/linalg/tests/data/gendare_20170120_data.npz,sha256=o9-rRR2dXCAkPg7YXNi2yWV2afuaD4O1vhZVhXg9VbU,2164 +scipy/linalg/tests/test_basic.py,sha256=T_iDjnMI0vaL6Ce20ElLRplNlxpiBazvgd-o91LFePM,105431 +scipy/linalg/tests/test_batch.py,sha256=NwVV_SWeI1xX4SnHIFbWA1ty5ke28Ux9zy3QYHPtHHk,28874 +scipy/linalg/tests/test_blas.py,sha256=DvEaxyr4IXdiwKgQEAA5QLhhJ39bc3t7okSa1meWhpo,37595 +scipy/linalg/tests/test_cython_blas.py,sha256=0Y2w1Btw6iatfodZE7z0lisJJLVCr70DAW-62he_sz4,4087 +scipy/linalg/tests/test_cython_lapack.py,sha256=McSFDUU4kgCavU1u3-uqBGlzUZiLGxM5qPfBFgPTqdE,796 +scipy/linalg/tests/test_cythonized_array_utils.py,sha256=MDa9kj1M6pCikyxsVnLmZO23zejqvH1liopf7guSRAs,4203 +scipy/linalg/tests/test_decomp.py,sha256=5dC4daV6siYJ-F8jAUEGO8KN0AaAnlZQpK_rO2rl-rw,120430 +scipy/linalg/tests/test_decomp_cholesky.py,sha256=5WxQbSxK6134NztaoNu-d4OmudQRfhgeyf2LmyJdx1w,9743 +scipy/linalg/tests/test_decomp_cossin.py,sha256=b10EQSJzYwGwgEHj_s71tDPr59e3lZmid7M8G9qgv3A,12560 +scipy/linalg/tests/test_decomp_ldl.py,sha256=n9ETZLP6IRVaVt0c5u8aZF-sPpAMTD2EQ4W-za9SNdM,5034 +scipy/linalg/tests/test_decomp_lu.py,sha256=spCYelU_CXmHAaKrJM4V5djLKq5MCeX4wN1SBCFkSOo,12629 +scipy/linalg/tests/test_decomp_polar.py,sha256=fGKl3Skqz6IpHBeFcq6bdqvS8M53rXx2Wh6Kx4f5T3Y,3287 +scipy/linalg/tests/test_decomp_update.py,sha256=Q1L6MAOXIBMuI0wCO-w1bHsqTod8FSydIUmC5RqlTz0,68424 +scipy/linalg/tests/test_extending.py,sha256=sKc6YdWOcCMiiJZ8g2-DkvSaLWqXLOvFhqco2W85M30,1823 +scipy/linalg/tests/test_fblas.py,sha256=oMPWfEZfh-MFZtKLGFNGm0wmdUZkkNvtH7x_GwbSY7I,18664 +scipy/linalg/tests/test_interpolative.py,sha256=8_OQau0olSNQWi6RUasHgHasQvvvaMjJ7JUl0jh1Lqw,8616 +scipy/linalg/tests/test_lapack.py,sha256=AqhrOz_Ki6z_idcmduBluDzK4dY1sCCqmvNyzM8zg9A,138869 +scipy/linalg/tests/test_matfuncs.py,sha256=l1gemWpPGkKIn7jbREUYttT5F4Z4IRaIoUUjQrsEeds,43916 +scipy/linalg/tests/test_matmul_toeplitz.py,sha256=73Qe51lCXEWZGpxk8GYv0owDSlN0IpnLJPlI0nsCdhY,4088 +scipy/linalg/tests/test_procrustes.py,sha256=EW3XeVvPK0uiYEmjuHh8LmwZKhgSaEO7DWhAsH7gnwM,9058 +scipy/linalg/tests/test_sketches.py,sha256=jNVAdrDA_X6Dk9oKg0W92s4euHyfhQPgIHNsAYzEMWs,4010 +scipy/linalg/tests/test_solve_toeplitz.py,sha256=UpF5Cem6wYj8Iiu2ooFTkDI9Ozuofa5dx2J6KOsciCw,4579 +scipy/linalg/tests/test_solvers.py,sha256=8kSm_WOhyniaL3NWmdKS-tTd9K0IBdD1iynAjrR8h4k,34598 +scipy/linalg/tests/test_special_matrices.py,sha256=HVMoXFrJAZQn5sg7pVOaeRW5Nc3-tyNY7ZLEKzWTK3U,24843 +scipy/misc/__init__.py,sha256=dVfULY959nFwpl5NCxyCpiHyNcSNaR7HYOg7QU21a5s,135 +scipy/misc/__pycache__/__init__.cpython-312.pyc,, +scipy/misc/__pycache__/common.cpython-312.pyc,, +scipy/misc/__pycache__/doccer.cpython-312.pyc,, +scipy/misc/common.py,sha256=nAGQOVR9ZEAb703uhOVQZqf-z0iCM4EDhbHK4_h_Tdc,142 +scipy/misc/doccer.py,sha256=wHbpGV8todadz6MIzJHalDfRjiKI164qs6iMcHgsVu0,142 +scipy/ndimage/__init__.py,sha256=KUbDfnLPN7B-U650Nh-XVf7fQ0bW8vkEDPssG8oZsi4,5175 +scipy/ndimage/__pycache__/__init__.cpython-312.pyc,, +scipy/ndimage/__pycache__/_delegators.cpython-312.pyc,, +scipy/ndimage/__pycache__/_filters.cpython-312.pyc,, +scipy/ndimage/__pycache__/_fourier.cpython-312.pyc,, +scipy/ndimage/__pycache__/_interpolation.cpython-312.pyc,, +scipy/ndimage/__pycache__/_measurements.cpython-312.pyc,, +scipy/ndimage/__pycache__/_morphology.cpython-312.pyc,, +scipy/ndimage/__pycache__/_ndimage_api.cpython-312.pyc,, +scipy/ndimage/__pycache__/_ni_docstrings.cpython-312.pyc,, +scipy/ndimage/__pycache__/_ni_support.cpython-312.pyc,, +scipy/ndimage/__pycache__/_support_alternative_backends.cpython-312.pyc,, +scipy/ndimage/__pycache__/filters.cpython-312.pyc,, +scipy/ndimage/__pycache__/fourier.cpython-312.pyc,, +scipy/ndimage/__pycache__/interpolation.cpython-312.pyc,, +scipy/ndimage/__pycache__/measurements.cpython-312.pyc,, +scipy/ndimage/__pycache__/morphology.cpython-312.pyc,, +scipy/ndimage/_ctest.cpython-312-darwin.so,sha256=KNeRKOSlIp7noEfVkRZ5pU90H9xhjbp8nKTNBk0TvpY,51120 +scipy/ndimage/_cytest.cpython-312-darwin.so,sha256=7Sc8Ysnw_3MKTlWri8Ns88VYwTB75XHwGNgav5i3f0g,96352 +scipy/ndimage/_delegators.py,sha256=EI2Xsmw6GDL8MnLeQYZ6uK9dVkMv01WOd1fZTLS_BrU,9410 +scipy/ndimage/_filters.py,sha256=OuVuvfxY7ibLGzR3qiEcE7V_6Sqz69AE3amxOPExu4s,92349 +scipy/ndimage/_fourier.py,sha256=SoAYRx7ax7Tv51MyYzDlZ3fN682x4T6N8yReX2La4-I,11266 +scipy/ndimage/_interpolation.py,sha256=KKQMixU4VgfEprLNPUeLWNvzfBBJ_nhr9bnJYT3o7Nc,37740 +scipy/ndimage/_measurements.py,sha256=vg9pVW8Onbc-oKmNN2ARf50ffiAz-DTMofcfs46TcoI,56249 +scipy/ndimage/_morphology.py,sha256=9QydGKTTLZ5IlNA4E3lOGE789hRcR0WNEAJMU7sXLkQ,100970 +scipy/ndimage/_nd_image.cpython-312-darwin.so,sha256=NfyyRzsongf-xnhqFvdDIngpxce30iPCpGqSTCoMs3E,156160 +scipy/ndimage/_ndimage_api.py,sha256=S8DBRWydSRfAz-ZlHSMeCSbjYGgCLioa9_Q2VXGeC_g,586 +scipy/ndimage/_ni_docstrings.py,sha256=EhrW-Q_R2fO9pDXYhc8xKS1QY5nXFxQtEXd2aLWG5GM,8727 +scipy/ndimage/_ni_label.cpython-312-darwin.so,sha256=a-u1qzNnDg8ABeHwWON9FWhJpGEDv03WpUU0fkTbuMQ,188400 +scipy/ndimage/_ni_support.py,sha256=1JpV6XSyvMP6-rqKHHEBrc83RaVkDzynBHlO672sczY,5216 +scipy/ndimage/_rank_filter_1d.cpython-312-darwin.so,sha256=dMuM-y6TpsxeC9EmKX7vz0FAtk7DR9RYF3mYyQ-rwDM,52536 +scipy/ndimage/_support_alternative_backends.py,sha256=-ox6hzUSsNkAAzAitL4ze-XBKmzg_pcXO2zFF_eomoQ,4145 +scipy/ndimage/filters.py,sha256=cAv2zezrTJEm9JzKPV_pmXzZcgczCK_VaYJ4mdNW3FM,976 +scipy/ndimage/fourier.py,sha256=gnifi4S_Epyu4DpNsebz4A5BKzBWoGf11FkXWeXsoqY,599 +scipy/ndimage/interpolation.py,sha256=GHYvxCyQsLfKtNUc8AUN_vqmBhmAPwNnxm2-VpFMayk,664 +scipy/ndimage/measurements.py,sha256=xdSs52Y5RjURLP710iGURXWQFeS3ok4WjoYufKh9OeA,788 +scipy/ndimage/morphology.py,sha256=yFWSo7o_7PuYq61WGQOCIgMppneNLxqhJocyN0bMsVA,965 +scipy/ndimage/tests/__init__.py,sha256=GbIXCsLtZxgmuisjxfFsd3pj6-RQhmauc6AVy6sybDc,314 +scipy/ndimage/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_c_api.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_datatypes.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_filters.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_fourier.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_interpolation.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_measurements.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_morphology.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_ni_support.cpython-312.pyc,, +scipy/ndimage/tests/__pycache__/test_splines.cpython-312.pyc,, +scipy/ndimage/tests/data/label_inputs.txt,sha256=JPbEnncwUyhlAAv6grN8ysQW9w9M7ZSIn_NPopqU7z4,294 +scipy/ndimage/tests/data/label_results.txt,sha256=Cf2_l7FCWNjIkyi-XU1MaGzmLnf2J7NK2SZ_10O-8d0,4309 +scipy/ndimage/tests/data/label_strels.txt,sha256=AU2FUAg0WghfvnPDW6lhMB1kpNdfv3coCR8blcRNBJ8,252 +scipy/ndimage/tests/dots.png,sha256=sgtW-tx0ccBpTT6BSNniioPXlnusFr-IUglK_qOVBBQ,2114 +scipy/ndimage/tests/test_c_api.py,sha256=7Gv-hR91MWpiGQ32yjXIBjFytuaYLqz3wYiCXcC8ZSk,3738 +scipy/ndimage/tests/test_datatypes.py,sha256=TYMiGyBcdOq3KVLzvjZPjerD1EXonyHFQYBLTWDwN7o,2819 +scipy/ndimage/tests/test_filters.py,sha256=-Fx-4BLcLhG3ciTcA-nRedfhatdzhjn5VOGoRgEosbE,134869 +scipy/ndimage/tests/test_fourier.py,sha256=4e0ngc3Ul2JiLzyRzjW-BJuSX5AF0J87gsSXy5tSulQ,8080 +scipy/ndimage/tests/test_interpolation.py,sha256=9eToKX4j6ELzPAcSmbBuQRL0eE5yYBxd-FXy6GdDkoc,61290 +scipy/ndimage/tests/test_measurements.py,sha256=xw5iokRs5ifM7H4xbUqwFS-IGK02iklbRz0VShdn01U,62616 +scipy/ndimage/tests/test_morphology.py,sha256=QqGnKJiZ29gkySoY9-p6fwHVXsbYPp9JMxgfkK-ioQo,137867 +scipy/ndimage/tests/test_ni_support.py,sha256=5ZBJivg8-l-OFx02ZCLWEBK56Bdmu0AUqUmWjiPqAMQ,2484 +scipy/ndimage/tests/test_splines.py,sha256=z688_2iOVTb3ICre4-lyJNHOM0Xj00R-Bv8LH7Er5_A,2360 +scipy/odr/__init__.py,sha256=cb97lL9npGTTE1ZufLQTVm74uRUEwMiLu5G_GrXPjRA,6214 +scipy/odr/__odrpack.cpython-312-darwin.so,sha256=cPFq9irs3wsb7E3GPfoOeBkOfO0rglZsrBm9FEaxvlM,240656 +scipy/odr/__pycache__/__init__.cpython-312.pyc,, +scipy/odr/__pycache__/_add_newdocs.cpython-312.pyc,, +scipy/odr/__pycache__/_models.cpython-312.pyc,, +scipy/odr/__pycache__/_odrpack.cpython-312.pyc,, +scipy/odr/__pycache__/models.cpython-312.pyc,, +scipy/odr/__pycache__/odrpack.cpython-312.pyc,, +scipy/odr/_add_newdocs.py,sha256=kviOIY4HPMd6ninCtC82smc4D9fytrYvRwy8AOjl9c0,1328 +scipy/odr/_models.py,sha256=NXoKEJGpSer4YISjl9uY3YV4D7hcXTOY9oDgex3GA4I,8782 +scipy/odr/_odrpack.py,sha256=dpYQHipVkHjEXGPa6G7sdCsxLInbpMjz8JFePq2X1pk,44310 +scipy/odr/models.py,sha256=awdUPgiJ8slzPMzDITmNMNNyIoKsJ8elNryFE3jyf6o,785 +scipy/odr/odrpack.py,sha256=LvvD6GKspFMi-uwlRoBek5DESYWXGVNpJ3o0qs58HGc,828 +scipy/odr/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/odr/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/odr/tests/__pycache__/test_odr.cpython-312.pyc,, +scipy/odr/tests/test_odr.py,sha256=X51l1F2Fb3KrqvCM3qmNRBHKw3mwALw-Z02ug43u3wU,22478 +scipy/optimize/__init__.pxd,sha256=kFYBK9tveJXql1KXuOkKGvj4Fu67GmuyRP5kMVkMbyk,39 +scipy/optimize/__init__.py,sha256=7ZzePqFF1X1377f_s3dpVdeg51I3YwManuh8Pl4M1mE,13279 +scipy/optimize/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/__pycache__/_basinhopping.cpython-312.pyc,, +scipy/optimize/__pycache__/_bracket.cpython-312.pyc,, +scipy/optimize/__pycache__/_chandrupatla.cpython-312.pyc,, +scipy/optimize/__pycache__/_cobyla_py.cpython-312.pyc,, +scipy/optimize/__pycache__/_cobyqa_py.cpython-312.pyc,, +scipy/optimize/__pycache__/_constraints.cpython-312.pyc,, +scipy/optimize/__pycache__/_dcsrch.cpython-312.pyc,, +scipy/optimize/__pycache__/_differentiable_functions.cpython-312.pyc,, +scipy/optimize/__pycache__/_differentialevolution.cpython-312.pyc,, +scipy/optimize/__pycache__/_direct_py.cpython-312.pyc,, +scipy/optimize/__pycache__/_dual_annealing.cpython-312.pyc,, +scipy/optimize/__pycache__/_elementwise.cpython-312.pyc,, +scipy/optimize/__pycache__/_hessian_update_strategy.cpython-312.pyc,, +scipy/optimize/__pycache__/_isotonic.cpython-312.pyc,, +scipy/optimize/__pycache__/_lbfgsb_py.cpython-312.pyc,, +scipy/optimize/__pycache__/_linesearch.cpython-312.pyc,, +scipy/optimize/__pycache__/_linprog.cpython-312.pyc,, +scipy/optimize/__pycache__/_linprog_doc.cpython-312.pyc,, +scipy/optimize/__pycache__/_linprog_highs.cpython-312.pyc,, +scipy/optimize/__pycache__/_linprog_ip.cpython-312.pyc,, +scipy/optimize/__pycache__/_linprog_rs.cpython-312.pyc,, +scipy/optimize/__pycache__/_linprog_simplex.cpython-312.pyc,, +scipy/optimize/__pycache__/_linprog_util.cpython-312.pyc,, +scipy/optimize/__pycache__/_milp.cpython-312.pyc,, +scipy/optimize/__pycache__/_minimize.cpython-312.pyc,, +scipy/optimize/__pycache__/_minpack_py.cpython-312.pyc,, +scipy/optimize/__pycache__/_nnls.cpython-312.pyc,, +scipy/optimize/__pycache__/_nonlin.cpython-312.pyc,, +scipy/optimize/__pycache__/_numdiff.cpython-312.pyc,, +scipy/optimize/__pycache__/_optimize.cpython-312.pyc,, +scipy/optimize/__pycache__/_qap.cpython-312.pyc,, +scipy/optimize/__pycache__/_remove_redundancy.cpython-312.pyc,, +scipy/optimize/__pycache__/_root.cpython-312.pyc,, +scipy/optimize/__pycache__/_root_scalar.cpython-312.pyc,, +scipy/optimize/__pycache__/_shgo.cpython-312.pyc,, +scipy/optimize/__pycache__/_slsqp_py.cpython-312.pyc,, +scipy/optimize/__pycache__/_spectral.cpython-312.pyc,, +scipy/optimize/__pycache__/_tnc.cpython-312.pyc,, +scipy/optimize/__pycache__/_trustregion.cpython-312.pyc,, +scipy/optimize/__pycache__/_trustregion_dogleg.cpython-312.pyc,, +scipy/optimize/__pycache__/_trustregion_exact.cpython-312.pyc,, +scipy/optimize/__pycache__/_trustregion_krylov.cpython-312.pyc,, +scipy/optimize/__pycache__/_trustregion_ncg.cpython-312.pyc,, +scipy/optimize/__pycache__/_tstutils.cpython-312.pyc,, +scipy/optimize/__pycache__/_zeros_py.cpython-312.pyc,, +scipy/optimize/__pycache__/cobyla.cpython-312.pyc,, +scipy/optimize/__pycache__/elementwise.cpython-312.pyc,, +scipy/optimize/__pycache__/lbfgsb.cpython-312.pyc,, +scipy/optimize/__pycache__/linesearch.cpython-312.pyc,, +scipy/optimize/__pycache__/minpack.cpython-312.pyc,, +scipy/optimize/__pycache__/minpack2.cpython-312.pyc,, +scipy/optimize/__pycache__/moduleTNC.cpython-312.pyc,, +scipy/optimize/__pycache__/nonlin.cpython-312.pyc,, +scipy/optimize/__pycache__/optimize.cpython-312.pyc,, +scipy/optimize/__pycache__/slsqp.cpython-312.pyc,, +scipy/optimize/__pycache__/tnc.cpython-312.pyc,, +scipy/optimize/__pycache__/zeros.cpython-312.pyc,, +scipy/optimize/_basinhopping.py,sha256=WsbBApKXaUhZ5VoNoFmUGkWtfibm6BzT2-NHk34QsbE,29989 +scipy/optimize/_bglu_dense.cpython-312-darwin.so,sha256=WFzYyNhp9WHob_kvXHrnMu7onVvDc-1ftapZ7jRCk_Q,171904 +scipy/optimize/_bracket.py,sha256=RWZNYU3t8qsNVhW4TcP7etHTyoocZiPGCxzC1uKkPbA,30939 +scipy/optimize/_chandrupatla.py,sha256=yfdxwFZNBb1SToOqkbheYr0rabz0T9LGsBzKV1kI4Rk,24548 +scipy/optimize/_cobyla_py.py,sha256=Q5eIlDlQQQdAEctTONx4UoqBP2iZEUorzWBpyZsqNFM,11009 +scipy/optimize/_cobyqa_py.py,sha256=_zejgs3XKkieGiMlRVn1x12cyWoulaPP2SpvxA4zK3k,2971 +scipy/optimize/_constraints.py,sha256=jl03ITqXTn54y0z4lmBz-hTlIxV-eX1jgsl4xZ4zj9I,23134 +scipy/optimize/_dcsrch.py,sha256=tw5Fpc5_bHAzAuPszso66q0iP0efrJRP8KJ8W2C1_2Y,25234 +scipy/optimize/_differentiable_functions.py,sha256=or1-xbTBeB4CBS-7IyIMv91QlPrijLIw_GU8AxmFRuA,29960 +scipy/optimize/_differentialevolution.py,sha256=usq2VzCmz0u_DyC6yiu70IUvl_dlWruxmdZsKiIg-sU,90022 +scipy/optimize/_direct.cpython-312-darwin.so,sha256=Aec6aesS7hVMKje9FRYJUn2AOZ2L9-cVYBw3NNpkdEU,69232 +scipy/optimize/_direct_py.py,sha256=thi8xqSHzBo5lIAj8My05Ii4Ya0ViUcny3G59-bNuAc,11848 +scipy/optimize/_dual_annealing.py,sha256=YU79aERoQuVZWEOfDyzdmj7O8V8tg3VMLX341wByNCI,31121 +scipy/optimize/_elementwise.py,sha256=5JcY6mZ5ZgNig2vDaaXswc7YtDpp9epHEQ5xK9HcHkU,34148 +scipy/optimize/_group_columns.cpython-312-darwin.so,sha256=ubiwAcSZUZRhLvN_D22HpTH0c-EgIVWES9SmP3lEuAk,94616 +scipy/optimize/_hessian_update_strategy.py,sha256=xmtREKGlLgVvlBynjb5eCnPbsH-xbPcprS-ZoziG80M,18423 +scipy/optimize/_highspy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/optimize/_highspy/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/_highspy/__pycache__/_highs_wrapper.cpython-312.pyc,, +scipy/optimize/_highspy/_core.cpython-312-darwin.so,sha256=1AVVE8G_Z1cg1wLq767OaZZm-twKdxe5ktUZAnMeb0w,5294616 +scipy/optimize/_highspy/_highs_options.cpython-312-darwin.so,sha256=Bw6H-Psvh4R1YpvqxryTK7x5WfATSGIKA6ZNB6Dt5A0,405928 +scipy/optimize/_highspy/_highs_wrapper.py,sha256=wVqUOgmFv3FthLk3GdCy9XLmmDc2VasCWGFLSyq2cwM,11294 +scipy/optimize/_isotonic.py,sha256=WY-9jtT5VVafVALYIp6lJPQnBfYVNDP9oJpg-kErYYI,6077 +scipy/optimize/_lbfgsb.cpython-312-darwin.so,sha256=BwKZVk7sfTMI7R4ZGYZUcomzXbfa8JLSXvW5Ag0kBmw,68592 +scipy/optimize/_lbfgsb_py.py,sha256=skrkTC1jzYijSzqVsTgKIZ0nT4e7mbhPq6K0T2ttbdk,23093 +scipy/optimize/_linesearch.py,sha256=4zfjJXv0K_IHYEmvkZSSDa_TlILcN6WoOnW6m-u1Yg8,27216 +scipy/optimize/_linprog.py,sha256=TGl9k9Ioh-hgHYgtndN5BNcU4vqfpZm8whRK2f4ehQQ,30262 +scipy/optimize/_linprog_doc.py,sha256=AqRggJEqncrthBW0iCG2zhg-3Ks4-ZR_B3wTQSOfslE,61931 +scipy/optimize/_linprog_highs.py,sha256=491Jt7-YCQGKM0YQnWgdMpYYVKZ8tBAPDFCdX9-1vGM,17142 +scipy/optimize/_linprog_ip.py,sha256=QBlUjw6jl3mEZnouExtuac2dlIn9Gtki5yJVzkSffSU,46651 +scipy/optimize/_linprog_rs.py,sha256=wRVGZxCSpo4ttw4CPpmXozSvM9WRXD179fGiGh8gOQ4,23146 +scipy/optimize/_linprog_simplex.py,sha256=9_nxcVl-ofHN9p_dDyC1C6jHlPttSfO9kp8WF1ST4JM,24748 +scipy/optimize/_linprog_util.py,sha256=mzLvoLOkq4IZJcXINMPk1fzRXm7Z3QBPRd06NbiEgZw,62763 +scipy/optimize/_lsap.cpython-312-darwin.so,sha256=hRiQ3n3BtdrVaPiWANLu8DdzDAPKlJBssV91JOapULk,70744 +scipy/optimize/_lsq/__init__.py,sha256=Yk4FSVEqe1h-qPqVX7XSkQNBYDtZO2veTmMAebCxhIQ,172 +scipy/optimize/_lsq/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/_lsq/__pycache__/bvls.cpython-312.pyc,, +scipy/optimize/_lsq/__pycache__/common.cpython-312.pyc,, +scipy/optimize/_lsq/__pycache__/dogbox.cpython-312.pyc,, +scipy/optimize/_lsq/__pycache__/least_squares.cpython-312.pyc,, +scipy/optimize/_lsq/__pycache__/lsq_linear.cpython-312.pyc,, +scipy/optimize/_lsq/__pycache__/trf.cpython-312.pyc,, +scipy/optimize/_lsq/__pycache__/trf_linear.cpython-312.pyc,, +scipy/optimize/_lsq/bvls.py,sha256=7u5B8LfUbv3ZRZ8DAZKuDTSNRfDEBmTsn25VZtMMsKk,5195 +scipy/optimize/_lsq/common.py,sha256=h_VsfPQM3fy-MWYY2WbPDvfzZssBOsZl3xmaEWxfsMc,20480 +scipy/optimize/_lsq/dogbox.py,sha256=A-Q6_1XV3TbN7wUGS8vT2JFeZfSz-GuS8h9HKKRJUMU,12177 +scipy/optimize/_lsq/givens_elimination.cpython-312-darwin.so,sha256=NvMEAh9-KNaLYDsWZvQXrHOYF453rEpqFAEzh5YmkPQ,77944 +scipy/optimize/_lsq/least_squares.py,sha256=7bJeypmMILnMELOyL6-bCGH5vlJRIJSBtzn1bYV7G3w,42812 +scipy/optimize/_lsq/lsq_linear.py,sha256=HBVp9GhWm9r7meFhPp5WBX-H-LHTtFVGvKIAMSgI24I,15053 +scipy/optimize/_lsq/trf.py,sha256=DHwp1dP9aRVyDpVH8FHUfhTKWoIeeHJoaqjPHRxOSJM,20516 +scipy/optimize/_lsq/trf_linear.py,sha256=jIs7WviOu_8Kpb7sTln8W7YLgkcndv0eGIP15g_mC4g,7642 +scipy/optimize/_milp.py,sha256=qEC8gW3OnpypleLEzY2FMoxbvpZWVV50lR95jR65BII,15241 +scipy/optimize/_minimize.py,sha256=Wv0-y-q6ZgbCf1-fKYeCwNroDdDj4B2Y1CSZIu3mt-o,53050 +scipy/optimize/_minpack.cpython-312-darwin.so,sha256=PV7_XGoSx9FHIu9nNxwKNW40bYbcS5dSwXld6ujSmig,103520 +scipy/optimize/_minpack_py.py,sha256=zDy2mNhZxfcSdrvt8qPEmkiNJuzx07vi23gSyTdL3EY,45387 +scipy/optimize/_moduleTNC.cpython-312-darwin.so,sha256=41vgXzCalRyzZngvnpRdWeE7YcPYkHEIX5UMmkhtbLo,145984 +scipy/optimize/_nnls.py,sha256=WfKev4V9okgpecuBg_rWrKzE3Ge2j_zA8QwTZem4it0,2915 +scipy/optimize/_nonlin.py,sha256=x_DNnKjkTAwjwwnJ_XZlIXxCU_74bTVvUAwV0ovOrmY,52206 +scipy/optimize/_numdiff.py,sha256=q5LoLQ-T8sejXroKKAC3DPgBXZfM8JSr9VYgYhG-sAs,35825 +scipy/optimize/_optimize.py,sha256=BBoYB8yqaBFck7B77Ul9JcKUp9cwzlp8sfIfxaGF-mE,149749 +scipy/optimize/_pava_pybind.cpython-312-darwin.so,sha256=2I7iA1Jn6DJkbIbXqh4xqIY_Ir4Wrl2ieXNDXuaPrmE,226224 +scipy/optimize/_qap.py,sha256=6bIzIiLwD4V2MCJrqQBOJ2h7uycy0qx01mkl-CR1U3I,29390 +scipy/optimize/_remove_redundancy.py,sha256=00_Zc8_5uY6q2pBr8gu2_AYk7kX9YBjF8LqaxgqTKUY,18757 +scipy/optimize/_root.py,sha256=XZ8iqg3NhtOJZVC8ZRMfo5Jtj4poB8KVhDqkS0Hd1o4,28706 +scipy/optimize/_root_scalar.py,sha256=XSwjKAXVZRJrGwSc7hIpQTucDwJv84cWZpcYlLDLF3U,20391 +scipy/optimize/_shgo.py,sha256=zAg_cEamqQ_85I2oDKwlSRsZLs7rYtjEmO5CWNQBxxg,63593 +scipy/optimize/_shgo_lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/optimize/_shgo_lib/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/_shgo_lib/__pycache__/_complex.cpython-312.pyc,, +scipy/optimize/_shgo_lib/__pycache__/_vertex.cpython-312.pyc,, +scipy/optimize/_shgo_lib/_complex.py,sha256=my2yyCrPKpLbmz0onA-Y-xLTw20KuwEiKbOrQ-fpe6E,50263 +scipy/optimize/_shgo_lib/_vertex.py,sha256=I2TAqEEdTK66Km6UIkrDm2-tKpeJUuFX7DAfTk3XvUg,13996 +scipy/optimize/_slsqp_py.py,sha256=yDYujTZEDz3pe1hWKq24ZmEnHqf2YWBQX1GmAa_3Fgk,24296 +scipy/optimize/_slsqplib.cpython-312-darwin.so,sha256=h6BtOyuqdYyAXt967Zol59vGfAznilRBt78tRgdISgE,70624 +scipy/optimize/_spectral.py,sha256=uV4DgfWAKcEpB7CC1CUgtWJjIGfIbpk8SH1ZwUyGFXo,8128 +scipy/optimize/_tnc.py,sha256=htQhspgXo-P0jt7TmynmAPzqq8qZaM4yVmI8O1cImGU,17339 +scipy/optimize/_trlib/__init__.py,sha256=cNGWE1VffijqhPtSaqwagtBJvjJK-XrJ6K80RURLd48,524 +scipy/optimize/_trlib/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/_trlib/_trlib.cpython-312-darwin.so,sha256=knnI-G0iLR7KiLpRPN1cbj0lSc-W99FTMYqAJCIKMcE,182816 +scipy/optimize/_trustregion.py,sha256=HrxSmXdTHnQQVyGo4GqPxXhhGU4xbwPu-pedgskaLjA,11866 +scipy/optimize/_trustregion_constr/__init__.py,sha256=c8J2wYGQZr9WpLIT4zE4MUgEj4YNbHEWYYYsFmxAeXI,180 +scipy/optimize/_trustregion_constr/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/__pycache__/canonical_constraint.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/__pycache__/equality_constrained_sqp.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/__pycache__/minimize_trustregion_constr.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/__pycache__/projections.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/__pycache__/qp_subproblem.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/__pycache__/report.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/__pycache__/tr_interior_point.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/canonical_constraint.py,sha256=gc5KucHwFCz_-w2IYWd_C1X1E0TFy_sey-_0KBY_djE,12542 +scipy/optimize/_trustregion_constr/equality_constrained_sqp.py,sha256=mNbnrNvKAkj7AzHTUpQQGgAfiUQ5ZSY0uzjk45B91Cs,9160 +scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py,sha256=j7Xanu91OsRjHGFkGZiRDi54Z-41m9sPmVbVibH2yfA,26594 +scipy/optimize/_trustregion_constr/projections.py,sha256=Q7zBucAd44hxj_KwusacAAnAuLSavr3T3qLUk4bwN_k,13517 +scipy/optimize/_trustregion_constr/qp_subproblem.py,sha256=AoLwMIDUMROleMGAldXH3gItoyzJ6qRTpNhDrijyvNA,22587 +scipy/optimize/_trustregion_constr/report.py,sha256=_L-HrO5C1lzvKvaijgkOYD210dvM4PkrhBSEQrMhVlw,1782 +scipy/optimize/_trustregion_constr/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/optimize/_trustregion_constr/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/tests/__pycache__/test_canonical_constraint.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/tests/__pycache__/test_nested_minimize.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/tests/__pycache__/test_projections.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/tests/__pycache__/test_qp_subproblem.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/tests/__pycache__/test_report.cpython-312.pyc,, +scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py,sha256=zVPxZDa0WkG_tw9Fm_eo_JzsQ8rQrUJyQicq4J12Nd4,9869 +scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py,sha256=tgBVQe97RwVu_GJACARyg0s9zHiFGVHSPNrXLCjlX7w,1216 +scipy/optimize/_trustregion_constr/tests/test_projections.py,sha256=Agc-mtiLBximfHMI0CTDklb0shxHL8DUXEBuV08CjSs,8869 +scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py,sha256=5nNaAOTP4Pox6ZIqQ9b9gpOBHALaPY3m4IS--7PX4a0,27642 +scipy/optimize/_trustregion_constr/tests/test_report.py,sha256=hyRnUGBhDhKHR5SKD66ZME4zzCIViIh3_-700p0afXY,1104 +scipy/optimize/_trustregion_constr/tr_interior_point.py,sha256=Kt3jEh7tPo9cp3PaQd675ofg7JVk-84sYzaZS7UA6Uo,14395 +scipy/optimize/_trustregion_dogleg.py,sha256=HS783IZYHE-EEuF82c4rkFp9u3MNKUdCeynZ6ap8y8s,4389 +scipy/optimize/_trustregion_exact.py,sha256=ne9CVO0g-LQosj2P6QzvpiNsZTynNRJekyfvDq-P9U0,16672 +scipy/optimize/_trustregion_krylov.py,sha256=KGdudJsoXXROXAc82aZ8ACojD3rimvyx5PYitbo4UzQ,3030 +scipy/optimize/_trustregion_ncg.py,sha256=y7b7QjFBfnB1wDtbwnvKD9DYpz7y7NqVrJ9RhNPcipw,4580 +scipy/optimize/_tstutils.py,sha256=BBaThpZNuwIQBqtVMOEB4bUHk3QdG2NpuLJBum8P6ak,34047 +scipy/optimize/_zeros.cpython-312-darwin.so,sha256=3iS13fupP80tZA7NZOdxTHVHV9PVnEJPZF1X7mnMN7Q,51280 +scipy/optimize/_zeros_py.py,sha256=FPiPEICYXq4K-Eu1lS2luZSrIEPn_lsMhgODlHU5EWE,56659 +scipy/optimize/cobyla.py,sha256=k2io8SM0vahYT5Zu4nS4yfa05_gyH0y-jVVxdWkC4dU,557 +scipy/optimize/cython_optimize.pxd,sha256=ecYJEpT0CXN-2vtaZfGCChD-oiIaJyRDIsTHE8eUG5M,442 +scipy/optimize/cython_optimize/__init__.py,sha256=eehEQNmLGy3e_XjNh6t5vQIC9l_OREeE4tYRRaFZdNs,4887 +scipy/optimize/cython_optimize/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/cython_optimize/_zeros.cpython-312-darwin.so,sha256=_DIphYWsOXusi6sHrIVF9O6j67BX2Vb17RRt7fllITo,114672 +scipy/optimize/cython_optimize/_zeros.pxd,sha256=anyu-MgWhq24f1bywI4TlohvJjOnpNpkCtSzpKBJSSo,1239 +scipy/optimize/cython_optimize/c_zeros.pxd,sha256=6Gc0l1q-1nlCO9uKrYeXFiHsbimRZzU3t6EoTa8MVvA,1118 +scipy/optimize/elementwise.py,sha256=8eEQW_PeNkr49YBTROr5xWDLgeJd7rxtdQk3tVuEECQ,1190 +scipy/optimize/lbfgsb.py,sha256=XT7kclUTtom8JASPYyAScx-5irlBd9s9yEnZzRwFqu8,601 +scipy/optimize/linesearch.py,sha256=w5OhOofynUbz7IzHAGEc6huLKV_rMR5eUq77VcskA9o,535 +scipy/optimize/minpack.py,sha256=2S9tkmBI670qqeDN7k_1-ZLYsFZV1yXaDMkrCvMETiQ,664 +scipy/optimize/minpack2.py,sha256=IPIduBcu0LRo75GJ9SiMa_GjfdKCOYzsWUs61_d1HR8,514 +scipy/optimize/moduleTNC.py,sha256=qTEQ4IWtv_LT6fH3-iYmYNwrtrjG1gS4KFbZ73iDcd0,507 +scipy/optimize/nonlin.py,sha256=uoKIYAdmhwNrC6zFbUIBCNdM1a59nn7hb5jxSOuK3rs,710 +scipy/optimize/optimize.py,sha256=SivH06ZYrbIwJLTQj3ZShU4FXft7w2y1a2uYE9ILIMo,877 +scipy/optimize/slsqp.py,sha256=Xei2XAZBNcz8cQdLdK8tTHeyIgpLEElP2ENdTH2QEi8,569 +scipy/optimize/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/optimize/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__basinhopping.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__differential_evolution.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__dual_annealing.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__linprog_clean_inputs.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__numdiff.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__remove_redundancy.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__root.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__shgo.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test__spectral.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_bracket.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_cobyla.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_cobyqa.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_constraint_conversion.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_constraints.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_direct.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_extending.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_hessian_update_strategy.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_lbfgsb_hessinv.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_lbfgsb_setulb.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_least_squares.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_linesearch.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_linprog.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_lsq_common.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_lsq_linear.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_milp.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_minpack.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_nnls.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_nonlin.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_optimize.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_quadratic_assignment.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_regression.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_slsqp.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_tnc.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_trustregion.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_trustregion_exact.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_trustregion_krylov.cpython-312.pyc,, +scipy/optimize/tests/__pycache__/test_zeros.cpython-312.pyc,, +scipy/optimize/tests/_cython_examples/extending.pyx,sha256=5TCYF9hvIYu8S9Y7PIql-xdJfcn_LI50yDrf4uh7i2M,1314 +scipy/optimize/tests/_cython_examples/meson.build,sha256=GCeweHtWXjvk73tZN3HqsMTw7F1St0JuIhGyxmEiPv0,703 +scipy/optimize/tests/test__basinhopping.py,sha256=5tsmhal5dAxecemRbRVVwhwmEmYMlR84b3_Ep8AgPzA,19230 +scipy/optimize/tests/test__differential_evolution.py,sha256=9lwlQpFfJL5HUIZ91YXPHh_V7jEyYzR_wDat3IJVH5E,71804 +scipy/optimize/tests/test__dual_annealing.py,sha256=narPlqiULIu0dlWySB9mWn6Y-1sjM_DaiwARgCQeVKA,16603 +scipy/optimize/tests/test__linprog_clean_inputs.py,sha256=kwBb1lKIYrRi07zw_zyXQE8dV3owopmXb4WYaff2qzI,11876 +scipy/optimize/tests/test__numdiff.py,sha256=zzjj-kAR8jUWDGPOS88HAeK0Avvq_LWifaaR5tR-8Lg,34627 +scipy/optimize/tests/test__remove_redundancy.py,sha256=wxGfVJaHD_-5g_aMNU3w92EuWrCrfhCLU1ixhFVio64,6883 +scipy/optimize/tests/test__root.py,sha256=xMNuKf_eNAFN6hwp1PzY7KIXlcFWV8ozPtzGtnZRmjA,4199 +scipy/optimize/tests/test__shgo.py,sha256=HYr2RFqo56lTX7Tfjjc97IEyVbJlpDW7CGTS8MN8Nqg,42350 +scipy/optimize/tests/test__spectral.py,sha256=V7J3hHkzYPLSgSycFVt2zEXUbO9N3wTfyhjRoTfz3Eo,6639 +scipy/optimize/tests/test_bracket.py,sha256=5Uv-mwZN_j_IdgXZ8q9nliyrFTIcqDDyrOihILQeN0I,36152 +scipy/optimize/tests/test_chandrupatla.py,sha256=OtuMLK4pOCsmR86tdvJWciCbRb5D9XSMMJzU8LZKRF0,38639 +scipy/optimize/tests/test_cobyla.py,sha256=gLCVj8xmmSoIx5oikBMr9PVpgyGsoyAG5JdcNAZJmmU,6822 +scipy/optimize/tests/test_cobyqa.py,sha256=5sHRoBc4ZVfjZZAYMGObwSAtWq2A53L9KSwHuUUhQLk,8143 +scipy/optimize/tests/test_constraint_conversion.py,sha256=2FUZwIk7TPMBd-ulpVs-puUcgrpKez3b87fgYJOhYs8,12522 +scipy/optimize/tests/test_constraints.py,sha256=X3Y31naHyXBgyI03UowHOPY_qxhRrL2I9fJtCvZ2kGo,9407 +scipy/optimize/tests/test_cython_optimize.py,sha256=n-HccBWoUmmBWq_OsNrAVnt4QrdssIYm4PWG29Ocias,2638 +scipy/optimize/tests/test_differentiable_functions.py,sha256=eqpZUgmxI2UI2hW-S7DfPCAdvHDUDZJr4D6J7vHEy-8,38437 +scipy/optimize/tests/test_direct.py,sha256=_R4_VkYkIJcS7X9a7n9rxwnZClK5i9nXSiYYkX0aRiA,13267 +scipy/optimize/tests/test_extending.py,sha256=r9Phn1PUn0U3U6QJeMiPreKG6jKmnWFqwpf1Al7w7K0,1104 +scipy/optimize/tests/test_hessian_update_strategy.py,sha256=EiL5ImqkGFmUTjgZjv0FGpGBjTzWXqT3w6eCrzQtPmo,14337 +scipy/optimize/tests/test_isotonic_regression.py,sha256=aJakW5zYcILN3wa--CYFBoZ3MB6n5Rzwd4WfNs_SFQk,7113 +scipy/optimize/tests/test_lbfgsb_hessinv.py,sha256=XnInFBGl9BQZS-wndHuPhNFDkb4kIsd02QMdVsg3Iy4,1934 +scipy/optimize/tests/test_lbfgsb_setulb.py,sha256=6Aqn26aKUJp75unFqCAzesLq_tWPsQpp2rCftauSOS8,3582 +scipy/optimize/tests/test_least_squares.py,sha256=_ozl0YHfvpPHCKbP7Kr8lpw4pVFY-eSUkVihDcJS_EM,38297 +scipy/optimize/tests/test_linear_assignment.py,sha256=vhP5go29wZY-XaszuCkajQzYqYKzqAPs5WSO5zI3j2M,4103 +scipy/optimize/tests/test_linesearch.py,sha256=BGEDLJjO8RUPW6Aek8AHb4VB4voOuTX88gYHEKkJud8,11598 +scipy/optimize/tests/test_linprog.py,sha256=XqBf5HVLQomD6lCg67_RIMOTd9YLsbKskmtSBcboAN0,105114 +scipy/optimize/tests/test_lsq_common.py,sha256=alCLPPQB4mrxLIAo_rn7eg9xrCEH7DerNBozSimOQRA,9500 +scipy/optimize/tests/test_lsq_linear.py,sha256=5K_o46uKUJsprMeeT7lwf9gBIfiFxzeeREoOEe8WSKs,11000 +scipy/optimize/tests/test_milp.py,sha256=JvtivR6ZrI4rB_LxMCCPSmpeJoWos699FF_RC-59u-4,18811 +scipy/optimize/tests/test_minimize_constrained.py,sha256=o1wJLIUkGRj6FEyd9ShkMhCqCu6dAwVtyuUKrQVcdTg,28130 +scipy/optimize/tests/test_minpack.py,sha256=4hOCKOnfsstwupL-_bmAkTgR3rDypkXVw8fwmf3f4LI,44879 +scipy/optimize/tests/test_nnls.py,sha256=ib5rfMaFlDIq28Ir8H5ZJfvYuVd5ZzPjrXtqKJ7BtM0,27195 +scipy/optimize/tests/test_nonlin.py,sha256=nbAIXMTq-KlH2EjCui1CbgUtFpwftj3cLWkK0Ah58nc,20250 +scipy/optimize/tests/test_optimize.py,sha256=fzfiKb9mh9hH24tzFttm3StetaNnlNNUXnZEZU1_gfs,143191 +scipy/optimize/tests/test_quadratic_assignment.py,sha256=uc6HeZZ5QXAIEl1aIKV9FJCkbeYW8xAbcwuX3TvvrZk,17508 +scipy/optimize/tests/test_regression.py,sha256=CSg8X-hq6-6jW8vki6aVfEFYRUGTWOg58silM1XNXbU,1077 +scipy/optimize/tests/test_slsqp.py,sha256=io__JB2LIrNtcV3uwgXq26g5jJY2YV_YQyzW8-YebsU,25662 +scipy/optimize/tests/test_tnc.py,sha256=ahSwu8F1tUcPV09l1MsbacUXXi1avQHzQNniYhZRf4s,12700 +scipy/optimize/tests/test_trustregion.py,sha256=IhrFNgseaMd-R6RizA9obQP9m0zozGgLSaxHSXbBBFA,4638 +scipy/optimize/tests/test_trustregion_exact.py,sha256=99gAvNkeN9CmGOfNKpOmigMhZpQh6NnnVhm1qIV_bQ8,21301 +scipy/optimize/tests/test_trustregion_krylov.py,sha256=G_p_Kje8awkqw1Z9AV0k9xI9BWRrPUKZgCoeo94g7y0,6571 +scipy/optimize/tests/test_zeros.py,sha256=A-Zctk9ZFE2Zau4WeVcTMAzU6t8nQr-k8yxtWcbVAiE,37955 +scipy/optimize/tnc.py,sha256=aEKhka8wryg4mVlbrGFwzTJF_KYB49joMkSxKgh1KnA,560 +scipy/optimize/zeros.py,sha256=Sc06-J8JUazdfR36UamHhPndJoPK0FkOzHR-unHWoBw,620 +scipy/signal/__init__.py,sha256=A8hqxncT2j2t_zb1iIWVga5bH1VgeSkKjHg--FQlNWQ,13561 +scipy/signal/__pycache__/__init__.cpython-312.pyc,, +scipy/signal/__pycache__/_arraytools.cpython-312.pyc,, +scipy/signal/__pycache__/_czt.cpython-312.pyc,, +scipy/signal/__pycache__/_delegators.cpython-312.pyc,, +scipy/signal/__pycache__/_filter_design.cpython-312.pyc,, +scipy/signal/__pycache__/_fir_filter_design.cpython-312.pyc,, +scipy/signal/__pycache__/_lti_conversion.cpython-312.pyc,, +scipy/signal/__pycache__/_ltisys.cpython-312.pyc,, +scipy/signal/__pycache__/_max_len_seq.cpython-312.pyc,, +scipy/signal/__pycache__/_peak_finding.cpython-312.pyc,, +scipy/signal/__pycache__/_polyutils.cpython-312.pyc,, +scipy/signal/__pycache__/_savitzky_golay.cpython-312.pyc,, +scipy/signal/__pycache__/_short_time_fft.cpython-312.pyc,, +scipy/signal/__pycache__/_signal_api.cpython-312.pyc,, +scipy/signal/__pycache__/_signaltools.cpython-312.pyc,, +scipy/signal/__pycache__/_spectral_py.cpython-312.pyc,, +scipy/signal/__pycache__/_spline_filters.cpython-312.pyc,, +scipy/signal/__pycache__/_support_alternative_backends.cpython-312.pyc,, +scipy/signal/__pycache__/_upfirdn.cpython-312.pyc,, +scipy/signal/__pycache__/_waveforms.cpython-312.pyc,, +scipy/signal/__pycache__/_wavelets.cpython-312.pyc,, +scipy/signal/__pycache__/bsplines.cpython-312.pyc,, +scipy/signal/__pycache__/filter_design.cpython-312.pyc,, +scipy/signal/__pycache__/fir_filter_design.cpython-312.pyc,, +scipy/signal/__pycache__/lti_conversion.cpython-312.pyc,, +scipy/signal/__pycache__/ltisys.cpython-312.pyc,, +scipy/signal/__pycache__/signaltools.cpython-312.pyc,, +scipy/signal/__pycache__/spectral.cpython-312.pyc,, +scipy/signal/__pycache__/spline.cpython-312.pyc,, +scipy/signal/__pycache__/waveforms.cpython-312.pyc,, +scipy/signal/__pycache__/wavelets.cpython-312.pyc,, +scipy/signal/_arraytools.py,sha256=k3kHbl9RzcqsyftIYSFJZvJFL4zlcMAHyaRFUkFxOXY,8294 +scipy/signal/_czt.py,sha256=t5P1kRCM3iw3eCaL9hTgctMfQKezkqnjbghLjCkffQE,19445 +scipy/signal/_delegators.py,sha256=Flc_oinMci8_PZdVZXB775JFZDcjYy4NvTpa5klN_n8,14646 +scipy/signal/_filter_design.py,sha256=pSpXlae6s_HZMpDb-QI-rA_Qwtq0XW5pEdl-4Jz0Gyk,204408 +scipy/signal/_fir_filter_design.py,sha256=cSnE-AvsGISz1mGPuvtoEiMDNG3ey9lhsX1mJAjVJiQ,64160 +scipy/signal/_lti_conversion.py,sha256=w1SlFZSv9U-T5EM1-B6A6FDfRZmEwewyrWHSmrjPZHs,18281 +scipy/signal/_ltisys.py,sha256=ZYa0xvsIUGLp7Xdsg8QlPX2kgU11IeDeh7_aqcgyxDU,121224 +scipy/signal/_max_len_seq.py,sha256=8QkMWoYY3qy3bCKfsuXaS93Bnb2zd-ue6j5i5-3_hi0,5060 +scipy/signal/_max_len_seq_inner.cpython-312-darwin.so,sha256=umS_I3-RkUPASeWjKvNX0q8DiADBz3XMbjpWyWOD-Bc,75992 +scipy/signal/_peak_finding.py,sha256=e9vpWL98OQ9Ik1f7gwLl4d5feTAiyLwPm_yarJq3T_8,48856 +scipy/signal/_peak_finding_utils.cpython-312-darwin.so,sha256=rzGwWnOxpDNZcCJ8PI8vWO7NYjuJ4bJn34-T51f6nEs,131336 +scipy/signal/_polyutils.py,sha256=V3QGVjltypg--YVe8nHw_3xZpcqrjvyiSqbRewqWNPA,8416 +scipy/signal/_savitzky_golay.py,sha256=4SSWfYNIsyQrWpQTbV1mJvQ08YPvn9SLlPna_DXqono,14372 +scipy/signal/_short_time_fft.py,sha256=ObTun_SoEMiDdlEURsp4XnFtt6vvpVRLL9aJPEGuIcI,101673 +scipy/signal/_signal_api.py,sha256=wp3qv0vBhANNCCq1S--VUWmHRdEDy5u5obbNDNUk_Cw,1237 +scipy/signal/_signaltools.py,sha256=h9nbt_Z0zPufE_E4GUrBTQyH-Fa5cM84VTsk38nXFhQ,196595 +scipy/signal/_sigtools.cpython-312-darwin.so,sha256=kwELAj0THIKoHuub6N4xk8tvbfaUqf-YiKYBt2EgF-0,123120 +scipy/signal/_sosfilt.cpython-312-darwin.so,sha256=1MfnMBEQ-2D0ylmEJg6zOFbm2kCiOAanMJ4aEU22kxg,114464 +scipy/signal/_spectral_py.py,sha256=nB-p-lmc5nDr6RYXzkPREimp2V9Lety_1nW7KkTrQI4,97065 +scipy/signal/_spline.cpython-312-darwin.so,sha256=a5YSs3oLOplk_BnZFJJjhk0DvjHy6SgqXRgmraJWlwE,69744 +scipy/signal/_spline.pyi,sha256=9tWZQCI7D84ONLwICZG6psBGtwKxAvLF7JaZ1tQUKoY,948 +scipy/signal/_spline_filters.py,sha256=6BX6eu7yt2qNYSY8VJtZ1wHrQbOzvxK0mGre6eNtRpU,25439 +scipy/signal/_support_alternative_backends.py,sha256=EGqh6VeDiWyKwtcx-Et-J8aOvyOsVbXf1pZA_nVRBqg,18177 +scipy/signal/_upfirdn.py,sha256=bE78hIj-iGh7wCXcMh-3Tus9WM_pptNoGLHKXHLFvu0,7976 +scipy/signal/_upfirdn_apply.cpython-312-darwin.so,sha256=DcrEsoebqQryYXKAnAjmbBKXr3QRbjevyOY5VdELnTc,184968 +scipy/signal/_waveforms.py,sha256=0Gembo6HsY--mZJ82tFCEw5RYzfhxeDY-gFHOHdJXBk,22912 +scipy/signal/_wavelets.py,sha256=K7wj6hMQgJrJ1sb3b2SB4LRc7JlZx5ej9tX6v7E1YCw,886 +scipy/signal/bsplines.py,sha256=G1sa6en1z_41sU7ckRY8-flJjUKSqJJihaxBlwzUd3s,651 +scipy/signal/filter_design.py,sha256=EyHs8OX4mdeUi6e3Zf7IWuz6r5Re2eR_t0Bi10JuntM,1112 +scipy/signal/fir_filter_design.py,sha256=mJr3FG_K_4qbzLOUasIJmXSycuFmotHkEMCAn812v6I,657 +scipy/signal/lti_conversion.py,sha256=6uQ1qaT7XI75DoFmtRqRS94Hkpm-Qvy66CRNhmQ-Lbw,639 +scipy/signal/ltisys.py,sha256=TFul9jyL0ujEIchiOnDdIiJKIXZ8SSgOV066DvmX_QA,869 +scipy/signal/signaltools.py,sha256=I7U_hMuMf02zpdNi0LcPogucTDf0nUVUSkMZ1eAoq3E,1038 +scipy/signal/spectral.py,sha256=RA3jj6AWV6ptNwXfpVrbuyxxed8P7nWw8bLsD0iZIgw,662 +scipy/signal/spline.py,sha256=rC_E8HwcpDqwIGdaDF0Cb5uC6kPoAQP57jeQNq-aCmI,536 +scipy/signal/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/signal/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/signal/tests/__pycache__/_scipy_spectral_test_shim.cpython-312.pyc,, +scipy/signal/tests/__pycache__/mpsig.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_array_tools.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_bsplines.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_cont2discrete.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_czt.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_dltisys.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_filter_design.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_fir_filter_design.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_ltisys.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_max_len_seq.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_peak_finding.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_result_type.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_savitzky_golay.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_short_time_fft.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_signaltools.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_spectral.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_splines.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_upfirdn.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_waveforms.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_wavelets.cpython-312.pyc,, +scipy/signal/tests/__pycache__/test_windows.cpython-312.pyc,, +scipy/signal/tests/_scipy_spectral_test_shim.py,sha256=ioVfbdXOV77dDef-hcpuwqnDES1ZaQg29ZjYTd_ts1g,12748 +scipy/signal/tests/mpsig.py,sha256=DHB3eHB0KYA-E0SBebKG36YLk-T5egbwwryne3RwIHM,3308 +scipy/signal/tests/test_array_tools.py,sha256=QN4SGbtxDSP2MFvyYl00RasYYyNF4A1g8Y6_1Sij7YQ,3589 +scipy/signal/tests/test_bsplines.py,sha256=jTmrfmpGY5R_SjYVAwWahCukYTnD-IKOIQA9TM_B3ME,19116 +scipy/signal/tests/test_cont2discrete.py,sha256=d-b1pgroBK-4jByyn8bwvvkvmUbV1qUGIxVRQs9Mplc,15570 +scipy/signal/tests/test_czt.py,sha256=2-kcWyadICVl_mF0vbq1KYii-rYMtZiuiOSb6HkYn7w,7156 +scipy/signal/tests/test_dltisys.py,sha256=gefhLnAHHlgVJlW1jJRn5d3inR5RX_-ke6q7r_4g1j0,21567 +scipy/signal/tests/test_filter_design.py,sha256=qd_EZmzF9gmpBEA0w5ryHcJt-rAdIm4TQVDq4U8T9ak,228943 +scipy/signal/tests/test_fir_filter_design.py,sha256=Fz10PbpgRLzJZOQWhmcrtl37UufY7rKoMYQO82ZnS9s,36654 +scipy/signal/tests/test_ltisys.py,sha256=2x6xHq_bJdihoXDkoK3XY9J04H0VqC_bG_M9G2DQl8M,46097 +scipy/signal/tests/test_max_len_seq.py,sha256=JzfWWN4n6FO9Axw6H6xWrWyc21LlkqMwkGl23f-V664,3318 +scipy/signal/tests/test_peak_finding.py,sha256=YUqNXTV70bjgdpDlgCQNniiR0wUM-gECbW9zvP_wzT0,36023 +scipy/signal/tests/test_result_type.py,sha256=F48EQGbFfQfMwcnt-sMofHGNHVTbHntbMlgoeS2vYcY,1573 +scipy/signal/tests/test_savitzky_golay.py,sha256=tTtbTECtl3Ou1-QB1BI7KcpPryzU2GrR_p-qoQdknTc,14270 +scipy/signal/tests/test_short_time_fft.py,sha256=H1QZ2SX1DhVtPobHrJbnbVe1Kg6aObepadduiWXmJsI,48294 +scipy/signal/tests/test_signaltools.py,sha256=s9NCso2IV53Mcef_HZObIysePHctKdfoAFnvzDVuhj8,196642 +scipy/signal/tests/test_spectral.py,sha256=nhqL27Tpa5WjunBQXaWGljJEPEUZt7rd3QWWQFPnC6w,83384 +scipy/signal/tests/test_splines.py,sha256=UJ4UNfwXWFWmfo_lu7ZHngIrUZmmlyx5f-cAK7sLEPQ,16957 +scipy/signal/tests/test_upfirdn.py,sha256=yds26YXmh1uqCJouI_X4RjbrhBLbHvZG1HZJ_gD57CM,13011 +scipy/signal/tests/test_waveforms.py,sha256=HfyUh2X65Qfv0qNLGOk99XAtwy8ELEcIDJnCCoHR6WY,13554 +scipy/signal/tests/test_wavelets.py,sha256=42yMux80J-K7Ue9QLnzN84U9K3j2GRdywMxGpbLldeM,2145 +scipy/signal/tests/test_windows.py,sha256=MSn9jcMDJb06XzHQuYFnTSKSLhbRIkx0PMA30VV9DGQ,55199 +scipy/signal/waveforms.py,sha256=jfOXW7kgtGdh1nrMo1YLAh79W_Ln3WgzEN2esrp70wE,599 +scipy/signal/wavelets.py,sha256=7pA7HVMiXwG4fZZ0Q4nzz47hWWALMTYtxwGrIqV3bNE,510 +scipy/signal/windows/__init__.py,sha256=TtLlEQSIXo8WiAPJh0raWYS8_5zLHOjarzCmDhj9Eu8,2126 +scipy/signal/windows/__pycache__/__init__.cpython-312.pyc,, +scipy/signal/windows/__pycache__/_windows.cpython-312.pyc,, +scipy/signal/windows/__pycache__/windows.cpython-312.pyc,, +scipy/signal/windows/_windows.py,sha256=eVK6aQbJ5jl2pVbz6NuQ2bbmfG3SUCYcGf4PAEuJ7kI,95033 +scipy/signal/windows/windows.py,sha256=FI6w8mt0V1221Rqv3Do3LuWRWrtKo3hYYTvpB_5UB1c,839 +scipy/sparse/__init__.py,sha256=kugwj8l-e9bCdjUFCEV4nQ517Qur2kgNQ6hv8dIplsU,10109 +scipy/sparse/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/__pycache__/_base.cpython-312.pyc,, +scipy/sparse/__pycache__/_bsr.cpython-312.pyc,, +scipy/sparse/__pycache__/_compressed.cpython-312.pyc,, +scipy/sparse/__pycache__/_construct.cpython-312.pyc,, +scipy/sparse/__pycache__/_coo.cpython-312.pyc,, +scipy/sparse/__pycache__/_csc.cpython-312.pyc,, +scipy/sparse/__pycache__/_csr.cpython-312.pyc,, +scipy/sparse/__pycache__/_data.cpython-312.pyc,, +scipy/sparse/__pycache__/_dia.cpython-312.pyc,, +scipy/sparse/__pycache__/_dok.cpython-312.pyc,, +scipy/sparse/__pycache__/_extract.cpython-312.pyc,, +scipy/sparse/__pycache__/_index.cpython-312.pyc,, +scipy/sparse/__pycache__/_lil.cpython-312.pyc,, +scipy/sparse/__pycache__/_matrix.cpython-312.pyc,, +scipy/sparse/__pycache__/_matrix_io.cpython-312.pyc,, +scipy/sparse/__pycache__/_spfuncs.cpython-312.pyc,, +scipy/sparse/__pycache__/_sputils.cpython-312.pyc,, +scipy/sparse/__pycache__/base.cpython-312.pyc,, +scipy/sparse/__pycache__/bsr.cpython-312.pyc,, +scipy/sparse/__pycache__/compressed.cpython-312.pyc,, +scipy/sparse/__pycache__/construct.cpython-312.pyc,, +scipy/sparse/__pycache__/coo.cpython-312.pyc,, +scipy/sparse/__pycache__/csc.cpython-312.pyc,, +scipy/sparse/__pycache__/csr.cpython-312.pyc,, +scipy/sparse/__pycache__/data.cpython-312.pyc,, +scipy/sparse/__pycache__/dia.cpython-312.pyc,, +scipy/sparse/__pycache__/dok.cpython-312.pyc,, +scipy/sparse/__pycache__/extract.cpython-312.pyc,, +scipy/sparse/__pycache__/lil.cpython-312.pyc,, +scipy/sparse/__pycache__/sparsetools.cpython-312.pyc,, +scipy/sparse/__pycache__/spfuncs.cpython-312.pyc,, +scipy/sparse/__pycache__/sputils.cpython-312.pyc,, +scipy/sparse/_base.py,sha256=5tcP1l8DePGYzfDIOYaqO0d_h9pHE3A372BW1CSB_Rs,58343 +scipy/sparse/_bsr.py,sha256=wAzh3MxiT1K9AQQgi49uNzjfCst6jZHy31np1k40mNE,31157 +scipy/sparse/_compressed.py,sha256=2NhHzrEEabkdwvZOK-fsOvBOGgmdufu5H7MlJvhg3A8,52058 +scipy/sparse/_construct.py,sha256=_-O4bnUUa1iJB5sMtwUyrRr-hiJazqzahyelx1ddIks,59658 +scipy/sparse/_coo.py,sha256=s0kP0yRarvRoIpij66FHTsyuB1RarxlHyRsOpm3Heew,75029 +scipy/sparse/_csc.py,sha256=iMRi5xFyFpKV-o4ff_I9SjwAN-hHp7YDfnTIEu4jZVI,11162 +scipy/sparse/_csparsetools.cpython-312-darwin.so,sha256=d6JCwpNxJce1467JgiKZsDxhFTYsty1amtlL-NF8g_o,404752 +scipy/sparse/_csr.py,sha256=j-VF_qQnndzv_e8XO0OWa6ofYzmXZm63Heqrm2BGqhM,18601 +scipy/sparse/_data.py,sha256=yeFDnTI6jBp62Kb0DigJ2jAsJwb9cBn2kWiU9pS16mg,20980 +scipy/sparse/_dia.py,sha256=iGXFZUjsEbwYlXKx_gelLMjs-MTuvmbE6QUlnf3QLUw,23643 +scipy/sparse/_dok.py,sha256=sVXX5QYYbCiEWwqeqSJsXlQ3cSxbVDwFz0hUajMLhmY,23387 +scipy/sparse/_extract.py,sha256=0NWW00hxjk5gl4CjNRHtvcqsx54yNei2VVbqARMOlAo,5058 +scipy/sparse/_index.py,sha256=iCFt5cKBZF2J2e6DSjwtpW7LKv4feFMTaz0p5ujgX5o,18216 +scipy/sparse/_lil.py,sha256=tY9AM6oiyYrqPbeYmXjOgq3JGzlvLmxcH6F89-gmbYQ,20889 +scipy/sparse/_matrix.py,sha256=e57TxL-4_ZNCWWwW4GdwYmY2fplQQCQqhpBheJn-XRk,5022 +scipy/sparse/_matrix_io.py,sha256=N086rQFxa4_RUXaxSwPojMk1yzRxrq5MqpCd08jy-_E,6241 +scipy/sparse/_sparsetools.cpython-312-darwin.so,sha256=tkXIvZWupgo8w3xdCpWSemfC7-0gtXS3e0FDGw_lANY,3614784 +scipy/sparse/_spfuncs.py,sha256=lDVTp6CiQIuMxTfSzOi3-k6p97ayXJxdKPTf7j_4GWc,1987 +scipy/sparse/_sputils.py,sha256=sc3DLX5J-rWt1-wU8IWDISdRhuCDNi5swmKPb-9aZB8,21095 +scipy/sparse/base.py,sha256=Kyn-S8HXKVlf_mHMGhcxbnLYqFyZpx5ydS707bnOhDM,609 +scipy/sparse/bsr.py,sha256=M_uhxnBwHnh0p4C7xE8tj82PiXATa4_gHIfOvLyh3gg,561 +scipy/sparse/compressed.py,sha256=lyEi-UD6ygcufeIqRBHpGfjVckp-vIlojYBjfnLc7Us,550 +scipy/sparse/construct.py,sha256=vfz2WK4r2bviiKZSUiIsfdDFDu9osyFlXF8ZsxSAn3E,812 +scipy/sparse/coo.py,sha256=ui1P-vcbPnLArYHxLWO06N1KFsCfw-CD6TWz_YSQ8-k,592 +scipy/sparse/csc.py,sha256=X9TL9GN1YtbJluM0Iq9_cDyDQBACYlJ7MToGQomvKOA,561 +scipy/sparse/csgraph/__init__.py,sha256=znrEd48JFLdlcevl8IFDSM104Yl1YvXC0O_f8OUWATs,7842 +scipy/sparse/csgraph/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/csgraph/__pycache__/_laplacian.cpython-312.pyc,, +scipy/sparse/csgraph/__pycache__/_validation.cpython-312.pyc,, +scipy/sparse/csgraph/_flow.cpython-312-darwin.so,sha256=pznFHFBKPF0glzGJY96wfOUNqIz-2STFb0F2f7IugDU,165944 +scipy/sparse/csgraph/_laplacian.py,sha256=bpCduRWjIhcDpclvPbftx74PExTiW0P3EE6_Ztiop1Y,18273 +scipy/sparse/csgraph/_matching.cpython-312-darwin.so,sha256=gl1bvWg82gocGJYrty2GPVXPjBSnpP-NDAtpB24KXyQ,164928 +scipy/sparse/csgraph/_min_spanning_tree.cpython-312-darwin.so,sha256=z8OG_Y3PtoyZZgkYqFUL_Qr1ePdDVUxzCqhtbds4Yes,114216 +scipy/sparse/csgraph/_reordering.cpython-312-darwin.so,sha256=kkxJPe6b_SYd0BIJTkhK7pHBJ0t33MwqG-kxe3G7SAk,149904 +scipy/sparse/csgraph/_shortest_path.cpython-312-darwin.so,sha256=jGCFW89cRUChgw9V_-bas9diVF0j0EXypxUekHwvF4g,346280 +scipy/sparse/csgraph/_tools.cpython-312-darwin.so,sha256=ooDxkUVdLG3VVLv5mLLUKuu1njQfoeHKU2dxRRTBnh0,164800 +scipy/sparse/csgraph/_traversal.cpython-312-darwin.so,sha256=YVIkrgDG-jICnoWgwPg9b3wNh-ee1p_NFjgr_F7Vlpg,286128 +scipy/sparse/csgraph/_validation.py,sha256=SxINtd4jYyH0YWdzspr8JR0syZfO3nMj7C60GWBUr6k,2629 +scipy/sparse/csgraph/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/csgraph/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_connected_components.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_conversions.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_flow.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_graph_laplacian.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_matching.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_pydata_sparse.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_reordering.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_shortest_path.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_spanning_tree.cpython-312.pyc,, +scipy/sparse/csgraph/tests/__pycache__/test_traversal.cpython-312.pyc,, +scipy/sparse/csgraph/tests/test_connected_components.py,sha256=a2HZjm7HsC0STqiDnhN6OJL4yIMcM28VNVtMXDI2BqE,3948 +scipy/sparse/csgraph/tests/test_conversions.py,sha256=3n2UJ_rwdcTkD8NfwDrk-8UBplJkqMFw12yPIwX9-R8,1854 +scipy/sparse/csgraph/tests/test_flow.py,sha256=I7csygtef5f6Uv67t2y3UZsln8Gg4eS1RE5zr7Xm-Eg,7718 +scipy/sparse/csgraph/tests/test_graph_laplacian.py,sha256=dG9JNNCgU4O6Y3xrV26IWcLV-Rn2TOe0PGCfkv_jGiM,10952 +scipy/sparse/csgraph/tests/test_matching.py,sha256=s5tq96kG0DojkE_8ZqaP9olNv5yPYYNypG2Si3Z-Qps,12367 +scipy/sparse/csgraph/tests/test_pydata_sparse.py,sha256=GSv9fe0hPROU8yynAf2m6WO9JC2yyY1aLSXxd7_eiR8,4967 +scipy/sparse/csgraph/tests/test_reordering.py,sha256=_WNqdGcU-WNhQRpjCq4Nhp8YY6cmVKb13au5sJPpzig,2569 +scipy/sparse/csgraph/tests/test_shortest_path.py,sha256=nSP2dAcf4iDg-HsmcDWHLbq0KLjg1sM-La1tVTOT7Sc,18744 +scipy/sparse/csgraph/tests/test_spanning_tree.py,sha256=q4LYiXxfwWUc1io4vRVBr9uxMacfdefPvcRlb3TOEnw,2164 +scipy/sparse/csgraph/tests/test_traversal.py,sha256=7ma9viR6P2FecuWbZVt1kDXvbuHS6WTp1na9uBHKOBE,6212 +scipy/sparse/csr.py,sha256=MaN7K1B7ejJdKlpOZhrkP5YcBVxVPYk_io4okYc_koQ,561 +scipy/sparse/data.py,sha256=R-tvadwaAxifKWzzxhz0awKv2OA89AduDenjz1B2Z1A,504 +scipy/sparse/dia.py,sha256=KsOmYg5wsX-kOKM_vaarB_3LpeZo0eo1qC1UdsiBEnE,561 +scipy/sparse/dok.py,sha256=ki_m850wPAbA8w3qxkXqAWIDo5p2h5cU14c7Pg9PNos,561 +scipy/sparse/extract.py,sha256=6qT2PNOilsEhDWl6MhmgpveIuQr4QCs3LATwIrBroOQ,567 +scipy/sparse/lil.py,sha256=Gve3XHYPYZavcUPJz1TSOhjv6AtPpkKBHTzCK6FG8ek,562 +scipy/sparse/linalg/__init__.py,sha256=EuUOCB6Y1PFw1_vTfc7F5eMdCOMQcLwO7igl0_Qymik,4228 +scipy/sparse/linalg/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_expm_multiply.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_funm_multiply_krylov.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_interface.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_matfuncs.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_norm.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_onenormest.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_special_sparse_arrays.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/_svdp.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/dsolve.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/eigen.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/interface.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/isolve.cpython-312.pyc,, +scipy/sparse/linalg/__pycache__/matfuncs.cpython-312.pyc,, +scipy/sparse/linalg/_dsolve/__init__.py,sha256=PIX7n_d0LOMZZZ65Dz4Mgz9trjKGB2kLaF16PQLkAIs,2039 +scipy/sparse/linalg/_dsolve/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_dsolve/__pycache__/_add_newdocs.cpython-312.pyc,, +scipy/sparse/linalg/_dsolve/__pycache__/linsolve.cpython-312.pyc,, +scipy/sparse/linalg/_dsolve/_add_newdocs.py,sha256=4Nm6RAKQlKI4lQt4z20v0D6m0Vk8eqp0mIzEk5gfztA,3743 +scipy/sparse/linalg/_dsolve/_superlu.cpython-312-darwin.so,sha256=B9qXg_igsnxKiVOYHKxMulq0LA88O-W_96Cd1XJaeNY,280960 +scipy/sparse/linalg/_dsolve/linsolve.py,sha256=qJAUlWLwmhnwdw2R7lBX7LEGj2vxiKvS0aeRlsFb84g,31328 +scipy/sparse/linalg/_dsolve/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/linalg/_dsolve/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_dsolve/tests/__pycache__/test_linsolve.cpython-312.pyc,, +scipy/sparse/linalg/_dsolve/tests/test_linsolve.py,sha256=GE1am6F-Key7jQJePQd8-BrIo3sV4V-NJ2bqye7Gx34,34644 +scipy/sparse/linalg/_eigen/__init__.py,sha256=SwNho3iWZu_lJvcdSomA5cQdcDU8gocKbmRnm6Bf9-0,460 +scipy/sparse/linalg/_eigen/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/__pycache__/_svds.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/__pycache__/_svds_doc.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/_svds.py,sha256=WYY_AfAMJgN3dD8ONPHjjF-gmWa904fv_lcxLmmnFx4,20203 +scipy/sparse/linalg/_eigen/_svds_doc.py,sha256=0_sC8kKbu3b5BYpGl16sPLrZu6mDxiFhj8xkbG2w5-U,15003 +scipy/sparse/linalg/_eigen/arpack/__init__.py,sha256=zDxf9LokyPitn3_0d-PUXoBCh6tWK0eUSvsAj6nkXI0,562 +scipy/sparse/linalg/_eigen/arpack/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/arpack/__pycache__/arpack.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/arpack/_arpacklib.cpython-312-darwin.so,sha256=zXucH7HWoVPgOAr55eIiKmwuYSecKFlyryTDVu5KAAo,179168 +scipy/sparse/linalg/_eigen/arpack/arpack.py,sha256=yhNKU-iSw4ZNQJugnh5KFdAP_o5615EAT8Sf-3doy_A,69630 +scipy/sparse/linalg/_eigen/arpack/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/linalg/_eigen/arpack/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/arpack/tests/__pycache__/test_arpack.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/arpack/tests/test_arpack.py,sha256=f4rFTKIhuZb3IaYe3eJc6cv05lMyHnp475qxyNFnzMI,24666 +scipy/sparse/linalg/_eigen/lobpcg/__init__.py,sha256=E5JEPRoVz-TaLrj_rPm5LP3jCwei4XD-RxbcxYwf5lM,420 +scipy/sparse/linalg/_eigen/lobpcg/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/lobpcg/__pycache__/lobpcg.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py,sha256=J4nV8lQWq-sn41FeCUjXQTtk4kH0RbChmuOruFbLTDg,41937 +scipy/sparse/linalg/_eigen/lobpcg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/linalg/_eigen/lobpcg/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/lobpcg/tests/__pycache__/test_lobpcg.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/lobpcg/tests/test_lobpcg.py,sha256=SQtxbX6z9bCks9AXkdYYbg6w-zZ8hjljNNfB6kEz-uo,27547 +scipy/sparse/linalg/_eigen/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/linalg/_eigen/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/tests/__pycache__/test_svds.cpython-312.pyc,, +scipy/sparse/linalg/_eigen/tests/test_svds.py,sha256=jutn53fesaMNiNMI6Xi29mHZJPNP3NxO4jNi0P2Cxfs,36616 +scipy/sparse/linalg/_expm_multiply.py,sha256=KOSuV2qF4OSKrLGSwUAFT1ibnv4bhU9JBFJkvy9AVXY,26491 +scipy/sparse/linalg/_funm_multiply_krylov.py,sha256=5h4viKrFkBrpK4zV-gOdCquAKVc3zuQWvhzgWkuluXU,12194 +scipy/sparse/linalg/_interface.py,sha256=7o0WNoCL7X6CKy2DxkvYkOX1X_JTAmvaTtPKfp-gQwA,29583 +scipy/sparse/linalg/_isolve/__init__.py,sha256=Z_eQUYbe6RWMSNi09T9TfPEWm8RsVxcIKYAlihM-U-c,479 +scipy/sparse/linalg/_isolve/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/_gcrotmk.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/iterative.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/lgmres.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/lsqr.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/tfqmr.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/__pycache__/utils.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/_gcrotmk.py,sha256=C6CIO3qXgmCod_AmV3ErdIDrymYCx5_tbqhb0ZwdDa8,15746 +scipy/sparse/linalg/_isolve/iterative.py,sha256=-des4DKVAA17GnbdEiKSCJCKWRQLdBZp6WG2lzMRDo8,33423 +scipy/sparse/linalg/_isolve/lgmres.py,sha256=4o_BMPrhyjXHH6HABhkU8jpEjVDQPaAzdLrdAFZZTxw,8623 +scipy/sparse/linalg/_isolve/lsmr.py,sha256=8MRtv-FJa7nOHlJ7MZ4TsQiWAkZwntD0r55SOQuRqvI,15650 +scipy/sparse/linalg/_isolve/lsqr.py,sha256=Ca2SjyNwMFXSckUTW_LqYFkFc5CWOaZ1yiYB0tK2uB8,21322 +scipy/sparse/linalg/_isolve/minres.py,sha256=akSoJYFPE5no3XPZrkIpdY8DEVLKdf8XCmmN_6zceCE,10862 +scipy/sparse/linalg/_isolve/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/linalg/_isolve/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/__pycache__/test_gcrotmk.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/__pycache__/test_iterative.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/__pycache__/test_lgmres.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsmr.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/__pycache__/test_lsqr.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/__pycache__/test_minres.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/__pycache__/test_utils.cpython-312.pyc,, +scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py,sha256=3V-JDPsjIsCce7P06cBZJU0LEK3ioBmD0KSezcOBvQY,6069 +scipy/sparse/linalg/_isolve/tests/test_iterative.py,sha256=bEPFrmwNp8UwLpP2nSwH-lKy2YY98Ac7B6FWj6E51hI,26265 +scipy/sparse/linalg/_isolve/tests/test_lgmres.py,sha256=nUWVBNX-e5fo2abWW-0DzNPvxWW7us4IJUWe8k1jjZk,7695 +scipy/sparse/linalg/_isolve/tests/test_lsmr.py,sha256=6D3aZELcgJrp3Qf_HisAIowcwxnCzAiCfTf77YNsbrg,6362 +scipy/sparse/linalg/_isolve/tests/test_lsqr.py,sha256=tYKtlTuXMYYHvfpmrhdCqlzk0BIyohl2b-4b0SA6nBg,3759 +scipy/sparse/linalg/_isolve/tests/test_minres.py,sha256=d_rLkqdObBDD4FBpTOYgzwysTqBtYjgV5v1IDLhyr-8,2434 +scipy/sparse/linalg/_isolve/tests/test_utils.py,sha256=VlmvctRaQtjuYvQuoe2t2ufib74Tua_7qsiVrs3j-p0,265 +scipy/sparse/linalg/_isolve/tfqmr.py,sha256=c8zWhLGlxrY2fUhZReBTqz-Bm274ds97nES19sylkXs,6161 +scipy/sparse/linalg/_isolve/utils.py,sha256=o3T9hbZOk0XXz36AfmTM1KLFHry29atMCldJ1WoZx_k,3387 +scipy/sparse/linalg/_matfuncs.py,sha256=O5I5AmSCVoPzdhBMNzmjxoeCOmO8dN57zTfJbbV5GWo,29338 +scipy/sparse/linalg/_norm.py,sha256=86KekAh-FaTPKywik6NdU3N7n8dgly5CaaTjGzoOiw0,6120 +scipy/sparse/linalg/_onenormest.py,sha256=43iH6jN2r_kiSvZuOw1AhXyETGihtkA99b0wGMGqexc,15482 +scipy/sparse/linalg/_propack.cpython-312-darwin.so,sha256=oDJzvqivzqQhDXBVd44S4ft0cvL8zKEJCFnYHpJto44,140112 +scipy/sparse/linalg/_special_sparse_arrays.py,sha256=NCu2AF3oV3s47KHPX2qgzc3IQQPs1a9RAX9xuHRHLxk,34361 +scipy/sparse/linalg/_svdp.py,sha256=tTZEFaCdqUlvJQ1Nw9CHuO5XV_1949yhIwLqAzbp6so,10352 +scipy/sparse/linalg/dsolve.py,sha256=fvCzVUda-h-WzwGWDss4FVuv6TVE-OKHzARBlUCDIJw,654 +scipy/sparse/linalg/eigen.py,sha256=4BTo8Tc9SNQaruyrF4gRdFE5NstiA0XH9I44IyikZQ4,626 +scipy/sparse/linalg/interface.py,sha256=_KXBkGhZWvY_ZmGixqWMZe6J64bCPdjtrqr63HvicUI,573 +scipy/sparse/linalg/isolve.py,sha256=diSAxpbYg8PeH75QOEE-CREO8p39f4BZK2dGynJDKIc,649 +scipy/sparse/linalg/matfuncs.py,sha256=H2qJl4ZZqZ4bI-E9NCbu1oFfto0EdFxCTKTugMPHRHg,570 +scipy/sparse/linalg/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/linalg/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_expm_multiply.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_funm_multiply_krylov.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_interface.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_matfuncs.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_norm.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_onenormest.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_propack.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_pydata_sparse.cpython-312.pyc,, +scipy/sparse/linalg/tests/__pycache__/test_special_sparse_arrays.cpython-312.pyc,, +scipy/sparse/linalg/tests/propack_test_data.npz,sha256=v-NNmpI1Pgj0APODcTblU6jpHUQRhpE9ObWb-KYnu6M,600350 +scipy/sparse/linalg/tests/test_expm_multiply.py,sha256=0I8iDdswxJAgbDzbvRn9rKdWdPUTQJ2yNVaEjHr_MlI,15000 +scipy/sparse/linalg/tests/test_funm_multiply_krylov.py,sha256=Rs1i_fsV3rU4foz-cfXg1y2cBcOSztVo3wMYAQ4XULs,7289 +scipy/sparse/linalg/tests/test_interface.py,sha256=0_zkLOLDLRRDrHXkAifj8i2762BOOKA0HRi1jWwSE7g,21059 +scipy/sparse/linalg/tests/test_matfuncs.py,sha256=guVhj5UAU8Cz9NdlW4sgt12xKlQAljtMIe4As3Y5F5M,22021 +scipy/sparse/linalg/tests/test_norm.py,sha256=PRLnvUFHt7m6RjbBVhAh5npEy6biEUmfhSVMppxy7Mg,6504 +scipy/sparse/linalg/tests/test_onenormest.py,sha256=8fAgd2Fc5nRVf9sCB-AdhmTGIt4rxSCOIObBF7YJpDc,9300 +scipy/sparse/linalg/tests/test_propack.py,sha256=nIiJNNiC72dAHMWSvOqrH2AsbM5pp2RbRHa5pJGtHqc,7453 +scipy/sparse/linalg/tests/test_pydata_sparse.py,sha256=eawVssB3pRqxRmfzoHAVY7xvJU-Flo7JYsnoxhr76Mw,7302 +scipy/sparse/linalg/tests/test_special_sparse_arrays.py,sha256=Ql1D3db_Wv9A5Wkwbsqg4401slLeEy9-mQoeCMhLxas,13105 +scipy/sparse/sparsetools.py,sha256=pCcuyQYvIahrvr43V398XHyqwcGtWCPLFH6n1uSYmB8,516 +scipy/sparse/spfuncs.py,sha256=TWpfkZk3JErNajVFUH5B85d3r6UuSv0Rsx0lMtUSac0,508 +scipy/sparse/sputils.py,sha256=PsqT7RUmiO8ph5jG8GHYmPbacDQFljjc0SL7RMxweJU,508 +scipy/sparse/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/sparse/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_64bit.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_arithmetic1d.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_array_api.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_base.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_common1d.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_construct.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_coo.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_csc.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_csr.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_dok.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_extract.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_indexing1d.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_matrix_io.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_minmax1d.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_sparsetools.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_spfuncs.cpython-312.pyc,, +scipy/sparse/tests/__pycache__/test_sputils.cpython-312.pyc,, +scipy/sparse/tests/data/csc_py2.npz,sha256=usJ_Gj6x_dEC2uObfdYc6D6C8JY4jjROFChQcZhNAfo,846 +scipy/sparse/tests/data/csc_py3.npz,sha256=axuEMVxwd0F-cgUS0IalpiF8KHW4GNJ3BK6bcjfGnf4,851 +scipy/sparse/tests/test_64bit.py,sha256=HmeclVZ44TexUrlNkhB8PnYE46PFkiHxMv-h8K_BvwU,12975 +scipy/sparse/tests/test_arithmetic1d.py,sha256=4woi2qefAsFXR94Tjj_rlvOfdI-e_Vl6wGAFFw01HkI,11984 +scipy/sparse/tests/test_array_api.py,sha256=0Fkb7wZ1D7xZ0HK-FjAhjCFz406WCHWVSB_6vhmrMaI,14186 +scipy/sparse/tests/test_base.py,sha256=kqI4wxWt1a0o3gu3KEcyelW7pJnvq1FbrqkcFF1P0BU,224450 +scipy/sparse/tests/test_common1d.py,sha256=j_gxMwdHb-naLk9OZ9PYexfOJcqswmVtvCs7Vdy9sG4,15653 +scipy/sparse/tests/test_construct.py,sha256=Lw940_bqQb0yqIwr_XTftDYVlViP9rWNQKW6sHGgZxE,50069 +scipy/sparse/tests/test_coo.py,sha256=Fu3rUCREs1csbvdyL1NK6yen72kc_2iV2UnUonzQaps,48368 +scipy/sparse/tests/test_csc.py,sha256=qq-0sTMsKz6_xqPJX-eyYPxvXy0zCgSAP7W_8iXpu_4,4313 +scipy/sparse/tests/test_csr.py,sha256=4Wf_pjkWg1J6ybR_k-rAgsPrGklcea9XGefqdCY9JRA,8239 +scipy/sparse/tests/test_dok.py,sha256=MsDKnAvVsLgcnXOxnxBXYPZzEwK_qFBIOm8n-_YIDY4,6630 +scipy/sparse/tests/test_extract.py,sha256=4qUPrtCv9H7xd-c9Xs51seQCiIlK45n-9ZEVTDuPiv8,1685 +scipy/sparse/tests/test_indexing1d.py,sha256=g_VZO2iFmMz_Yq8AZILOKW3RdRFt6YS67rMLB4ZdT4I,21067 +scipy/sparse/tests/test_matrix_io.py,sha256=AQ3n2MZ7gOCtpiLJn7YdBCMy_tW5LD9jMxJDYqAFWSM,3867 +scipy/sparse/tests/test_minmax1d.py,sha256=UBeHcN4Pw_VAPXtgsyDev5pK3eXvisiiLjibeaiA8S0,4269 +scipy/sparse/tests/test_sparsetools.py,sha256=S5i2-h98qETawJxE_SRGWvhE4dtA8qMwQ9FplpAnAPg,10613 +scipy/sparse/tests/test_spfuncs.py,sha256=ECs34sgYYhTBWe4hIkx357obH2lLsnJWkh7TfacjThw,3258 +scipy/sparse/tests/test_sputils.py,sha256=RXx_xjrYf0xOUyd6AeeKy4UoeHS3kHxna_2ZXiHGYQs,16486 +scipy/spatial/__init__.py,sha256=ibMwKsyOAIbikHD1p19v7NaYSMYQZEU7kN6Hahc7sZs,3752 +scipy/spatial/__pycache__/__init__.cpython-312.pyc,, +scipy/spatial/__pycache__/_geometric_slerp.cpython-312.pyc,, +scipy/spatial/__pycache__/_kdtree.cpython-312.pyc,, +scipy/spatial/__pycache__/_plotutils.cpython-312.pyc,, +scipy/spatial/__pycache__/_procrustes.cpython-312.pyc,, +scipy/spatial/__pycache__/_spherical_voronoi.cpython-312.pyc,, +scipy/spatial/__pycache__/ckdtree.cpython-312.pyc,, +scipy/spatial/__pycache__/distance.cpython-312.pyc,, +scipy/spatial/__pycache__/kdtree.cpython-312.pyc,, +scipy/spatial/__pycache__/qhull.cpython-312.pyc,, +scipy/spatial/_ckdtree.cpython-312-darwin.so,sha256=J_0IBbTCJ511rgTWcrE9b70FqL-5D_5xpNZz1Xldy00,514688 +scipy/spatial/_distance_pybind.cpython-312-darwin.so,sha256=zzERrxHyGwABLVzWKtcqZMq1FM3jDVP2zsZS9caY6Uk,562536 +scipy/spatial/_distance_wrap.cpython-312-darwin.so,sha256=obOAMQUcG24wF8_mQK0h_AkiBwjcvq5ZlRclCZ1-_-A,104408 +scipy/spatial/_geometric_slerp.py,sha256=Ohc2AeoQWv8rgIJUIO9Il5U6XBj_L772G6hYLzQiPoM,8619 +scipy/spatial/_hausdorff.cpython-312-darwin.so,sha256=FjJVhW-Y8qtyQQ54BXVwZ63iQQTguKNoiHJUepyU3BY,96912 +scipy/spatial/_kdtree.py,sha256=I13ZRpOfKrAQjvPQoCiAGxjgEI1wQvyOOzsmMUkZkjg,33717 +scipy/spatial/_plotutils.py,sha256=pIBD6vxSfXl_tiFdm7fmuOoNHe57Zfr6KkeQqhgsTtA,7067 +scipy/spatial/_procrustes.py,sha256=qvhHPHt_OIKo-ge_k19S4VWqbP6ZgMXLVnNey0JxTb8,4427 +scipy/spatial/_qhull.cpython-312-darwin.so,sha256=vSJUCXnxbqoPWDo4uvYEl7A6PNcjvoWGm6sEbPvnUcY,720832 +scipy/spatial/_qhull.pyi,sha256=ofIDWfFY8M45z00uD1TmBDVTKyK2GJfoWIbdjmf4X0c,5954 +scipy/spatial/_spherical_voronoi.py,sha256=LWK3B_hM8JNeqBvoSnrDsufaYYlJDHtmQv3cOCl5T4Q,13518 +scipy/spatial/_voronoi.cpython-312-darwin.so,sha256=EOddSrzOtJPlwOzhKwl8feFFcs7jqLTxidWC6OU38G8,96576 +scipy/spatial/_voronoi.pyi,sha256=aAOiF4fvHz18hmuSjieKkRItssD443p2_w1ggXOIs1g,126 +scipy/spatial/ckdtree.py,sha256=0IssUT415ieBOJuvfZJxIra-TeYyd0KxDGLrXDZ_GGw,523 +scipy/spatial/distance.py,sha256=TXEaNg05WK-sG6zgr7ddKxbRxtwDRjakXHF8C4o8FuE,91845 +scipy/spatial/distance.pyi,sha256=T_hhLNuJ0TXEykdpgg6mxnQJYW0wggVMBJ5ZrTXbbx0,5007 +scipy/spatial/kdtree.py,sha256=ZYJL8A_WpLyEH29aFQGLbxd9ttFdGBgdglbgAfsvhz8,636 +scipy/spatial/qhull.py,sha256=aFE-KscuINt6QIhFC2dqhwFCYu3HSBkVXDH5exHH71s,622 +scipy/spatial/qhull_src/COPYING_QHULL.txt,sha256=EG1VyTH9aoSCLlNF2QAnPQWfHCcxDQJWfMsxPF0YxV0,1720 +scipy/spatial/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/spatial/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test__plotutils.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test__procrustes.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test_distance.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test_hausdorff.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test_kdtree.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test_qhull.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test_slerp.cpython-312.pyc,, +scipy/spatial/tests/__pycache__/test_spherical_voronoi.cpython-312.pyc,, +scipy/spatial/tests/data/cdist-X1.txt,sha256=ULnYAgX2_AwOVF-VE7XfnW5S0pzhx7UAoocxSnXMaWs,5750 +scipy/spatial/tests/data/cdist-X2.txt,sha256=_IJVjXsp3pvd8NNPNTLmVbHOrzl_RiEXz7cb86NfvZ4,11500 +scipy/spatial/tests/data/degenerate_pointset.npz,sha256=BIq8Hd2SS_LU0fIWAVVS7ZQx-emVRvvzgnaO2lh4gXU,22548 +scipy/spatial/tests/data/iris.txt,sha256=k19QSfkqhMmByqNMzwWDmM6wf5dt6whdGyfAyUO3AW0,15000 +scipy/spatial/tests/data/pdist-boolean-inp.txt,sha256=5Z9SMsXrtmzeUwJlVmGkrPDC_Km7nVpZIbBl7p3Hdc0,50000 +scipy/spatial/tests/data/pdist-chebyshev-ml-iris.txt,sha256=Yerj1wqIzcdyULlha-q02WBNGyS2Q5o2wAr0XVEkzis,178801 +scipy/spatial/tests/data/pdist-chebyshev-ml.txt,sha256=NEd2b-DONqUMV9f8gJ2yod17C_5fXGHHZ38PeFsXkyw,3041 +scipy/spatial/tests/data/pdist-cityblock-ml-iris.txt,sha256=UCWZJeMkMajbpjeG0FW60b0q-4r1geAyguNY6Chx5bM,178801 +scipy/spatial/tests/data/pdist-cityblock-ml.txt,sha256=8Iq7cF8oMJjpqd6qsDt_mKPQK0T8Ldot2P8C5rgbGIU,3041 +scipy/spatial/tests/data/pdist-correlation-ml-iris.txt,sha256=l2kEAu0Pm3OsFJsQtHf9Qdy5jnnoOu1v3MooBISnjP0,178801 +scipy/spatial/tests/data/pdist-correlation-ml.txt,sha256=S4GY3z-rf_BGuHmsnColMvR8KwYDyE9lqEbYT_a3Qag,3041 +scipy/spatial/tests/data/pdist-cosine-ml-iris.txt,sha256=hQzzoZrmw9OXAbqkxC8eTFXtJZrbFzMgcWMLbJlOv7U,178801 +scipy/spatial/tests/data/pdist-cosine-ml.txt,sha256=P92Tm6Ie8xg4jGSP7k7bmFRAP5MfxtVR_KacS73a6PI,3041 +scipy/spatial/tests/data/pdist-double-inp.txt,sha256=0Sx5yL8D8pyYDXTIBZAoTiSsRpG_eJz8uD2ttVrklhU,50000 +scipy/spatial/tests/data/pdist-euclidean-ml-iris.txt,sha256=3-UwBM7WZa4aCgmW_ZAdRSq8KYMq2gnkIUqU73Z0OLI,178801 +scipy/spatial/tests/data/pdist-euclidean-ml.txt,sha256=rkQA2-_d7uByKmw003lFXbXNDjHrUGBplZ8nB_TU5pk,3041 +scipy/spatial/tests/data/pdist-hamming-ml.txt,sha256=IAYroplsdz6n7PZ-vIMIJ4FjG9jC1OSxc3-oVJdSFDM,3041 +scipy/spatial/tests/data/pdist-jaccard-ml.txt,sha256=Zb42SoVEnlTj_N_ndnym3_d4RNZWeHm290hTtpp_zO8,3041 +scipy/spatial/tests/data/pdist-jensenshannon-ml-iris.txt,sha256=L7STTmlRX-z-YvksmiAxEe1UoTmDnQ_lnAjZH53Szp0,172738 +scipy/spatial/tests/data/pdist-jensenshannon-ml.txt,sha256=-sZUikGMWskONojs6fJIMX8VEWpviYYg4u1vipY6Bak,2818 +scipy/spatial/tests/data/pdist-minkowski-3.2-ml-iris.txt,sha256=N5L5CxRT5yf_vq6pFjorJ09Sr-RcnrAlH-_F3kEsyUU,178801 +scipy/spatial/tests/data/pdist-minkowski-3.2-ml.txt,sha256=DRgzqxRtvQVzFnpFAjNC9TDNgRtk2ZRkWPyAaeOx3q4,3041 +scipy/spatial/tests/data/pdist-minkowski-5.8-ml-iris.txt,sha256=jz7SGKU8GuJWASH2u428QL9c-G_-8nZvOFSOUlMdCyA,178801 +scipy/spatial/tests/data/pdist-seuclidean-ml-iris.txt,sha256=37H01o6GibccR_hKIwwbWxGX0Tuxnb-4Qc6rmDxwwUI,178801 +scipy/spatial/tests/data/pdist-seuclidean-ml.txt,sha256=YmcI7LZ6i-Wg1wjAkLVX7fmxzCj621Pc5itO3PvCm_k,3041 +scipy/spatial/tests/data/pdist-spearman-ml.txt,sha256=IrtJmDQliv4lDZ_UUjkZNso3EZyu7pMACxMB-rvHUj0,3041 +scipy/spatial/tests/data/random-bool-data.txt,sha256=MHAQdE4hPVzgu-csVVbm1DNJ80dP7XthJ1kb2In8ImM,6000 +scipy/spatial/tests/data/random-double-data.txt,sha256=GA8hYrHsTBeS864GJf0X6JRTvGlbpM8P8sJairmfnBU,75000 +scipy/spatial/tests/data/random-int-data.txt,sha256=xTUbCgoT4X8nll3kXu7S9lv-eJzZtwewwm5lFepxkdQ,10266 +scipy/spatial/tests/data/random-uint-data.txt,sha256=8IPpXhwglxzinL5PcK-PEqleZRlNKdx3zCVMoDklyrY,8711 +scipy/spatial/tests/data/selfdual-4d-polytope.txt,sha256=rkVhIL1mupGuqDrw1a5QFaODzZkdoaLMbGI_DbLLTzM,480 +scipy/spatial/tests/test__plotutils.py,sha256=fASbg0i7iLiJIEj5vIkiDuTq3wU0z3mKJY019kzKrFk,3814 +scipy/spatial/tests/test__procrustes.py,sha256=wmmnUHRdw_oID0YLi404IEWPH6vEGhvHXSeGPY_idHo,4974 +scipy/spatial/tests/test_distance.py,sha256=TKpl3Yi3ylIwx4IM4SLFoDOv7MacSYxZhgaUbuEWqww,84726 +scipy/spatial/tests/test_hausdorff.py,sha256=XcDEzwFuOR9BaLegIj-DPp5GrAi_RsvcW8oGqJf0xkg,8217 +scipy/spatial/tests/test_kdtree.py,sha256=dlSaXMAIXFS73SMM2Vl9UPEe8Vtbyyiz69zmdb8ddYA,49340 +scipy/spatial/tests/test_qhull.py,sha256=sYXP8kiFuTTUkl3cV6Brl28VPJixLAphUnVnCwikuRc,50121 +scipy/spatial/tests/test_slerp.py,sha256=KMmqbcefISrTnzWAmY3IBDaJw13fnRXHddLsUKAn5Tk,18455 +scipy/spatial/tests/test_spherical_voronoi.py,sha256=YCVSpO7-RrmKaAivwrLh5rZJ6CTTNKuIJ9iyhXsi178,14500 +scipy/spatial/transform/__init__.py,sha256=XqVBg4ekbA48c9r9A9xmdIkchyxy-nyLEYwGq71IXqQ,826 +scipy/spatial/transform/__pycache__/__init__.cpython-312.pyc,, +scipy/spatial/transform/__pycache__/_rigid_transform.cpython-312.pyc,, +scipy/spatial/transform/__pycache__/_rigid_transform_xp.cpython-312.pyc,, +scipy/spatial/transform/__pycache__/_rotation.cpython-312.pyc,, +scipy/spatial/transform/__pycache__/_rotation_groups.cpython-312.pyc,, +scipy/spatial/transform/__pycache__/_rotation_spline.cpython-312.pyc,, +scipy/spatial/transform/__pycache__/_rotation_xp.cpython-312.pyc,, +scipy/spatial/transform/__pycache__/rotation.cpython-312.pyc,, +scipy/spatial/transform/_rigid_transform.py,sha256=VgiBvCvGkgic2j8sli1CXnXiBsMrThmqTZ1bUWLxOqI,71755 +scipy/spatial/transform/_rigid_transform_cy.cpython-312-darwin.so,sha256=9X0X-2Dgy5__4BWo2AOtt-H2dt94QXmasJTUv0U2dhk,217832 +scipy/spatial/transform/_rigid_transform_xp.py,sha256=MUVmT_YCakUBPkhlLSLf_xASXAZdwcJUqttla31clZ4,16512 +scipy/spatial/transform/_rotation.py,sha256=zaL7DZPB16EDkV8stR3jR8YSxf6IUw6PnSys940BY1o,107354 +scipy/spatial/transform/_rotation_cy.cpython-312-darwin.so,sha256=9J5ybK8_34h4hO8h2IOZcyttfJZeeOUOZFEP4lRhhyg,408288 +scipy/spatial/transform/_rotation_groups.py,sha256=XS-9K6xYnnwWywMMYMVznBYc1-0DPhADHQp_FIT3_f8,4422 +scipy/spatial/transform/_rotation_spline.py,sha256=psUsaAMZZXk5g3Rgb7RSOIchYCFQbRGRB6suKbfU6KU,14244 +scipy/spatial/transform/_rotation_xp.py,sha256=rRlg8Ts9qHEBJDcIlvpt9UXpJ60wS7phYvRj84CDmLk,44173 +scipy/spatial/transform/rotation.py,sha256=co5Bpny89EfCywilEeeLDvJPESBLrSXTCCJqRlfdYzg,556 +scipy/spatial/transform/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/spatial/transform/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/spatial/transform/tests/__pycache__/test_rigid_transform.cpython-312.pyc,, +scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-312.pyc,, +scipy/spatial/transform/tests/__pycache__/test_rotation_groups.cpython-312.pyc,, +scipy/spatial/transform/tests/__pycache__/test_rotation_spline.cpython-312.pyc,, +scipy/spatial/transform/tests/test_rigid_transform.py,sha256=bjG2EfhTmDfQeAug7KB9ZCrGnu2vR2egRuVbaZ1Z_sw,59088 +scipy/spatial/transform/tests/test_rotation.py,sha256=Ocq_0-Rf4Ece0ieyOeIeVblc84IT8nXuTKsm5WzHVcg,115498 +scipy/spatial/transform/tests/test_rotation_groups.py,sha256=qnG7kfzs5jDe0_nYxVycziOED3zSABZhxoInxNNCfr0,5552 +scipy/spatial/transform/tests/test_rotation_spline.py,sha256=9rcVmUBVFmRh9EbxkVwBFsT9LByg5H7-3YwaCs48sH4,5886 +scipy/special/__init__.pxd,sha256=l9Y21wnx5fZLvrxCeCMUWQvBI5gHx7LBhimDWptxke8,42 +scipy/special/__init__.py,sha256=McdMzKj59tjc4ZYNULnffrOsqy5qX2kyepgjuSIA_lY,31817 +scipy/special/__pycache__/__init__.cpython-312.pyc,, +scipy/special/__pycache__/_add_newdocs.cpython-312.pyc,, +scipy/special/__pycache__/_basic.cpython-312.pyc,, +scipy/special/__pycache__/_ellip_harm.cpython-312.pyc,, +scipy/special/__pycache__/_input_validation.cpython-312.pyc,, +scipy/special/__pycache__/_lambertw.cpython-312.pyc,, +scipy/special/__pycache__/_logsumexp.cpython-312.pyc,, +scipy/special/__pycache__/_mptestutils.cpython-312.pyc,, +scipy/special/__pycache__/_multiufuncs.cpython-312.pyc,, +scipy/special/__pycache__/_orthogonal.cpython-312.pyc,, +scipy/special/__pycache__/_sf_error.cpython-312.pyc,, +scipy/special/__pycache__/_spfun_stats.cpython-312.pyc,, +scipy/special/__pycache__/_spherical_bessel.cpython-312.pyc,, +scipy/special/__pycache__/_support_alternative_backends.cpython-312.pyc,, +scipy/special/__pycache__/_testutils.cpython-312.pyc,, +scipy/special/__pycache__/add_newdocs.cpython-312.pyc,, +scipy/special/__pycache__/basic.cpython-312.pyc,, +scipy/special/__pycache__/orthogonal.cpython-312.pyc,, +scipy/special/__pycache__/sf_error.cpython-312.pyc,, +scipy/special/__pycache__/specfun.cpython-312.pyc,, +scipy/special/__pycache__/spfun_stats.cpython-312.pyc,, +scipy/special/_add_newdocs.py,sha256=n7TDHaYpYHp4AQjgZbGojnVT7p2ft3zSNc6Q0jMY_aY,240843 +scipy/special/_basic.py,sha256=juGtgyoRx-zgKMH00zFbov57-1ZQdZDH01bR5GmWJV8,105294 +scipy/special/_comb.cpython-312-darwin.so,sha256=VzH6-NPBBbVUGH8LnfBTcMvFqJSCnOKWyDqxCCbkUrA,77336 +scipy/special/_ellip_harm.py,sha256=Uc2sUQCDhYkkJg9a4nZozcTDTSjy_6ToTCQaJdIsMPc,5388 +scipy/special/_ellip_harm_2.cpython-312-darwin.so,sha256=JwpyVkRirUv3zPNMVTg059_kGUs55HavuNDi5vb94Bc,113088 +scipy/special/_gufuncs.cpython-312-darwin.so,sha256=CdchF2DaB5iL_nwzNWMbM4D0BcWTkcs4fn4A3oeyI3U,627808 +scipy/special/_input_validation.py,sha256=ZEwg_sZaesaqzaVA_btZQAi_uPXtIViL_u3Zms6UnyQ,474 +scipy/special/_lambertw.py,sha256=-oSEnHFQWZiUZXMamxPWjfntWq5tt0rzHmI13DxGHBY,3962 +scipy/special/_logsumexp.py,sha256=OVY91WVdm-0fL-kaLYTYTp3agX-x6kuoaZQQwecO4-E,14432 +scipy/special/_mptestutils.py,sha256=ocy_wBXqHGIg311jfjATEA8O29ICl4qPnvTgsmTm5qg,14441 +scipy/special/_multiufuncs.py,sha256=ZHubzJTgWfWre_BZCMiac4T11Xe999B7Q8Dv3mkSJw0,19402 +scipy/special/_orthogonal.py,sha256=YgvyTzMOGbf4qu-yvwduOg404uRNdMl7NkIXDpg_FDs,74770 +scipy/special/_orthogonal.pyi,sha256=85-bMpsnhRc-GeDoh02h6vDAiVSMU0tOOF0cpv1xIXY,8265 +scipy/special/_precompute/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/special/_precompute/__pycache__/__init__.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/cosine_cdf.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/expn_asy.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/gammainc_asy.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/gammainc_data.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/hyp2f1_data.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/lambertw.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/loggamma.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/struve_convergence.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/utils.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/wright_bessel.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/wrightomega.cpython-312.pyc,, +scipy/special/_precompute/__pycache__/zetac.cpython-312.pyc,, +scipy/special/_precompute/cosine_cdf.py,sha256=ZGSeDDpLRsapyx2GbIrqqYR98fvaEQrLn7IE-fuodhE,354 +scipy/special/_precompute/expn_asy.py,sha256=JAz0hY1gBJu3Q_dvscQrSJdgKuwpjqFZVwz-sOQQ21w,1265 +scipy/special/_precompute/gammainc_asy.py,sha256=P5OFRcPkkpjGQeYCaMZ8SFSUmZG_CjrEHv8OLwgcGFc,2502 +scipy/special/_precompute/gammainc_data.py,sha256=jogxBuXLr3uEpMBvpqScDz5TzEEalksH8f-cRGzasck,4077 +scipy/special/_precompute/hyp2f1_data.py,sha256=STSBybQ2pCAu6sh8c9tiHsoDOgnisnSp4tkP2cK4MuI,14707 +scipy/special/_precompute/lambertw.py,sha256=7f4F3ivouVNZwuvVX8TAi2lPB7LirPS8IfN5lEw9zI0,1961 +scipy/special/_precompute/loggamma.py,sha256=iq7ZBrUmk8pXYZwO_wINI4u8ENsLbL9VUShGjGO0Pt0,1094 +scipy/special/_precompute/struve_convergence.py,sha256=z7R0Q5_Ye-EqLI9g-yARdl_j5FooofXMRXPLVrIFJQQ,3624 +scipy/special/_precompute/utils.py,sha256=JXJuI07Jlm4bDHJFVtj0jHq05p-V1ofeXZB16Y05kzI,887 +scipy/special/_precompute/wright_bessel.py,sha256=7z2W3spGANZO31r_xauMA6hIQ0eseRlXx-zJW6du5tU,12868 +scipy/special/_precompute/wright_bessel_data.py,sha256=f1id2Gk5TPyUmSt-Evhoq2_hfRgLUU7Qu_mELKtaXGg,5647 +scipy/special/_precompute/wrightomega.py,sha256=YpmLwtGJ4qazMDY0RXjhnQiuRAISI-Pr9MwKc7pZlhc,955 +scipy/special/_precompute/zetac.py,sha256=LmhJP7JFg7XktHvfm-DgzuiWZFtVdpvYzzLOB1ePG1Q,591 +scipy/special/_sf_error.py,sha256=q_Rbfkws1ttgTQKYLt6zFTdY6DFX2HajJe_lXiNWC0c,375 +scipy/special/_specfun.cpython-312-darwin.so,sha256=8uNdBsDqzn5Pa2DLQJ6NSyU9TJBt7H8MgUDnNJONtek,184176 +scipy/special/_special_ufuncs.cpython-312-darwin.so,sha256=02viwqrKdCAz1jqF21E0_GOdOrCm4rqYSK8qZSUNhmw,1130872 +scipy/special/_spfun_stats.py,sha256=f3cJO5OxyJVaC6_XE2cCKLVI2tQgOMBW8glk6OQRdr4,3870 +scipy/special/_spherical_bessel.py,sha256=Qh8ihvfYZfcyRuk54tGR77o78gkwhVHWKgG2EARuH5g,12457 +scipy/special/_support_alternative_backends.py,sha256=l2gLwt9dRHuvb9Kr60NtznC05Ver5-q2gRFdjRnhM9w,28223 +scipy/special/_test_internal.cpython-312-darwin.so,sha256=usEIk3ZZmxmKyqWv6rhnh3A-spI3aMUnU6_YfEpEVp0,96744 +scipy/special/_test_internal.pyi,sha256=cye6-VI7Jxvb4JDfa1R_f7slEDjYUUfM4edFZ_e0XiE,394 +scipy/special/_testutils.py,sha256=cvlrivMgy18oJqQKzEe3AdZbm4nRTACkC9kqg7wwgqw,11971 +scipy/special/_ufuncs.cpython-312-darwin.so,sha256=X_llzjtWD6fi9pAbZl5CuWVUAkpbMqJTx_f1vJXCE08,702944 +scipy/special/_ufuncs.pyi,sha256=ESwRdl7HOh9tTOlFp6zcqNQUDumfIPj1usUx0H773nY,8883 +scipy/special/_ufuncs.pyx,sha256=u3xZtu4a6r2f8AXa3UpauX1qWbv138lsHO4SVVM1L00,562124 +scipy/special/_ufuncs_cxx.cpython-312-darwin.so,sha256=UWrcpOcZkfCCu6uSefdiVKMEgGMO6ThuXCm78nKDy-o,1353776 +scipy/special/_ufuncs_cxx.pxd,sha256=iHoXu3i12I99u2UaqRJkhcjW-c0EK-5qOzlAd-xuGHA,5957 +scipy/special/_ufuncs_cxx.pyx,sha256=5ZPGyT93wtXSX6ligrZHgJTxfUjkSpU4s4Xh4k-BUVY,33231 +scipy/special/_ufuncs_cxx_defs.h,sha256=DpJ1C1qnXJH_qrhG_Rtpxw7lOQjCDzBsWs_skh6p22s,10296 +scipy/special/_ufuncs_defs.h,sha256=RpPf8Ex-DjoBTh9YGTbkUmQHzwOTkFnvT3naQzMOLYA,2829 +scipy/special/add_newdocs.py,sha256=Wnd-5R0wQAVxSolD4QY2CamTSbe1k48Aie3XaBWRKKc,436 +scipy/special/basic.py,sha256=_XJm4Y1lArjSQY14bZ93Deep6loN-kYMAJvGSf5ezFk,1546 +scipy/special/cython_special.cpython-312-darwin.so,sha256=aWgZJwul_5czwPir-JR01p87ASqlz9bMKF2iMglndyc,1696200 +scipy/special/cython_special.pxd,sha256=UrTdQIGs-2O6xKylRVk8vyvLM5ErxZh0ENhRc1kJoKw,16521 +scipy/special/cython_special.pyi,sha256=BQVUCzV8lCylnmLCtnN0Yz_ttlqyzcLc-BZx2KPXPzM,58 +scipy/special/orthogonal.py,sha256=aLzv7PzJgsdLpyTrV6Cu-rpHNHWlUAEqOImiW4fuzuE,1724 +scipy/special/sf_error.py,sha256=wOZqzX7iipkH39hOHqBlkmretJRbYy-K7PsnZPyaJFU,573 +scipy/special/specfun.py,sha256=vEn4jiJMvKiCXWiw_DdUqmyFbY6O_iYCFBTPaa6cLsg,552 +scipy/special/spfun_stats.py,sha256=ESJXGUwH7iijUk6aXZQVI1pnaWiVZ6_l0hVpC4bBSIw,535 +scipy/special/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/special/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_basic.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_bdtr.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_boost_ufuncs.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_boxcox.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_cdflib.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_cephes_intp_cast.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_cosine_distr.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_cython_special.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_data.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_dd.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_digamma.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_ellip_harm.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_erfinv.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_exponential_integrals.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_extending.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_faddeeva.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_gamma.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_gammainc.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_gen_harmonic.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_hyp2f1.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_hypergeometric.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_iv_ratio.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_kolmogorov.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_lambertw.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_legendre.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_log1mexp.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_loggamma.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_logit.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_logsumexp.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_mpmath.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_nan_inputs.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_ndtr.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_ndtri_exp.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_orthogonal.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_orthogonal_eval.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_owens_t.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_pcf.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_pdtr.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_powm1.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_precompute_expn_asy.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_precompute_gammainc.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_precompute_utils.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_round.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_sf_error.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_sici.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_specfun.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_spence.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_spfun_stats.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_sph_harm.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_spherical_bessel.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_support_alternative_backends.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_trig.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_ufunc_signatures.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_wright_bessel.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_wrightomega.cpython-312.pyc,, +scipy/special/tests/__pycache__/test_zeta.cpython-312.pyc,, +scipy/special/tests/_cython_examples/extending.pyx,sha256=0ISFhXHFnwuWXg5m9VIYdWGjP_W7hxUE8SwFNkvAM_s,292 +scipy/special/tests/_cython_examples/meson.build,sha256=7WUABNMPYujt2fmD4YNKqihhwaT9AaOs942x7ah0MWw,810 +scipy/special/tests/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/special/tests/data/__pycache__/__init__.cpython-312.pyc,, +scipy/special/tests/data/boost.npz,sha256=V7XCtn7gHHQVNqrmrZ-PEoEGt_3_FSr889j3dLBkWEQ,1270643 +scipy/special/tests/data/gsl.npz,sha256=y_Gv3SeZmAanECeZEKLrL59_VZAzx-y3lt6qEMRP6zE,51433 +scipy/special/tests/data/local.npz,sha256=bCnljOgnCE-E258bupYEWmHOafHT6j18gop5wTPPiPI,203438 +scipy/special/tests/test_basic.py,sha256=W5UN7iHiTcw4wmtG758btqIMqYwR34rPgv5fYkH_3H4,200103 +scipy/special/tests/test_bdtr.py,sha256=YrexKxguZwJVkfOxDMfsVqtSkz-N6fkdifoO6qT3ddY,3289 +scipy/special/tests/test_boost_ufuncs.py,sha256=4cEmHpVVl5KQg0qZywhbcH5uYmsvZcnQT9RotJXhnGI,3023 +scipy/special/tests/test_boxcox.py,sha256=kuGjRgfLInydtbFRm-kvPBy2cJGsHFBmX14mrinu87Q,3263 +scipy/special/tests/test_cdflib.py,sha256=8LiinjJcp4t8fnf7P0Nii3177bP6QuA9Yo20h6ddkcg,32361 +scipy/special/tests/test_cdft_asymptotic.py,sha256=aj-Hawo0dShzdBRz2AfqGl6UJr9odNMcGISYTa-rpJw,1619 +scipy/special/tests/test_cephes_intp_cast.py,sha256=yllVoacRDDS_mH7E_pvDux_Jpf7_Fdt3F9Jsgj3_BaY,1129 +scipy/special/tests/test_cosine_distr.py,sha256=zL7aWLisIEy1oNKjcynqncgsCxcPKvPb9Odr-J5Xa1M,2690 +scipy/special/tests/test_cython_special.py,sha256=6Sdf1U9KGtM6T7aMJGfmtITlLYcFM7Szoq8NB1uJ5lA,19046 +scipy/special/tests/test_data.py,sha256=XQBpfKQiHwAkr_SRYumMaOEYgew7ptKUlxm_NWCuR7c,28349 +scipy/special/tests/test_dd.py,sha256=I7xSqxTD-GYaO0ol25ZjsGZgqCVt13vbcQlUN7teeG4,1564 +scipy/special/tests/test_digamma.py,sha256=Bm7Hh_aETx6MTN3Wu7Sijy4rYGR_1haNGsi3xfzrAKM,1382 +scipy/special/tests/test_ellip_harm.py,sha256=tBPBdZy7153UvgL4Y-AOUkG6pflmj9uNKAwG9-GG7GM,9969 +scipy/special/tests/test_erfinv.py,sha256=fzdEHd6MxfSyzQDO93qndXukG2jWj-XNY2X4BJRIdBI,3059 +scipy/special/tests/test_exponential_integrals.py,sha256=wMPTu9dK32cbtJWOouF1Dw2e0hjZSNxYtcQbVaWlDTk,3863 +scipy/special/tests/test_extending.py,sha256=7Q8NRxp-QBASTY9y0b8xOcAJmrMKhLaruE_MX7nmJ0M,1184 +scipy/special/tests/test_faddeeva.py,sha256=YLY3Ylp4u_8zxTGxOb5kxNfXXEW0ld_GP2ceOR2ev_Y,2568 +scipy/special/tests/test_gamma.py,sha256=hb-ZlA2ZNz6gUGvVtMBgXFl_w30HPmthuUEAmNcz0sw,258 +scipy/special/tests/test_gammainc.py,sha256=QdOylOmN2CY5cFw0BihCP-05x_d8q0Pitb7-a4DgSic,4441 +scipy/special/tests/test_gen_harmonic.py,sha256=ojbzW6yAV3HOhQhU6mubHduDVlXpkPq2pkdolip1Vsw,3110 +scipy/special/tests/test_hyp2f1.py,sha256=lvERrDZuLSA7tzVo8rzFuHSNCijGjBuDCDTktJVAcKE,92261 +scipy/special/tests/test_hypergeometric.py,sha256=DUDe1YvIXt4IocGlJuqDO5swZ-QOyR2Etj2rwkF-NqQ,9996 +scipy/special/tests/test_iv_ratio.py,sha256=6Wa4PDSboT1srHiGUOR78_cTvStWgct31cGkLFvDT5A,10108 +scipy/special/tests/test_kolmogorov.py,sha256=-Ika_ORUwxDuaCXATLb489T9lDWoPkJR7r7PNRAE0mE,19280 +scipy/special/tests/test_lambertw.py,sha256=KpUZJA3TDejEfeZ5uS2n6eg3R2V0GhGQj30Pl1UxnOk,4572 +scipy/special/tests/test_legendre.py,sha256=Ffh1KkDrAo4_A5rH-xO77Pty2cHiiKnLM1B1b302Rio,53044 +scipy/special/tests/test_log1mexp.py,sha256=Spw_PfKgjer3aNUEnYiZUaC-dpDwg0cqwsfFxNgYG1U,3142 +scipy/special/tests/test_loggamma.py,sha256=x6kuJf-bEnn5ECdkDSgvk3An_A-9UxVsZpqa49IwAq8,1992 +scipy/special/tests/test_logit.py,sha256=uCc4Cb7SrUAx01hMyryJIhfh5k0zEozmYhHHky32nwM,6470 +scipy/special/tests/test_logsumexp.py,sha256=jJ3Tb6XcS1VY82ItbuhdRaNRbhJzpKlwx_tp4KS1iTo,19333 +scipy/special/tests/test_mpmath.py,sha256=6wRvhLtr9k-Hqob0lCZtbjIPJ6JWglqYLLzfHCj476M,69311 +scipy/special/tests/test_nan_inputs.py,sha256=D6cWbrzU3Y_9JoqE7fcK43xZCQ3Roe-QxNeL6C6uEiQ,1956 +scipy/special/tests/test_ndtr.py,sha256=-UMxTIi4CaaLoJ5-SGW9THChPIM3e1_fTY0L877ioNA,2680 +scipy/special/tests/test_ndtri_exp.py,sha256=13eabgdbfcL37RReiUH7g9amT9XMsTLOfwxFJXR_2Ww,3708 +scipy/special/tests/test_orthogonal.py,sha256=4T2s9XGHC0JoPMm7LpWZhPwbZRhAtJmThov5RoKJyyc,32878 +scipy/special/tests/test_orthogonal_eval.py,sha256=qXkJZEAeXGhJw48PcnZ8ZS4-mWQG-MIuSVbvYoX7uvI,9576 +scipy/special/tests/test_owens_t.py,sha256=zRbiKje7KrYJ25f1ZuIBfiFSyNtK_bnkIW7dRETIqME,1792 +scipy/special/tests/test_pcf.py,sha256=RNjEWZGFS99DOGZkkPJ8HNqLULko8UkX0nEWFYX26NE,664 +scipy/special/tests/test_pdtr.py,sha256=jCxVZ7anMlXL9_duT1RdBbLqTATYBCRwM-2kA_wepKU,1366 +scipy/special/tests/test_powm1.py,sha256=9hZeiQVKqV63J5oguYXv_vqolpnJX2XRO1JN0ouLWAM,2276 +scipy/special/tests/test_precompute_expn_asy.py,sha256=bCQikPkWbxVUeimvo79ToVPgwaudzxGC7Av-hPBgIU4,583 +scipy/special/tests/test_precompute_gammainc.py,sha256=Kxlp5iX7R4iog69KygYf0gjrtuTXkUJZPvGe0nnhL6M,4620 +scipy/special/tests/test_precompute_utils.py,sha256=MOvdbLbzjN5Z1JQQgtIyjwjuIMPX4s2bTc_kxaX67wc,1165 +scipy/special/tests/test_round.py,sha256=Zv32kFQrDdOPawfGDeZo1PfBG4UsOyKfd3zjbCWLii0,511 +scipy/special/tests/test_sf_error.py,sha256=7-a7XxGX0sz1uZWrvkN5Ysakq8vDQh3Ms8LB7zvp5GU,4562 +scipy/special/tests/test_sici.py,sha256=w4anBf8fiq2fmkwMSz3MX0uy35NLXVqfuW3Fwt2Nqek,1227 +scipy/special/tests/test_specfun.py,sha256=q2JYEnqmUq78rO8no9hXQZ3fc3RuxPrRCcpsLruovDg,1687 +scipy/special/tests/test_spence.py,sha256=fChPw7xncNCTPMUGb0C8BC-lDKHWoEXSz8Rb4Wv8vNo,1099 +scipy/special/tests/test_spfun_stats.py,sha256=U3uHlpl52ApcHyfMSTrKr_va7MeYX44VrEm6fwjDfp4,2029 +scipy/special/tests/test_sph_harm.py,sha256=CG_mi1SuQspgkau2UXoYEjavScUShAWtVOcovGlKtDc,1780 +scipy/special/tests/test_spherical_bessel.py,sha256=U60jQUKB2twu2mMZhkhXBz6JjkOuy4G9WWHZwwg9GX4,15195 +scipy/special/tests/test_support_alternative_backends.py,sha256=ioB0bTH03xX0LXlOPi6TASwIp-LlcrP5sAStaO7q2mk,15680 +scipy/special/tests/test_trig.py,sha256=CKZr--vh4fwiW-ycJf5wODosKYhCpkNqvHfTArz-2K8,2400 +scipy/special/tests/test_ufunc_signatures.py,sha256=gU0cC-BdCbsIzXsO2I5OsX-nj6qfX9ZylSGlerXqq3E,1977 +scipy/special/tests/test_wright_bessel.py,sha256=6WHuXB97skPSsoMgXwRlO7bHydFLnl9iDfctEpZE0uE,7694 +scipy/special/tests/test_wrightomega.py,sha256=BW8TS_CuDjR7exA4l6ADnKhXwgFWUYaN1UIopMBJUZY,3560 +scipy/special/tests/test_zeta.py,sha256=IEPRUdSX5kerDYPmhLWYkYixmUg1ErqHSprQpfkZTP0,11549 +scipy/stats/__init__.py,sha256=A3BIn-F9daAkO8DvrzTL30BcnKeYQYtq7COITEafG3M,18839 +scipy/stats/__pycache__/__init__.cpython-312.pyc,, +scipy/stats/__pycache__/_axis_nan_policy.cpython-312.pyc,, +scipy/stats/__pycache__/_binned_statistic.cpython-312.pyc,, +scipy/stats/__pycache__/_binomtest.cpython-312.pyc,, +scipy/stats/__pycache__/_bws_test.cpython-312.pyc,, +scipy/stats/__pycache__/_censored_data.cpython-312.pyc,, +scipy/stats/__pycache__/_common.cpython-312.pyc,, +scipy/stats/__pycache__/_constants.cpython-312.pyc,, +scipy/stats/__pycache__/_continued_fraction.cpython-312.pyc,, +scipy/stats/__pycache__/_continuous_distns.cpython-312.pyc,, +scipy/stats/__pycache__/_correlation.cpython-312.pyc,, +scipy/stats/__pycache__/_covariance.cpython-312.pyc,, +scipy/stats/__pycache__/_crosstab.cpython-312.pyc,, +scipy/stats/__pycache__/_discrete_distns.cpython-312.pyc,, +scipy/stats/__pycache__/_distn_infrastructure.cpython-312.pyc,, +scipy/stats/__pycache__/_distr_params.cpython-312.pyc,, +scipy/stats/__pycache__/_distribution_infrastructure.cpython-312.pyc,, +scipy/stats/__pycache__/_entropy.cpython-312.pyc,, +scipy/stats/__pycache__/_finite_differences.cpython-312.pyc,, +scipy/stats/__pycache__/_fit.cpython-312.pyc,, +scipy/stats/__pycache__/_hypotests.cpython-312.pyc,, +scipy/stats/__pycache__/_kde.cpython-312.pyc,, +scipy/stats/__pycache__/_ksstats.cpython-312.pyc,, +scipy/stats/__pycache__/_mannwhitneyu.cpython-312.pyc,, +scipy/stats/__pycache__/_mgc.cpython-312.pyc,, +scipy/stats/__pycache__/_morestats.cpython-312.pyc,, +scipy/stats/__pycache__/_mstats_basic.cpython-312.pyc,, +scipy/stats/__pycache__/_mstats_extras.cpython-312.pyc,, +scipy/stats/__pycache__/_multicomp.cpython-312.pyc,, +scipy/stats/__pycache__/_multivariate.cpython-312.pyc,, +scipy/stats/__pycache__/_new_distributions.cpython-312.pyc,, +scipy/stats/__pycache__/_odds_ratio.cpython-312.pyc,, +scipy/stats/__pycache__/_page_trend_test.cpython-312.pyc,, +scipy/stats/__pycache__/_probability_distribution.cpython-312.pyc,, +scipy/stats/__pycache__/_qmc.cpython-312.pyc,, +scipy/stats/__pycache__/_qmvnt.cpython-312.pyc,, +scipy/stats/__pycache__/_quantile.cpython-312.pyc,, +scipy/stats/__pycache__/_relative_risk.cpython-312.pyc,, +scipy/stats/__pycache__/_resampling.cpython-312.pyc,, +scipy/stats/__pycache__/_result_classes.cpython-312.pyc,, +scipy/stats/__pycache__/_sampling.cpython-312.pyc,, +scipy/stats/__pycache__/_sensitivity_analysis.cpython-312.pyc,, +scipy/stats/__pycache__/_stats_mstats_common.cpython-312.pyc,, +scipy/stats/__pycache__/_stats_py.cpython-312.pyc,, +scipy/stats/__pycache__/_survival.cpython-312.pyc,, +scipy/stats/__pycache__/_tukeylambda_stats.cpython-312.pyc,, +scipy/stats/__pycache__/_variation.cpython-312.pyc,, +scipy/stats/__pycache__/_warnings_errors.cpython-312.pyc,, +scipy/stats/__pycache__/_wilcoxon.cpython-312.pyc,, +scipy/stats/__pycache__/biasedurn.cpython-312.pyc,, +scipy/stats/__pycache__/contingency.cpython-312.pyc,, +scipy/stats/__pycache__/distributions.cpython-312.pyc,, +scipy/stats/__pycache__/kde.cpython-312.pyc,, +scipy/stats/__pycache__/morestats.cpython-312.pyc,, +scipy/stats/__pycache__/mstats.cpython-312.pyc,, +scipy/stats/__pycache__/mstats_basic.cpython-312.pyc,, +scipy/stats/__pycache__/mstats_extras.cpython-312.pyc,, +scipy/stats/__pycache__/mvn.cpython-312.pyc,, +scipy/stats/__pycache__/qmc.cpython-312.pyc,, +scipy/stats/__pycache__/sampling.cpython-312.pyc,, +scipy/stats/__pycache__/stats.cpython-312.pyc,, +scipy/stats/_ansari_swilk_statistics.cpython-312-darwin.so,sha256=yZMClQ17sFAhM-BTvRT3tnyf85_KxIgdEUAgoi7jflg,113776 +scipy/stats/_axis_nan_policy.py,sha256=-b0LKDi3lua8FRn8qHHm12rBtzCeJfsqttPPGDbbgQ8,32644 +scipy/stats/_biasedurn.cpython-312-darwin.so,sha256=eWs8flkDY-coOwyyRGQPv2vgOkB6mSCG-OlMVAxs7v8,157232 +scipy/stats/_biasedurn.pxd,sha256=bQC6xG4RH1E5h2jCKXRMADfgGctiO5TgNlJegKrR7DY,1046 +scipy/stats/_binned_statistic.py,sha256=Hnann2khDIGmvqIipGw_0zz4Jo10Pd9peIVtZvrACYM,32846 +scipy/stats/_binomtest.py,sha256=WlN1N8IvuaTOCJ5bXFrMeokPBVOkOE-bKMmV6U9UbBM,13199 +scipy/stats/_bws_test.py,sha256=2yfqpx9tlbotjTBJsBd4qOAK3fphUDN3J6Oe1AS-f-g,7143 +scipy/stats/_censored_data.py,sha256=Ts7GSYYti2z-8yoOJTedj6aCLnGhugLlDRdxZc4rPxs,18306 +scipy/stats/_common.py,sha256=4RqXT04Knp1CoOJuSBV6Uy_XmcmtVr0bImAbSk_VHlQ,172 +scipy/stats/_constants.py,sha256=mBeJgvWcDZBmPFStDNEjlzeZY3aMDMCHWoj7dCmgugQ,1002 +scipy/stats/_continued_fraction.py,sha256=2WyLuQWsx9aIHkYvTE4_VlepAfSKG4otiu_Y5wYbzKA,15508 +scipy/stats/_continuous_distns.py,sha256=i98XiARqobuq2SGESUzM_MkSLMH9eS4neD6CIArC2kQ,409353 +scipy/stats/_correlation.py,sha256=MBZwMk0Gti8LU4oxPAE1umY7_A8NwLu9DdzVFApRCuk,15418 +scipy/stats/_covariance.py,sha256=N5skfDbcnWPjTE2RwBoZGJUyFieM2q8y9NHhXBMqHlo,22913 +scipy/stats/_crosstab.py,sha256=djdU7xCQ-513VlxFEOvLN8oaY4QyUPHDJHWlilhyEVA,7351 +scipy/stats/_discrete_distns.py,sha256=KrDAmqfvqtQ9wpnvD7G9CHnJxl1nZwnZs-59GVk1vUc,66099 +scipy/stats/_distn_infrastructure.py,sha256=-ygCdbB59IZ_bRzhIf9dwQw3dQuROiKCJewzcvCQmXo,153570 +scipy/stats/_distr_params.py,sha256=ccFQx6dMoVaS6Vrdo2vGcvWZbjH9I4Ms_J0-eHFRlac,9083 +scipy/stats/_distribution_infrastructure.py,sha256=wADGRn4OkrG3IXpTad6XTPO0DAXDYGsaxiWW9jjiRSM,237587 +scipy/stats/_entropy.py,sha256=JANQdP6c4EHa03N_Q-YOzjDjzR45MfKluNeovUfh_Hs,15994 +scipy/stats/_finite_differences.py,sha256=QaA5p36T0oDt4e_oMOE3QGBT8gB2C3E3ziZSWkkBF9g,4168 +scipy/stats/_fit.py,sha256=GdpnDmX-7h8UF7lNDm9XdLaZ414yd-5TV7vsb-GCux0,59674 +scipy/stats/_hypotests.py,sha256=MauKdPt1738BRsCU0Z3dTc-afU-Hrk6EsBeYCljkaAQ,86904 +scipy/stats/_kde.py,sha256=IdzX_7UlcEoAYX0jfgsuYpCYPz_BVxrk6Ri4h3q6cxs,25691 +scipy/stats/_ksstats.py,sha256=8Oo_0BAAZnDkLgckkySAFGxUo51ksnDADzkBe4RdkmU,20140 +scipy/stats/_levy_stable/__init__.py,sha256=W4eb9-VmMdFYSfFgodM9b_ityynkNxKoAzz59vrvfeg,46226 +scipy/stats/_levy_stable/__pycache__/__init__.cpython-312.pyc,, +scipy/stats/_levy_stable/levyst.cpython-312-darwin.so,sha256=lj_OexG_jgIrpqvfccPDwuBXBw2QuBUWo8ml4sZ5_TY,78160 +scipy/stats/_mannwhitneyu.py,sha256=aVllakdGa7DvBlfDfdwHxil8jaeYJ78PI40vXrjFD7M,19577 +scipy/stats/_mgc.py,sha256=CjCxNh9PIAETVGhTeOOkwqxXY76V1FFrq5uRJCNLg1k,21440 +scipy/stats/_morestats.py,sha256=kaJFz43tn3IbbsbyPZv9fP_quRwf6S9epq3HYawBhEg,184110 +scipy/stats/_mstats_basic.py,sha256=YeDjKinAg7Sav3Tuk8MNFO-Rf9ly-3ex1hWIrULpRyI,122946 +scipy/stats/_mstats_extras.py,sha256=0LL3I-tOG17fI5CKPBK7a8e5-yrgX4XLjfsHOs5MMQs,16362 +scipy/stats/_multicomp.py,sha256=jPMYXI0NDr636UyCxnsoKh1Asyz8-kgLNOS7qDL8C-g,16917 +scipy/stats/_multivariate.py,sha256=NJjTUpSwCPqlyf-jOA_e8gZgN3kp30PE8ZpTxhO1IPI,273926 +scipy/stats/_new_distributions.py,sha256=kchaaycgk1mxgAo1YzDKriytaC6vY4tMnDeElOpXxD4,18923 +scipy/stats/_odds_ratio.py,sha256=zZvZsD7ftKeWUrypXeUapcNoq006XldVAkMMC3RLbWE,17005 +scipy/stats/_page_trend_test.py,sha256=o5F_WZ6H2cpkJJOSlkhe9oFOPFULHbyvTS8BPLqgYNg,19315 +scipy/stats/_probability_distribution.py,sha256=Vo32L06njo2b01gBO8yYO-O3_iWv3CKmStTuwagu_wI,70023 +scipy/stats/_qmc.py,sha256=KyYRFHX00a_2ipIPw8eIETIbO4MVowLyeCtBH8L-iRE,107783 +scipy/stats/_qmc_cy.cpython-312-darwin.so,sha256=1tYsF04rJ3EO9jM5wqOQuKZhjMAzjkMrnwW2rMAH5Ko,122432 +scipy/stats/_qmc_cy.pyi,sha256=xOpTSlaG_1YDZhkJjQQtukbcgOTAR9FpcRMkU5g9mXc,1134 +scipy/stats/_qmvnt.py,sha256=y3SLZ70XHw8ks7n9jxxjTP9aOT2deMrUAj69r_H2mD0,16447 +scipy/stats/_qmvnt_cy.cpython-312-darwin.so,sha256=DqLAYqgNElq0j0e99cckiFizkQL4TnJZgc5MU0vcIm8,131584 +scipy/stats/_quantile.py,sha256=9DSll-bzgO6iNC2hafJVIayRQryYtu3TYZRkUwq3Fd0,21175 +scipy/stats/_rcont/__init__.py,sha256=dUzWdRuJNAxnGYVFjDqUB8DMYti3by1WziKEfBDOlB4,84 +scipy/stats/_rcont/__pycache__/__init__.cpython-312.pyc,, +scipy/stats/_rcont/rcont.cpython-312-darwin.so,sha256=MiQqsZ6vm7a0syyaa3uqF4JbtKBYiHaF8eBiTucygwQ,96552 +scipy/stats/_relative_risk.py,sha256=5zeYBMshYwtomiLTkaXc1nmWYD0FsaQNjf0iuDadtSc,9571 +scipy/stats/_resampling.py,sha256=TvmkTtuqKlH4O1XfJrWP5l8ZNimKBlWfkd1xYQSyq_E,106090 +scipy/stats/_result_classes.py,sha256=_ghuGdpFsCMuEmnfHg1AeorR-fASc77ACXYWEmQzXjI,1085 +scipy/stats/_sampling.py,sha256=jVdGtsHyII1GPTwHFKba_aUQAEUIYnaPKz_3v0yKGfI,46407 +scipy/stats/_sensitivity_analysis.py,sha256=mRco8OcaVAgapjufLoDT1a2dTsL4F3EAzKSi-4F79AU,25123 +scipy/stats/_sobol.cpython-312-darwin.so,sha256=7rZgxsjqj6s01QNgYSp7hMizW787Kew5syIlYPrSyFs,167600 +scipy/stats/_sobol.pyi,sha256=TAywylI75AF9th9QZY8TYfHvIQ1cyM5QZi7eBOAkrbg,971 +scipy/stats/_sobol_direction_numbers.npz,sha256=SFmTEUfULORluGBcsnf5V9mLg50DGU_fBleTV5BtGTs,589334 +scipy/stats/_stats.cpython-312-darwin.so,sha256=QQUTKVmAHNe5uyOCAOH6wd3_CttKm05_a9e61xYUlHo,390464 +scipy/stats/_stats.pxd,sha256=T_7IrDqgIahKMECV5WAtxtsoV91XBVRM359kAXPIhww,709 +scipy/stats/_stats_mstats_common.py,sha256=2CFrWyPzisPZLbUjpmr3R5NFe_NIpJCZwHmB83cFNW0,12580 +scipy/stats/_stats_py.py,sha256=jVByQD8L96iJXCho_eXPhCoPBemKMG1roA-dnAq2zG4,418343 +scipy/stats/_stats_pythran.cpython-312-darwin.so,sha256=zda4syeZtHhxPdmV-KAXcQKhHI9-GV5ZomyOtba9RwU,188136 +scipy/stats/_survival.py,sha256=gBGsHonhgUxAik7Ww75C-deozqmwdY6RMUen_6J0myI,26051 +scipy/stats/_tukeylambda_stats.py,sha256=l-PPBlFs40R6mw8AaQhXsRGRInrSRIcocHrg__uTG5A,6881 +scipy/stats/_unuran/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/stats/_unuran/__pycache__/__init__.cpython-312.pyc,, +scipy/stats/_unuran/unuran_wrapper.cpython-312-darwin.so,sha256=_zSSAuxtBRuFE4qcCS-P1oqNzTYTaErx7K2P0AgDtDE,521384 +scipy/stats/_unuran/unuran_wrapper.pyi,sha256=KFcmefkNMDwGB6BDttAzcvi7vZrU6XuD23BcYFdsyBQ,5615 +scipy/stats/_variation.py,sha256=v8Np0iJJIAEcI1_wwY8V2IfaLut0niSpsdoR8XUYrNQ,4856 +scipy/stats/_warnings_errors.py,sha256=MpucxNFYEDytXh7vrZCMqTkRfuXTvvMpQ2W_Ak2OnPk,1196 +scipy/stats/_wilcoxon.py,sha256=MHB8k3Ppg6NdHiZZPCiE_4-CXnX-OqgR4iiRfWtdw6M,10459 +scipy/stats/biasedurn.py,sha256=ECfilE4KrIhU2sK-KWtr8yxqthfVsyz_-o4F2TnMXU4,431 +scipy/stats/contingency.py,sha256=G0XVk8sbDQRvdHrxgspcg6I-PYrOceoZs8bHVbGY_zQ,18823 +scipy/stats/distributions.py,sha256=9Kt2fyTohorJcf6a7M9DYH8Nu4jEU66nKP01cRhKmuE,859 +scipy/stats/kde.py,sha256=8ZThSc3lz-l1Gb2jzIvy1J87_HTd7eXzxuPLClVpo7c,516 +scipy/stats/morestats.py,sha256=sDSu5RfajS5a-iLN-46xvL_aoWwqI-2TPzCRY4cxQZg,957 +scipy/stats/mstats.py,sha256=aRbrykjrvl-qOBkmGjlFMH4rbWYSqBBQHReanSAomFg,2466 +scipy/stats/mstats_basic.py,sha256=PjgL37PCPwiDx_ptqnmKXc1W3QGlRjjPrG0nI5FA4So,1394 +scipy/stats/mstats_extras.py,sha256=925lNnnf_NTRoyAnXql-k9syzhv7MF6T2kPGsdE2FHc,721 +scipy/stats/mvn.py,sha256=pOcB_Dd_DHpfbYnuJKq-wqmNNGCun1M0294xK1bX0KQ,498 +scipy/stats/qmc.py,sha256=b6gLkc_FSm11Ssb9uIai4XxLk4XL_qqK6Jc2k4RSeN0,11703 +scipy/stats/sampling.py,sha256=VYwxxGosFs-T3qdCmdw4tJYEFLlegwj-JgDin7iwndE,1939 +scipy/stats/stats.py,sha256=wa4-yBcaUfv85bJiP53REdEswpu5i92Ak7JXtKrag8M,1496 +scipy/stats/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +scipy/stats/tests/__pycache__/__init__.cpython-312.pyc,, +scipy/stats/tests/__pycache__/common_tests.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_axis_nan_policy.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_binned_statistic.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_censored_data.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_contingency.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_continued_fraction.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_continuous.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_continuous_basic.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_continuous_fit_censored.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_correlation.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_crosstab.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_device_dtype.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_discrete_basic.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_discrete_distns.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_distributions.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_entropy.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_fast_gen_inversion.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_fit.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_hypotests.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_kdeoth.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_marray.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_mgc.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_morestats.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_mstats_basic.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_mstats_extras.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_multicomp.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_multivariate.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_new_distributions.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_odds_ratio.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_qmc.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_quantile.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_rank.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_relative_risk.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_resampling.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_sampling.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_sensitivity_analysis.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_stats.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_survival.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_tukeylambda_stats.cpython-312.pyc,, +scipy/stats/tests/__pycache__/test_variation.cpython-312.pyc,, +scipy/stats/tests/common_tests.py,sha256=o9V7L6feUUwUqDCjMy3sSsDtCg2W8R0bLZItC8OjO-Y,12327 +scipy/stats/tests/data/__pycache__/_mvt.cpython-312.pyc,, +scipy/stats/tests/data/__pycache__/fisher_exact_results_from_r.cpython-312.pyc,, +scipy/stats/tests/data/_mvt.py,sha256=OvFCmMqI74DWIgo32UV55dP1nzvFvYBSyYcmKJes9pI,6905 +scipy/stats/tests/data/fisher_exact_results_from_r.py,sha256=BKxPAi4h3IOebcZYGxCbutYuAX0tlb40P0DEkfEi918,27349 +scipy/stats/tests/data/jf_skew_t_gamlss_pdf_data.npy,sha256=JU0t7kpNVHuTMcYCQ8b8_K_9JsixBNCNT2BFp2RbO7o,4064 +scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy,sha256=zxjB8tZaIyvyxxISgt8xvyqL6Cevr8TtgQ7TdFfuiYo,183728 +scipy/stats/tests/data/levy_stable/stable-Z1-pdf-sample-data.npy,sha256=_umVErq0zMZWm0e5JOSwNOHNurViT6_H4SBki9X3oSg,183688 +scipy/stats/tests/data/levy_stable/stable-loc-scale-sample-data.npy,sha256=88cZ7dVDH7nnuey20Z48p6kJUpi9GfImaFsPykDwwHM,9328 +scipy/stats/tests/data/nist_anova/AtmWtAg.dat,sha256=Qdd0i7H4cNhAABfFOZPuplhi_9SCquFpO-hNkyRcMD8,3063 +scipy/stats/tests/data/nist_anova/SiRstv.dat,sha256=x9wJ2g1qnzf4DK_w9F_WiOiDMDEg4td2z6uU77G07xM,1947 +scipy/stats/tests/data/nist_anova/SmLs01.dat,sha256=KdnJedRthF7XLA-w7XkIPIMTgzu89yBAMmZA2H4uQOQ,6055 +scipy/stats/tests/data/nist_anova/SmLs02.dat,sha256=nCPyxRk1dAoSPWiC7kG4dLaXs2GL3-KRXRt2NwgXoIA,46561 +scipy/stats/tests/data/nist_anova/SmLs03.dat,sha256=6yPHiQSk0KI4oURQOk99t-uEm-IZN-8eIPHb_y0mQ1U,451566 +scipy/stats/tests/data/nist_anova/SmLs04.dat,sha256=fI-HpgJF9cdGdBinclhVzOcWCCc5ZJZuXalUwirV-lc,6815 +scipy/stats/tests/data/nist_anova/SmLs05.dat,sha256=iJTaAWUFn7DPLTd9bQh_EMKEK1DPG0fnN8xk7BQlPRE,53799 +scipy/stats/tests/data/nist_anova/SmLs06.dat,sha256=riOkYT-LRgmJhPpCK32x7xYnD38gwnh_Eo1X8OK3eN8,523605 +scipy/stats/tests/data/nist_anova/SmLs07.dat,sha256=QtSS11d-vkVvqaIEeJ6oNwyET1CKoyQqjlfBl2sTOJA,7381 +scipy/stats/tests/data/nist_anova/SmLs08.dat,sha256=qrxQQ0I6gnhrefygKwT48x-bz-8laD8Vpn7c81nITRg,59228 +scipy/stats/tests/data/nist_anova/SmLs09.dat,sha256=qmELOQyNlH7CWOMt8PQ0Z_yxgg9Hxc4lqZOuHZxxWuc,577633 +scipy/stats/tests/data/nist_linregress/Norris.dat,sha256=zD_RTRxfqJHVZTAAyddzLDDbhCzKSfwFGr3hwZ1nq30,2591 +scipy/stats/tests/data/rel_breitwigner_pdf_sample_data_ROOT.npy,sha256=7vTccC3YxuMcGMdOH4EoTD6coqtQKC3jnJrTC3u4520,38624 +scipy/stats/tests/data/studentized_range_mpmath_ref.json,sha256=icZGNBodwmJNzOyEki9MreI2lS6nQJNWfnVJiHRNRNM,29239 +scipy/stats/tests/test_axis_nan_policy.py,sha256=uEENifw0Lss7PIoLcS0r_JPji_kzE4GWxx0n6mz6Q1w,64097 +scipy/stats/tests/test_binned_statistic.py,sha256=JZSu4MtS4KxgaFvAI_ZuFvf6UFuwY0wR5OpE70qrsMY,18845 +scipy/stats/tests/test_censored_data.py,sha256=pAQfSHhmcetcxoS1ZgIHVm1pEbapW7az7I-y_8phb5w,6935 +scipy/stats/tests/test_contingency.py,sha256=00QIN99yybM_HhrLf8kck85gWPUAQmYIKI7XnVzPF94,10937 +scipy/stats/tests/test_continued_fraction.py,sha256=GGRwIZ6zhsVNaR0Kbc7x2GFpOxSV48URXKz7B5_kEBQ,6709 +scipy/stats/tests/test_continuous.py,sha256=MYvWWe-uAlDx9yiX_98Tdv1BC5ij-QFrD9JDtttr1ow,92928 +scipy/stats/tests/test_continuous_basic.py,sha256=CFIWABN3Smq-dhlFZFi1zgVfOhx4gFuokbiFlxkVeOg,43541 +scipy/stats/tests/test_continuous_fit_censored.py,sha256=7hu1sSo9hhh0g9pmPMmjj2BI2rkxvA1h20XdMYZeyog,24188 +scipy/stats/tests/test_correlation.py,sha256=YsppqXAkNgjoNeRLOpVZ6fTi1-MpoHXAKFZNC-1tzp4,10762 +scipy/stats/tests/test_crosstab.py,sha256=2zqnoWW70MkvFjxAQlpW4vzWI624rcYLAlAVf7vZ9DU,3906 +scipy/stats/tests/test_device_dtype.py,sha256=porleR1Buj-qpFfoUEuSDZse-Sxuy5ymSGuLNQJCGQU,9273 +scipy/stats/tests/test_discrete_basic.py,sha256=FkvPFDudDv4AKbCikoBWuOzw4TwS14vFxEf76zQTtwQ,22743 +scipy/stats/tests/test_discrete_distns.py,sha256=8izg9bocSopchnn8dQYjBP01MperIsA1V7EaslBv7OY,27016 +scipy/stats/tests/test_distributions.py,sha256=oQ2ToNOgMC-Ld-jzlCvbwp2RfnX1HOxzPsJq2ZSrGhM,419240 +scipy/stats/tests/test_entropy.py,sha256=i-yAfk89DRVY_8ywUhjGF9JoAhg3jYaYqcaxNFnAwcU,12840 +scipy/stats/tests/test_fast_gen_inversion.py,sha256=IfVEHASa8hWmgJOIDna8lhI5bouQyz2-o2qRfIbetmI,16062 +scipy/stats/tests/test_fit.py,sha256=dbLw0YWVHyw5l5M6Rsvq0wjmxp7kXR2zNBPA_h5DWH4,48935 +scipy/stats/tests/test_hypotests.py,sha256=yzmNvfG8CI9Q7DL6E7nT2mEwV_vl3T1sw0dPaPB_SC0,97163 +scipy/stats/tests/test_kdeoth.py,sha256=x5pcnbT0R1oOi_IeHW9q7yws64cu68t81Zpsfv5RnGs,22863 +scipy/stats/tests/test_marray.py,sha256=KFN16jpgVWr8EIyJ4b7bFXmNqohq39DKhb0kYnCXE68,17408 +scipy/stats/tests/test_mgc.py,sha256=5c_jMKD69zKK8-f1GrRIKJTkUy9AUa20-ojO2ANuWC4,8373 +scipy/stats/tests/test_morestats.py,sha256=ONaQVocgm9LKK1JxOQtfgZUrdcPdVsb4c73t6Hz-nYM,156735 +scipy/stats/tests/test_mstats_basic.py,sha256=NFGgWMGxKCuiR1qtOZRL0JX82bBTHHToZGKyHgYLgu8,89805 +scipy/stats/tests/test_mstats_extras.py,sha256=AWojnbc60PG-JVhWkHp7uwDePeKg-oeLG4VWqjaX9U0,7317 +scipy/stats/tests/test_multicomp.py,sha256=s5mL9NQMvD4khQ12n2_maXKX9Q5pI0HFjcaYMZyhcJ0,17826 +scipy/stats/tests/test_multivariate.py,sha256=b678Zz7x_NeWavFkktkTJ1pdpp68XXYvHf04hwliB7k,198121 +scipy/stats/tests/test_new_distributions.py,sha256=vv-L8STWshYz4GEXh0ws2BwgO0A8nfu6us5h0g8CZoE,874 +scipy/stats/tests/test_odds_ratio.py,sha256=ZII-yvP_vhuaNa3qPB0Q5lh9yzRF-08ZcdkAwuu5E94,6727 +scipy/stats/tests/test_qmc.py,sha256=xPoyWSyFzg7oGDxBHIOoG3SEaoPyMJaAPuvDDJv8jBA,59205 +scipy/stats/tests/test_quantile.py,sha256=IhOvFNsHIA0MXAEM6xsMQTUTZXkpTz6ip4KlCHHC22I,17897 +scipy/stats/tests/test_rank.py,sha256=jSEzXc-KUyHiw1A58ct0IX_DkYwZobGGZFyOx539oPU,12775 +scipy/stats/tests/test_relative_risk.py,sha256=jzOGNQ2y9_YfFnXiGAiRDrgahy66qQkw6ZkHgygCJMA,3646 +scipy/stats/tests/test_resampling.py,sha256=FrY8A1IwwhoMV03YiCiu4caPckEsRUfPsedo8fg38ww,92370 +scipy/stats/tests/test_sampling.py,sha256=rWfN1HH-17jIB3lpyCOvYhTSMemFhqywxKVcTEIJzYg,54874 +scipy/stats/tests/test_sensitivity_analysis.py,sha256=nNF_B6Zl5YxmvppI8TEPOGroDsbgyLTF6jBmdJH2AUw,10678 +scipy/stats/tests/test_stats.py,sha256=hz2veCHRerVhRL99gLx074q2reJnQDDOzQGOqOzmoac,403192 +scipy/stats/tests/test_survival.py,sha256=Wmig-n93Y2wCuye9btK4QqXwUAdzF0xR_MO9iYZARjU,21958 +scipy/stats/tests/test_tukeylambda_stats.py,sha256=6WUBNVoTseVjfrHfWXtU11gTgmRcdnwAPLQOI0y_5U8,3231 +scipy/stats/tests/test_variation.py,sha256=Q-t49HELEgydYzY7Tq0ZJD5mwEPsDP8iMsskF8YSM_4,9360 +scipy/version.py,sha256=zJSXFTu37JGBuGs2fl69G_-NwCpgCS1UkFLxnJ1wvwY,318 diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/WHEEL b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..82bc2ec6f0444b626656e7f729bc3314146e0889 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/scipy-1.17.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: meson +Root-Is-Purelib: false +Tag: cp312-cp312-macosx_14_0_arm64 +Generator: delocate 0.13.0 + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/__init__.py b/.venv_haddock/lib/python3.12/site-packages/yaml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d58f0891737def7f38e5d86dde2dbf9be0c13dce --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/__init__.py @@ -0,0 +1,390 @@ + +from .error import * + +from .tokens import * +from .events import * +from .nodes import * + +from .loader import * +from .dumper import * + +__version__ = '6.0.3' +try: + from .cyaml import * + __with_libyaml__ = True +except ImportError: + __with_libyaml__ = False + +import io + +#------------------------------------------------------------------------------ +# XXX "Warnings control" is now deprecated. Leaving in the API function to not +# break code that uses it. +#------------------------------------------------------------------------------ +def warnings(settings=None): + if settings is None: + return {} + +#------------------------------------------------------------------------------ +def scan(stream, Loader=Loader): + """ + Scan a YAML stream and produce scanning tokens. + """ + loader = Loader(stream) + try: + while loader.check_token(): + yield loader.get_token() + finally: + loader.dispose() + +def parse(stream, Loader=Loader): + """ + Parse a YAML stream and produce parsing events. + """ + loader = Loader(stream) + try: + while loader.check_event(): + yield loader.get_event() + finally: + loader.dispose() + +def compose(stream, Loader=Loader): + """ + Parse the first YAML document in a stream + and produce the corresponding representation tree. + """ + loader = Loader(stream) + try: + return loader.get_single_node() + finally: + loader.dispose() + +def compose_all(stream, Loader=Loader): + """ + Parse all YAML documents in a stream + and produce corresponding representation trees. + """ + loader = Loader(stream) + try: + while loader.check_node(): + yield loader.get_node() + finally: + loader.dispose() + +def load(stream, Loader): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + """ + loader = Loader(stream) + try: + return loader.get_single_data() + finally: + loader.dispose() + +def load_all(stream, Loader): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + """ + loader = Loader(stream) + try: + while loader.check_data(): + yield loader.get_data() + finally: + loader.dispose() + +def full_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve all tags except those known to be + unsafe on untrusted input. + """ + return load(stream, FullLoader) + +def full_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve all tags except those known to be + unsafe on untrusted input. + """ + return load_all(stream, FullLoader) + +def safe_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve only basic YAML tags. This is known + to be safe for untrusted input. + """ + return load(stream, SafeLoader) + +def safe_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve only basic YAML tags. This is known + to be safe for untrusted input. + """ + return load_all(stream, SafeLoader) + +def unsafe_load(stream): + """ + Parse the first YAML document in a stream + and produce the corresponding Python object. + + Resolve all tags, even those known to be + unsafe on untrusted input. + """ + return load(stream, UnsafeLoader) + +def unsafe_load_all(stream): + """ + Parse all YAML documents in a stream + and produce corresponding Python objects. + + Resolve all tags, even those known to be + unsafe on untrusted input. + """ + return load_all(stream, UnsafeLoader) + +def emit(events, stream=None, Dumper=Dumper, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None): + """ + Emit YAML parsing events into a stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + stream = io.StringIO() + getvalue = stream.getvalue + dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + try: + for event in events: + dumper.emit(event) + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def serialize_all(nodes, stream=None, Dumper=Dumper, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None): + """ + Serialize a sequence of representation trees into a YAML stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + if encoding is None: + stream = io.StringIO() + else: + stream = io.BytesIO() + getvalue = stream.getvalue + dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break, + encoding=encoding, version=version, tags=tags, + explicit_start=explicit_start, explicit_end=explicit_end) + try: + dumper.open() + for node in nodes: + dumper.serialize(node) + dumper.close() + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def serialize(node, stream=None, Dumper=Dumper, **kwds): + """ + Serialize a representation tree into a YAML stream. + If stream is None, return the produced string instead. + """ + return serialize_all([node], stream, Dumper=Dumper, **kwds) + +def dump_all(documents, stream=None, Dumper=Dumper, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + """ + Serialize a sequence of Python objects into a YAML stream. + If stream is None, return the produced string instead. + """ + getvalue = None + if stream is None: + if encoding is None: + stream = io.StringIO() + else: + stream = io.BytesIO() + getvalue = stream.getvalue + dumper = Dumper(stream, default_style=default_style, + default_flow_style=default_flow_style, + canonical=canonical, indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break, + encoding=encoding, version=version, tags=tags, + explicit_start=explicit_start, explicit_end=explicit_end, sort_keys=sort_keys) + try: + dumper.open() + for data in documents: + dumper.represent(data) + dumper.close() + finally: + dumper.dispose() + if getvalue: + return getvalue() + +def dump(data, stream=None, Dumper=Dumper, **kwds): + """ + Serialize a Python object into a YAML stream. + If stream is None, return the produced string instead. + """ + return dump_all([data], stream, Dumper=Dumper, **kwds) + +def safe_dump_all(documents, stream=None, **kwds): + """ + Serialize a sequence of Python objects into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + return dump_all(documents, stream, Dumper=SafeDumper, **kwds) + +def safe_dump(data, stream=None, **kwds): + """ + Serialize a Python object into a YAML stream. + Produce only basic YAML tags. + If stream is None, return the produced string instead. + """ + return dump_all([data], stream, Dumper=SafeDumper, **kwds) + +def add_implicit_resolver(tag, regexp, first=None, + Loader=None, Dumper=Dumper): + """ + Add an implicit scalar detector. + If an implicit scalar value matches the given regexp, + the corresponding tag is assigned to the scalar. + first is a sequence of possible initial characters or None. + """ + if Loader is None: + loader.Loader.add_implicit_resolver(tag, regexp, first) + loader.FullLoader.add_implicit_resolver(tag, regexp, first) + loader.UnsafeLoader.add_implicit_resolver(tag, regexp, first) + else: + Loader.add_implicit_resolver(tag, regexp, first) + Dumper.add_implicit_resolver(tag, regexp, first) + +def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=Dumper): + """ + Add a path based resolver for the given tag. + A path is a list of keys that forms a path + to a node in the representation tree. + Keys can be string values, integers, or None. + """ + if Loader is None: + loader.Loader.add_path_resolver(tag, path, kind) + loader.FullLoader.add_path_resolver(tag, path, kind) + loader.UnsafeLoader.add_path_resolver(tag, path, kind) + else: + Loader.add_path_resolver(tag, path, kind) + Dumper.add_path_resolver(tag, path, kind) + +def add_constructor(tag, constructor, Loader=None): + """ + Add a constructor for the given tag. + Constructor is a function that accepts a Loader instance + and a node object and produces the corresponding Python object. + """ + if Loader is None: + loader.Loader.add_constructor(tag, constructor) + loader.FullLoader.add_constructor(tag, constructor) + loader.UnsafeLoader.add_constructor(tag, constructor) + else: + Loader.add_constructor(tag, constructor) + +def add_multi_constructor(tag_prefix, multi_constructor, Loader=None): + """ + Add a multi-constructor for the given tag prefix. + Multi-constructor is called for a node if its tag starts with tag_prefix. + Multi-constructor accepts a Loader instance, a tag suffix, + and a node object and produces the corresponding Python object. + """ + if Loader is None: + loader.Loader.add_multi_constructor(tag_prefix, multi_constructor) + loader.FullLoader.add_multi_constructor(tag_prefix, multi_constructor) + loader.UnsafeLoader.add_multi_constructor(tag_prefix, multi_constructor) + else: + Loader.add_multi_constructor(tag_prefix, multi_constructor) + +def add_representer(data_type, representer, Dumper=Dumper): + """ + Add a representer for the given type. + Representer is a function accepting a Dumper instance + and an instance of the given data type + and producing the corresponding representation node. + """ + Dumper.add_representer(data_type, representer) + +def add_multi_representer(data_type, multi_representer, Dumper=Dumper): + """ + Add a representer for the given type. + Multi-representer is a function accepting a Dumper instance + and an instance of the given data type or subtype + and producing the corresponding representation node. + """ + Dumper.add_multi_representer(data_type, multi_representer) + +class YAMLObjectMetaclass(type): + """ + The metaclass for YAMLObject. + """ + def __init__(cls, name, bases, kwds): + super(YAMLObjectMetaclass, cls).__init__(name, bases, kwds) + if 'yaml_tag' in kwds and kwds['yaml_tag'] is not None: + if isinstance(cls.yaml_loader, list): + for loader in cls.yaml_loader: + loader.add_constructor(cls.yaml_tag, cls.from_yaml) + else: + cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml) + + cls.yaml_dumper.add_representer(cls, cls.to_yaml) + +class YAMLObject(metaclass=YAMLObjectMetaclass): + """ + An object that can dump itself to a YAML stream + and load itself from a YAML stream. + """ + + __slots__ = () # no direct instantiation, so allow immutable subclasses + + yaml_loader = [Loader, FullLoader, UnsafeLoader] + yaml_dumper = Dumper + + yaml_tag = None + yaml_flow_style = None + + @classmethod + def from_yaml(cls, loader, node): + """ + Convert a representation node to a Python object. + """ + return loader.construct_yaml_object(node, cls) + + @classmethod + def to_yaml(cls, dumper, data): + """ + Convert a Python object to a representation node. + """ + return dumper.represent_yaml_object(cls.yaml_tag, data, cls, + flow_style=cls.yaml_flow_style) + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/composer.py b/.venv_haddock/lib/python3.12/site-packages/yaml/composer.py new file mode 100644 index 0000000000000000000000000000000000000000..6d15cb40e3b4198819c91c6f8d8b32807fcf53b2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/composer.py @@ -0,0 +1,139 @@ + +__all__ = ['Composer', 'ComposerError'] + +from .error import MarkedYAMLError +from .events import * +from .nodes import * + +class ComposerError(MarkedYAMLError): + pass + +class Composer: + + def __init__(self): + self.anchors = {} + + def check_node(self): + # Drop the STREAM-START event. + if self.check_event(StreamStartEvent): + self.get_event() + + # If there are more documents available? + return not self.check_event(StreamEndEvent) + + def get_node(self): + # Get the root node of the next document. + if not self.check_event(StreamEndEvent): + return self.compose_document() + + def get_single_node(self): + # Drop the STREAM-START event. + self.get_event() + + # Compose a document if the stream is not empty. + document = None + if not self.check_event(StreamEndEvent): + document = self.compose_document() + + # Ensure that the stream contains no more documents. + if not self.check_event(StreamEndEvent): + event = self.get_event() + raise ComposerError("expected a single document in the stream", + document.start_mark, "but found another document", + event.start_mark) + + # Drop the STREAM-END event. + self.get_event() + + return document + + def compose_document(self): + # Drop the DOCUMENT-START event. + self.get_event() + + # Compose the root node. + node = self.compose_node(None, None) + + # Drop the DOCUMENT-END event. + self.get_event() + + self.anchors = {} + return node + + def compose_node(self, parent, index): + if self.check_event(AliasEvent): + event = self.get_event() + anchor = event.anchor + if anchor not in self.anchors: + raise ComposerError(None, None, "found undefined alias %r" + % anchor, event.start_mark) + return self.anchors[anchor] + event = self.peek_event() + anchor = event.anchor + if anchor is not None: + if anchor in self.anchors: + raise ComposerError("found duplicate anchor %r; first occurrence" + % anchor, self.anchors[anchor].start_mark, + "second occurrence", event.start_mark) + self.descend_resolver(parent, index) + if self.check_event(ScalarEvent): + node = self.compose_scalar_node(anchor) + elif self.check_event(SequenceStartEvent): + node = self.compose_sequence_node(anchor) + elif self.check_event(MappingStartEvent): + node = self.compose_mapping_node(anchor) + self.ascend_resolver() + return node + + def compose_scalar_node(self, anchor): + event = self.get_event() + tag = event.tag + if tag is None or tag == '!': + tag = self.resolve(ScalarNode, event.value, event.implicit) + node = ScalarNode(tag, event.value, + event.start_mark, event.end_mark, style=event.style) + if anchor is not None: + self.anchors[anchor] = node + return node + + def compose_sequence_node(self, anchor): + start_event = self.get_event() + tag = start_event.tag + if tag is None or tag == '!': + tag = self.resolve(SequenceNode, None, start_event.implicit) + node = SequenceNode(tag, [], + start_event.start_mark, None, + flow_style=start_event.flow_style) + if anchor is not None: + self.anchors[anchor] = node + index = 0 + while not self.check_event(SequenceEndEvent): + node.value.append(self.compose_node(node, index)) + index += 1 + end_event = self.get_event() + node.end_mark = end_event.end_mark + return node + + def compose_mapping_node(self, anchor): + start_event = self.get_event() + tag = start_event.tag + if tag is None or tag == '!': + tag = self.resolve(MappingNode, None, start_event.implicit) + node = MappingNode(tag, [], + start_event.start_mark, None, + flow_style=start_event.flow_style) + if anchor is not None: + self.anchors[anchor] = node + while not self.check_event(MappingEndEvent): + #key_event = self.peek_event() + item_key = self.compose_node(node, None) + #if item_key in node.value: + # raise ComposerError("while composing a mapping", start_event.start_mark, + # "found duplicate key", key_event.start_mark) + item_value = self.compose_node(node, item_key) + #node.value[item_key] = item_value + node.value.append((item_key, item_value)) + end_event = self.get_event() + node.end_mark = end_event.end_mark + return node + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/constructor.py b/.venv_haddock/lib/python3.12/site-packages/yaml/constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..619acd3070a4845c653fcf22a626e05158035bc2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/constructor.py @@ -0,0 +1,748 @@ + +__all__ = [ + 'BaseConstructor', + 'SafeConstructor', + 'FullConstructor', + 'UnsafeConstructor', + 'Constructor', + 'ConstructorError' +] + +from .error import * +from .nodes import * + +import collections.abc, datetime, base64, binascii, re, sys, types + +class ConstructorError(MarkedYAMLError): + pass + +class BaseConstructor: + + yaml_constructors = {} + yaml_multi_constructors = {} + + def __init__(self): + self.constructed_objects = {} + self.recursive_objects = {} + self.state_generators = [] + self.deep_construct = False + + def check_data(self): + # If there are more documents available? + return self.check_node() + + def check_state_key(self, key): + """Block special attributes/methods from being set in a newly created + object, to prevent user-controlled methods from being called during + deserialization""" + if self.get_state_keys_blacklist_regexp().match(key): + raise ConstructorError(None, None, + "blacklisted key '%s' in instance state found" % (key,), None) + + def get_data(self): + # Construct and return the next document. + if self.check_node(): + return self.construct_document(self.get_node()) + + def get_single_data(self): + # Ensure that the stream contains a single document and construct it. + node = self.get_single_node() + if node is not None: + return self.construct_document(node) + return None + + def construct_document(self, node): + data = self.construct_object(node) + while self.state_generators: + state_generators = self.state_generators + self.state_generators = [] + for generator in state_generators: + for dummy in generator: + pass + self.constructed_objects = {} + self.recursive_objects = {} + self.deep_construct = False + return data + + def construct_object(self, node, deep=False): + if node in self.constructed_objects: + return self.constructed_objects[node] + if deep: + old_deep = self.deep_construct + self.deep_construct = True + if node in self.recursive_objects: + raise ConstructorError(None, None, + "found unconstructable recursive node", node.start_mark) + self.recursive_objects[node] = None + constructor = None + tag_suffix = None + if node.tag in self.yaml_constructors: + constructor = self.yaml_constructors[node.tag] + else: + for tag_prefix in self.yaml_multi_constructors: + if tag_prefix is not None and node.tag.startswith(tag_prefix): + tag_suffix = node.tag[len(tag_prefix):] + constructor = self.yaml_multi_constructors[tag_prefix] + break + else: + if None in self.yaml_multi_constructors: + tag_suffix = node.tag + constructor = self.yaml_multi_constructors[None] + elif None in self.yaml_constructors: + constructor = self.yaml_constructors[None] + elif isinstance(node, ScalarNode): + constructor = self.__class__.construct_scalar + elif isinstance(node, SequenceNode): + constructor = self.__class__.construct_sequence + elif isinstance(node, MappingNode): + constructor = self.__class__.construct_mapping + if tag_suffix is None: + data = constructor(self, node) + else: + data = constructor(self, tag_suffix, node) + if isinstance(data, types.GeneratorType): + generator = data + data = next(generator) + if self.deep_construct: + for dummy in generator: + pass + else: + self.state_generators.append(generator) + self.constructed_objects[node] = data + del self.recursive_objects[node] + if deep: + self.deep_construct = old_deep + return data + + def construct_scalar(self, node): + if not isinstance(node, ScalarNode): + raise ConstructorError(None, None, + "expected a scalar node, but found %s" % node.id, + node.start_mark) + return node.value + + def construct_sequence(self, node, deep=False): + if not isinstance(node, SequenceNode): + raise ConstructorError(None, None, + "expected a sequence node, but found %s" % node.id, + node.start_mark) + return [self.construct_object(child, deep=deep) + for child in node.value] + + def construct_mapping(self, node, deep=False): + if not isinstance(node, MappingNode): + raise ConstructorError(None, None, + "expected a mapping node, but found %s" % node.id, + node.start_mark) + mapping = {} + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + if not isinstance(key, collections.abc.Hashable): + raise ConstructorError("while constructing a mapping", node.start_mark, + "found unhashable key", key_node.start_mark) + value = self.construct_object(value_node, deep=deep) + mapping[key] = value + return mapping + + def construct_pairs(self, node, deep=False): + if not isinstance(node, MappingNode): + raise ConstructorError(None, None, + "expected a mapping node, but found %s" % node.id, + node.start_mark) + pairs = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + value = self.construct_object(value_node, deep=deep) + pairs.append((key, value)) + return pairs + + @classmethod + def add_constructor(cls, tag, constructor): + if not 'yaml_constructors' in cls.__dict__: + cls.yaml_constructors = cls.yaml_constructors.copy() + cls.yaml_constructors[tag] = constructor + + @classmethod + def add_multi_constructor(cls, tag_prefix, multi_constructor): + if not 'yaml_multi_constructors' in cls.__dict__: + cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy() + cls.yaml_multi_constructors[tag_prefix] = multi_constructor + +class SafeConstructor(BaseConstructor): + + def construct_scalar(self, node): + if isinstance(node, MappingNode): + for key_node, value_node in node.value: + if key_node.tag == 'tag:yaml.org,2002:value': + return self.construct_scalar(value_node) + return super().construct_scalar(node) + + def flatten_mapping(self, node): + merge = [] + index = 0 + while index < len(node.value): + key_node, value_node = node.value[index] + if key_node.tag == 'tag:yaml.org,2002:merge': + del node.value[index] + if isinstance(value_node, MappingNode): + self.flatten_mapping(value_node) + merge.extend(value_node.value) + elif isinstance(value_node, SequenceNode): + submerge = [] + for subnode in value_node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing a mapping", + node.start_mark, + "expected a mapping for merging, but found %s" + % subnode.id, subnode.start_mark) + self.flatten_mapping(subnode) + submerge.append(subnode.value) + submerge.reverse() + for value in submerge: + merge.extend(value) + else: + raise ConstructorError("while constructing a mapping", node.start_mark, + "expected a mapping or list of mappings for merging, but found %s" + % value_node.id, value_node.start_mark) + elif key_node.tag == 'tag:yaml.org,2002:value': + key_node.tag = 'tag:yaml.org,2002:str' + index += 1 + else: + index += 1 + if merge: + node.value = merge + node.value + + def construct_mapping(self, node, deep=False): + if isinstance(node, MappingNode): + self.flatten_mapping(node) + return super().construct_mapping(node, deep=deep) + + def construct_yaml_null(self, node): + self.construct_scalar(node) + return None + + bool_values = { + 'yes': True, + 'no': False, + 'true': True, + 'false': False, + 'on': True, + 'off': False, + } + + def construct_yaml_bool(self, node): + value = self.construct_scalar(node) + return self.bool_values[value.lower()] + + def construct_yaml_int(self, node): + value = self.construct_scalar(node) + value = value.replace('_', '') + sign = +1 + if value[0] == '-': + sign = -1 + if value[0] in '+-': + value = value[1:] + if value == '0': + return 0 + elif value.startswith('0b'): + return sign*int(value[2:], 2) + elif value.startswith('0x'): + return sign*int(value[2:], 16) + elif value[0] == '0': + return sign*int(value, 8) + elif ':' in value: + digits = [int(part) for part in value.split(':')] + digits.reverse() + base = 1 + value = 0 + for digit in digits: + value += digit*base + base *= 60 + return sign*value + else: + return sign*int(value) + + inf_value = 1e300 + while inf_value != inf_value*inf_value: + inf_value *= inf_value + nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99). + + def construct_yaml_float(self, node): + value = self.construct_scalar(node) + value = value.replace('_', '').lower() + sign = +1 + if value[0] == '-': + sign = -1 + if value[0] in '+-': + value = value[1:] + if value == '.inf': + return sign*self.inf_value + elif value == '.nan': + return self.nan_value + elif ':' in value: + digits = [float(part) for part in value.split(':')] + digits.reverse() + base = 1 + value = 0.0 + for digit in digits: + value += digit*base + base *= 60 + return sign*value + else: + return sign*float(value) + + def construct_yaml_binary(self, node): + try: + value = self.construct_scalar(node).encode('ascii') + except UnicodeEncodeError as exc: + raise ConstructorError(None, None, + "failed to convert base64 data into ascii: %s" % exc, + node.start_mark) + try: + if hasattr(base64, 'decodebytes'): + return base64.decodebytes(value) + else: + return base64.decodestring(value) + except binascii.Error as exc: + raise ConstructorError(None, None, + "failed to decode base64 data: %s" % exc, node.start_mark) + + timestamp_regexp = re.compile( + r'''^(?P[0-9][0-9][0-9][0-9]) + -(?P[0-9][0-9]?) + -(?P[0-9][0-9]?) + (?:(?:[Tt]|[ \t]+) + (?P[0-9][0-9]?) + :(?P[0-9][0-9]) + :(?P[0-9][0-9]) + (?:\.(?P[0-9]*))? + (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) + (?::(?P[0-9][0-9]))?))?)?$''', re.X) + + def construct_yaml_timestamp(self, node): + value = self.construct_scalar(node) + match = self.timestamp_regexp.match(node.value) + values = match.groupdict() + year = int(values['year']) + month = int(values['month']) + day = int(values['day']) + if not values['hour']: + return datetime.date(year, month, day) + hour = int(values['hour']) + minute = int(values['minute']) + second = int(values['second']) + fraction = 0 + tzinfo = None + if values['fraction']: + fraction = values['fraction'][:6] + while len(fraction) < 6: + fraction += '0' + fraction = int(fraction) + if values['tz_sign']: + tz_hour = int(values['tz_hour']) + tz_minute = int(values['tz_minute'] or 0) + delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute) + if values['tz_sign'] == '-': + delta = -delta + tzinfo = datetime.timezone(delta) + elif values['tz']: + tzinfo = datetime.timezone.utc + return datetime.datetime(year, month, day, hour, minute, second, fraction, + tzinfo=tzinfo) + + def construct_yaml_omap(self, node): + # Note: we do not check for duplicate keys, because it's too + # CPU-expensive. + omap = [] + yield omap + if not isinstance(node, SequenceNode): + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a sequence, but found %s" % node.id, node.start_mark) + for subnode in node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a mapping of length 1, but found %s" % subnode.id, + subnode.start_mark) + if len(subnode.value) != 1: + raise ConstructorError("while constructing an ordered map", node.start_mark, + "expected a single mapping item, but found %d items" % len(subnode.value), + subnode.start_mark) + key_node, value_node = subnode.value[0] + key = self.construct_object(key_node) + value = self.construct_object(value_node) + omap.append((key, value)) + + def construct_yaml_pairs(self, node): + # Note: the same code as `construct_yaml_omap`. + pairs = [] + yield pairs + if not isinstance(node, SequenceNode): + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a sequence, but found %s" % node.id, node.start_mark) + for subnode in node.value: + if not isinstance(subnode, MappingNode): + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a mapping of length 1, but found %s" % subnode.id, + subnode.start_mark) + if len(subnode.value) != 1: + raise ConstructorError("while constructing pairs", node.start_mark, + "expected a single mapping item, but found %d items" % len(subnode.value), + subnode.start_mark) + key_node, value_node = subnode.value[0] + key = self.construct_object(key_node) + value = self.construct_object(value_node) + pairs.append((key, value)) + + def construct_yaml_set(self, node): + data = set() + yield data + value = self.construct_mapping(node) + data.update(value) + + def construct_yaml_str(self, node): + return self.construct_scalar(node) + + def construct_yaml_seq(self, node): + data = [] + yield data + data.extend(self.construct_sequence(node)) + + def construct_yaml_map(self, node): + data = {} + yield data + value = self.construct_mapping(node) + data.update(value) + + def construct_yaml_object(self, node, cls): + data = cls.__new__(cls) + yield data + if hasattr(data, '__setstate__'): + state = self.construct_mapping(node, deep=True) + data.__setstate__(state) + else: + state = self.construct_mapping(node) + data.__dict__.update(state) + + def construct_undefined(self, node): + raise ConstructorError(None, None, + "could not determine a constructor for the tag %r" % node.tag, + node.start_mark) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:null', + SafeConstructor.construct_yaml_null) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:bool', + SafeConstructor.construct_yaml_bool) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:int', + SafeConstructor.construct_yaml_int) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:float', + SafeConstructor.construct_yaml_float) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:binary', + SafeConstructor.construct_yaml_binary) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:timestamp', + SafeConstructor.construct_yaml_timestamp) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:omap', + SafeConstructor.construct_yaml_omap) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:pairs', + SafeConstructor.construct_yaml_pairs) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:set', + SafeConstructor.construct_yaml_set) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:str', + SafeConstructor.construct_yaml_str) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:seq', + SafeConstructor.construct_yaml_seq) + +SafeConstructor.add_constructor( + 'tag:yaml.org,2002:map', + SafeConstructor.construct_yaml_map) + +SafeConstructor.add_constructor(None, + SafeConstructor.construct_undefined) + +class FullConstructor(SafeConstructor): + # 'extend' is blacklisted because it is used by + # construct_python_object_apply to add `listitems` to a newly generate + # python instance + def get_state_keys_blacklist(self): + return ['^extend$', '^__.*__$'] + + def get_state_keys_blacklist_regexp(self): + if not hasattr(self, 'state_keys_blacklist_regexp'): + self.state_keys_blacklist_regexp = re.compile('(' + '|'.join(self.get_state_keys_blacklist()) + ')') + return self.state_keys_blacklist_regexp + + def construct_python_str(self, node): + return self.construct_scalar(node) + + def construct_python_unicode(self, node): + return self.construct_scalar(node) + + def construct_python_bytes(self, node): + try: + value = self.construct_scalar(node).encode('ascii') + except UnicodeEncodeError as exc: + raise ConstructorError(None, None, + "failed to convert base64 data into ascii: %s" % exc, + node.start_mark) + try: + if hasattr(base64, 'decodebytes'): + return base64.decodebytes(value) + else: + return base64.decodestring(value) + except binascii.Error as exc: + raise ConstructorError(None, None, + "failed to decode base64 data: %s" % exc, node.start_mark) + + def construct_python_long(self, node): + return self.construct_yaml_int(node) + + def construct_python_complex(self, node): + return complex(self.construct_scalar(node)) + + def construct_python_tuple(self, node): + return tuple(self.construct_sequence(node)) + + def find_python_module(self, name, mark, unsafe=False): + if not name: + raise ConstructorError("while constructing a Python module", mark, + "expected non-empty name appended to the tag", mark) + if unsafe: + try: + __import__(name) + except ImportError as exc: + raise ConstructorError("while constructing a Python module", mark, + "cannot find module %r (%s)" % (name, exc), mark) + if name not in sys.modules: + raise ConstructorError("while constructing a Python module", mark, + "module %r is not imported" % name, mark) + return sys.modules[name] + + def find_python_name(self, name, mark, unsafe=False): + if not name: + raise ConstructorError("while constructing a Python object", mark, + "expected non-empty name appended to the tag", mark) + if '.' in name: + module_name, object_name = name.rsplit('.', 1) + else: + module_name = 'builtins' + object_name = name + if unsafe: + try: + __import__(module_name) + except ImportError as exc: + raise ConstructorError("while constructing a Python object", mark, + "cannot find module %r (%s)" % (module_name, exc), mark) + if module_name not in sys.modules: + raise ConstructorError("while constructing a Python object", mark, + "module %r is not imported" % module_name, mark) + module = sys.modules[module_name] + if not hasattr(module, object_name): + raise ConstructorError("while constructing a Python object", mark, + "cannot find %r in the module %r" + % (object_name, module.__name__), mark) + return getattr(module, object_name) + + def construct_python_name(self, suffix, node): + value = self.construct_scalar(node) + if value: + raise ConstructorError("while constructing a Python name", node.start_mark, + "expected the empty value, but found %r" % value, node.start_mark) + return self.find_python_name(suffix, node.start_mark) + + def construct_python_module(self, suffix, node): + value = self.construct_scalar(node) + if value: + raise ConstructorError("while constructing a Python module", node.start_mark, + "expected the empty value, but found %r" % value, node.start_mark) + return self.find_python_module(suffix, node.start_mark) + + def make_python_instance(self, suffix, node, + args=None, kwds=None, newobj=False, unsafe=False): + if not args: + args = [] + if not kwds: + kwds = {} + cls = self.find_python_name(suffix, node.start_mark) + if not (unsafe or isinstance(cls, type)): + raise ConstructorError("while constructing a Python instance", node.start_mark, + "expected a class, but found %r" % type(cls), + node.start_mark) + if newobj and isinstance(cls, type): + return cls.__new__(cls, *args, **kwds) + else: + return cls(*args, **kwds) + + def set_python_instance_state(self, instance, state, unsafe=False): + if hasattr(instance, '__setstate__'): + instance.__setstate__(state) + else: + slotstate = {} + if isinstance(state, tuple) and len(state) == 2: + state, slotstate = state + if hasattr(instance, '__dict__'): + if not unsafe and state: + for key in state.keys(): + self.check_state_key(key) + instance.__dict__.update(state) + elif state: + slotstate.update(state) + for key, value in slotstate.items(): + if not unsafe: + self.check_state_key(key) + setattr(instance, key, value) + + def construct_python_object(self, suffix, node): + # Format: + # !!python/object:module.name { ... state ... } + instance = self.make_python_instance(suffix, node, newobj=True) + yield instance + deep = hasattr(instance, '__setstate__') + state = self.construct_mapping(node, deep=deep) + self.set_python_instance_state(instance, state) + + def construct_python_object_apply(self, suffix, node, newobj=False): + # Format: + # !!python/object/apply # (or !!python/object/new) + # args: [ ... arguments ... ] + # kwds: { ... keywords ... } + # state: ... state ... + # listitems: [ ... listitems ... ] + # dictitems: { ... dictitems ... } + # or short format: + # !!python/object/apply [ ... arguments ... ] + # The difference between !!python/object/apply and !!python/object/new + # is how an object is created, check make_python_instance for details. + if isinstance(node, SequenceNode): + args = self.construct_sequence(node, deep=True) + kwds = {} + state = {} + listitems = [] + dictitems = {} + else: + value = self.construct_mapping(node, deep=True) + args = value.get('args', []) + kwds = value.get('kwds', {}) + state = value.get('state', {}) + listitems = value.get('listitems', []) + dictitems = value.get('dictitems', {}) + instance = self.make_python_instance(suffix, node, args, kwds, newobj) + if state: + self.set_python_instance_state(instance, state) + if listitems: + instance.extend(listitems) + if dictitems: + for key in dictitems: + instance[key] = dictitems[key] + return instance + + def construct_python_object_new(self, suffix, node): + return self.construct_python_object_apply(suffix, node, newobj=True) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/none', + FullConstructor.construct_yaml_null) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/bool', + FullConstructor.construct_yaml_bool) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/str', + FullConstructor.construct_python_str) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/unicode', + FullConstructor.construct_python_unicode) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/bytes', + FullConstructor.construct_python_bytes) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/int', + FullConstructor.construct_yaml_int) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/long', + FullConstructor.construct_python_long) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/float', + FullConstructor.construct_yaml_float) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/complex', + FullConstructor.construct_python_complex) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/list', + FullConstructor.construct_yaml_seq) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/tuple', + FullConstructor.construct_python_tuple) + +FullConstructor.add_constructor( + 'tag:yaml.org,2002:python/dict', + FullConstructor.construct_yaml_map) + +FullConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/name:', + FullConstructor.construct_python_name) + +class UnsafeConstructor(FullConstructor): + + def find_python_module(self, name, mark): + return super(UnsafeConstructor, self).find_python_module(name, mark, unsafe=True) + + def find_python_name(self, name, mark): + return super(UnsafeConstructor, self).find_python_name(name, mark, unsafe=True) + + def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False): + return super(UnsafeConstructor, self).make_python_instance( + suffix, node, args, kwds, newobj, unsafe=True) + + def set_python_instance_state(self, instance, state): + return super(UnsafeConstructor, self).set_python_instance_state( + instance, state, unsafe=True) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/module:', + UnsafeConstructor.construct_python_module) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object:', + UnsafeConstructor.construct_python_object) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object/new:', + UnsafeConstructor.construct_python_object_new) + +UnsafeConstructor.add_multi_constructor( + 'tag:yaml.org,2002:python/object/apply:', + UnsafeConstructor.construct_python_object_apply) + +# Constructor is same as UnsafeConstructor. Need to leave this in place in case +# people have extended it directly. +class Constructor(UnsafeConstructor): + pass diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/cyaml.py b/.venv_haddock/lib/python3.12/site-packages/yaml/cyaml.py new file mode 100644 index 0000000000000000000000000000000000000000..0c21345879b298bb8668201bebe7d289586b17f9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/cyaml.py @@ -0,0 +1,101 @@ + +__all__ = [ + 'CBaseLoader', 'CSafeLoader', 'CFullLoader', 'CUnsafeLoader', 'CLoader', + 'CBaseDumper', 'CSafeDumper', 'CDumper' +] + +from yaml._yaml import CParser, CEmitter + +from .constructor import * + +from .serializer import * +from .representer import * + +from .resolver import * + +class CBaseLoader(CParser, BaseConstructor, BaseResolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + BaseConstructor.__init__(self) + BaseResolver.__init__(self) + +class CSafeLoader(CParser, SafeConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + SafeConstructor.__init__(self) + Resolver.__init__(self) + +class CFullLoader(CParser, FullConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + FullConstructor.__init__(self) + Resolver.__init__(self) + +class CUnsafeLoader(CParser, UnsafeConstructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + UnsafeConstructor.__init__(self) + Resolver.__init__(self) + +class CLoader(CParser, Constructor, Resolver): + + def __init__(self, stream): + CParser.__init__(self, stream) + Constructor.__init__(self) + Resolver.__init__(self) + +class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class CSafeDumper(CEmitter, SafeRepresenter, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + SafeRepresenter.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class CDumper(CEmitter, Serializer, Representer, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + CEmitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, encoding=encoding, + allow_unicode=allow_unicode, line_break=line_break, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/dumper.py b/.venv_haddock/lib/python3.12/site-packages/yaml/dumper.py new file mode 100644 index 0000000000000000000000000000000000000000..6aadba551f3836b02f4752277f4b3027073defad --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/dumper.py @@ -0,0 +1,62 @@ + +__all__ = ['BaseDumper', 'SafeDumper', 'Dumper'] + +from .emitter import * +from .serializer import * +from .representer import * +from .resolver import * + +class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + SafeRepresenter.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + +class Dumper(Emitter, Serializer, Representer, Resolver): + + def __init__(self, stream, + default_style=None, default_flow_style=False, + canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None, + encoding=None, explicit_start=None, explicit_end=None, + version=None, tags=None, sort_keys=True): + Emitter.__init__(self, stream, canonical=canonical, + indent=indent, width=width, + allow_unicode=allow_unicode, line_break=line_break) + Serializer.__init__(self, encoding=encoding, + explicit_start=explicit_start, explicit_end=explicit_end, + version=version, tags=tags) + Representer.__init__(self, default_style=default_style, + default_flow_style=default_flow_style, sort_keys=sort_keys) + Resolver.__init__(self) + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/emitter.py b/.venv_haddock/lib/python3.12/site-packages/yaml/emitter.py new file mode 100644 index 0000000000000000000000000000000000000000..a664d011162af69184df2f8e59ab7feec818f7c7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/emitter.py @@ -0,0 +1,1137 @@ + +# Emitter expects events obeying the following grammar: +# stream ::= STREAM-START document* STREAM-END +# document ::= DOCUMENT-START node DOCUMENT-END +# node ::= SCALAR | sequence | mapping +# sequence ::= SEQUENCE-START node* SEQUENCE-END +# mapping ::= MAPPING-START (node node)* MAPPING-END + +__all__ = ['Emitter', 'EmitterError'] + +from .error import YAMLError +from .events import * + +class EmitterError(YAMLError): + pass + +class ScalarAnalysis: + def __init__(self, scalar, empty, multiline, + allow_flow_plain, allow_block_plain, + allow_single_quoted, allow_double_quoted, + allow_block): + self.scalar = scalar + self.empty = empty + self.multiline = multiline + self.allow_flow_plain = allow_flow_plain + self.allow_block_plain = allow_block_plain + self.allow_single_quoted = allow_single_quoted + self.allow_double_quoted = allow_double_quoted + self.allow_block = allow_block + +class Emitter: + + DEFAULT_TAG_PREFIXES = { + '!' : '!', + 'tag:yaml.org,2002:' : '!!', + } + + def __init__(self, stream, canonical=None, indent=None, width=None, + allow_unicode=None, line_break=None): + + # The stream should have the methods `write` and possibly `flush`. + self.stream = stream + + # Encoding can be overridden by STREAM-START. + self.encoding = None + + # Emitter is a state machine with a stack of states to handle nested + # structures. + self.states = [] + self.state = self.expect_stream_start + + # Current event and the event queue. + self.events = [] + self.event = None + + # The current indentation level and the stack of previous indents. + self.indents = [] + self.indent = None + + # Flow level. + self.flow_level = 0 + + # Contexts. + self.root_context = False + self.sequence_context = False + self.mapping_context = False + self.simple_key_context = False + + # Characteristics of the last emitted character: + # - current position. + # - is it a whitespace? + # - is it an indention character + # (indentation space, '-', '?', or ':')? + self.line = 0 + self.column = 0 + self.whitespace = True + self.indention = True + + # Whether the document requires an explicit document indicator + self.open_ended = False + + # Formatting details. + self.canonical = canonical + self.allow_unicode = allow_unicode + self.best_indent = 2 + if indent and 1 < indent < 10: + self.best_indent = indent + self.best_width = 80 + if width and width > self.best_indent*2: + self.best_width = width + self.best_line_break = '\n' + if line_break in ['\r', '\n', '\r\n']: + self.best_line_break = line_break + + # Tag prefixes. + self.tag_prefixes = None + + # Prepared anchor and tag. + self.prepared_anchor = None + self.prepared_tag = None + + # Scalar analysis and style. + self.analysis = None + self.style = None + + def dispose(self): + # Reset the state attributes (to clear self-references) + self.states = [] + self.state = None + + def emit(self, event): + self.events.append(event) + while not self.need_more_events(): + self.event = self.events.pop(0) + self.state() + self.event = None + + # In some cases, we wait for a few next events before emitting. + + def need_more_events(self): + if not self.events: + return True + event = self.events[0] + if isinstance(event, DocumentStartEvent): + return self.need_events(1) + elif isinstance(event, SequenceStartEvent): + return self.need_events(2) + elif isinstance(event, MappingStartEvent): + return self.need_events(3) + else: + return False + + def need_events(self, count): + level = 0 + for event in self.events[1:]: + if isinstance(event, (DocumentStartEvent, CollectionStartEvent)): + level += 1 + elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)): + level -= 1 + elif isinstance(event, StreamEndEvent): + level = -1 + if level < 0: + return False + return (len(self.events) < count+1) + + def increase_indent(self, flow=False, indentless=False): + self.indents.append(self.indent) + if self.indent is None: + if flow: + self.indent = self.best_indent + else: + self.indent = 0 + elif not indentless: + self.indent += self.best_indent + + # States. + + # Stream handlers. + + def expect_stream_start(self): + if isinstance(self.event, StreamStartEvent): + if self.event.encoding and not hasattr(self.stream, 'encoding'): + self.encoding = self.event.encoding + self.write_stream_start() + self.state = self.expect_first_document_start + else: + raise EmitterError("expected StreamStartEvent, but got %s" + % self.event) + + def expect_nothing(self): + raise EmitterError("expected nothing, but got %s" % self.event) + + # Document handlers. + + def expect_first_document_start(self): + return self.expect_document_start(first=True) + + def expect_document_start(self, first=False): + if isinstance(self.event, DocumentStartEvent): + if (self.event.version or self.event.tags) and self.open_ended: + self.write_indicator('...', True) + self.write_indent() + if self.event.version: + version_text = self.prepare_version(self.event.version) + self.write_version_directive(version_text) + self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy() + if self.event.tags: + handles = sorted(self.event.tags.keys()) + for handle in handles: + prefix = self.event.tags[handle] + self.tag_prefixes[prefix] = handle + handle_text = self.prepare_tag_handle(handle) + prefix_text = self.prepare_tag_prefix(prefix) + self.write_tag_directive(handle_text, prefix_text) + implicit = (first and not self.event.explicit and not self.canonical + and not self.event.version and not self.event.tags + and not self.check_empty_document()) + if not implicit: + self.write_indent() + self.write_indicator('---', True) + if self.canonical: + self.write_indent() + self.state = self.expect_document_root + elif isinstance(self.event, StreamEndEvent): + if self.open_ended: + self.write_indicator('...', True) + self.write_indent() + self.write_stream_end() + self.state = self.expect_nothing + else: + raise EmitterError("expected DocumentStartEvent, but got %s" + % self.event) + + def expect_document_end(self): + if isinstance(self.event, DocumentEndEvent): + self.write_indent() + if self.event.explicit: + self.write_indicator('...', True) + self.write_indent() + self.flush_stream() + self.state = self.expect_document_start + else: + raise EmitterError("expected DocumentEndEvent, but got %s" + % self.event) + + def expect_document_root(self): + self.states.append(self.expect_document_end) + self.expect_node(root=True) + + # Node handlers. + + def expect_node(self, root=False, sequence=False, mapping=False, + simple_key=False): + self.root_context = root + self.sequence_context = sequence + self.mapping_context = mapping + self.simple_key_context = simple_key + if isinstance(self.event, AliasEvent): + self.expect_alias() + elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): + self.process_anchor('&') + self.process_tag() + if isinstance(self.event, ScalarEvent): + self.expect_scalar() + elif isinstance(self.event, SequenceStartEvent): + if self.flow_level or self.canonical or self.event.flow_style \ + or self.check_empty_sequence(): + self.expect_flow_sequence() + else: + self.expect_block_sequence() + elif isinstance(self.event, MappingStartEvent): + if self.flow_level or self.canonical or self.event.flow_style \ + or self.check_empty_mapping(): + self.expect_flow_mapping() + else: + self.expect_block_mapping() + else: + raise EmitterError("expected NodeEvent, but got %s" % self.event) + + def expect_alias(self): + if self.event.anchor is None: + raise EmitterError("anchor is not specified for alias") + self.process_anchor('*') + self.state = self.states.pop() + + def expect_scalar(self): + self.increase_indent(flow=True) + self.process_scalar() + self.indent = self.indents.pop() + self.state = self.states.pop() + + # Flow sequence handlers. + + def expect_flow_sequence(self): + self.write_indicator('[', True, whitespace=True) + self.flow_level += 1 + self.increase_indent(flow=True) + self.state = self.expect_first_flow_sequence_item + + def expect_first_flow_sequence_item(self): + if isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + self.write_indicator(']', False) + self.state = self.states.pop() + else: + if self.canonical or self.column > self.best_width: + self.write_indent() + self.states.append(self.expect_flow_sequence_item) + self.expect_node(sequence=True) + + def expect_flow_sequence_item(self): + if isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + if self.canonical: + self.write_indicator(',', False) + self.write_indent() + self.write_indicator(']', False) + self.state = self.states.pop() + else: + self.write_indicator(',', False) + if self.canonical or self.column > self.best_width: + self.write_indent() + self.states.append(self.expect_flow_sequence_item) + self.expect_node(sequence=True) + + # Flow mapping handlers. + + def expect_flow_mapping(self): + self.write_indicator('{', True, whitespace=True) + self.flow_level += 1 + self.increase_indent(flow=True) + self.state = self.expect_first_flow_mapping_key + + def expect_first_flow_mapping_key(self): + if isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + self.write_indicator('}', False) + self.state = self.states.pop() + else: + if self.canonical or self.column > self.best_width: + self.write_indent() + if not self.canonical and self.check_simple_key(): + self.states.append(self.expect_flow_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True) + self.states.append(self.expect_flow_mapping_value) + self.expect_node(mapping=True) + + def expect_flow_mapping_key(self): + if isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.flow_level -= 1 + if self.canonical: + self.write_indicator(',', False) + self.write_indent() + self.write_indicator('}', False) + self.state = self.states.pop() + else: + self.write_indicator(',', False) + if self.canonical or self.column > self.best_width: + self.write_indent() + if not self.canonical and self.check_simple_key(): + self.states.append(self.expect_flow_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True) + self.states.append(self.expect_flow_mapping_value) + self.expect_node(mapping=True) + + def expect_flow_mapping_simple_value(self): + self.write_indicator(':', False) + self.states.append(self.expect_flow_mapping_key) + self.expect_node(mapping=True) + + def expect_flow_mapping_value(self): + if self.canonical or self.column > self.best_width: + self.write_indent() + self.write_indicator(':', True) + self.states.append(self.expect_flow_mapping_key) + self.expect_node(mapping=True) + + # Block sequence handlers. + + def expect_block_sequence(self): + indentless = (self.mapping_context and not self.indention) + self.increase_indent(flow=False, indentless=indentless) + self.state = self.expect_first_block_sequence_item + + def expect_first_block_sequence_item(self): + return self.expect_block_sequence_item(first=True) + + def expect_block_sequence_item(self, first=False): + if not first and isinstance(self.event, SequenceEndEvent): + self.indent = self.indents.pop() + self.state = self.states.pop() + else: + self.write_indent() + self.write_indicator('-', True, indention=True) + self.states.append(self.expect_block_sequence_item) + self.expect_node(sequence=True) + + # Block mapping handlers. + + def expect_block_mapping(self): + self.increase_indent(flow=False) + self.state = self.expect_first_block_mapping_key + + def expect_first_block_mapping_key(self): + return self.expect_block_mapping_key(first=True) + + def expect_block_mapping_key(self, first=False): + if not first and isinstance(self.event, MappingEndEvent): + self.indent = self.indents.pop() + self.state = self.states.pop() + else: + self.write_indent() + if self.check_simple_key(): + self.states.append(self.expect_block_mapping_simple_value) + self.expect_node(mapping=True, simple_key=True) + else: + self.write_indicator('?', True, indention=True) + self.states.append(self.expect_block_mapping_value) + self.expect_node(mapping=True) + + def expect_block_mapping_simple_value(self): + self.write_indicator(':', False) + self.states.append(self.expect_block_mapping_key) + self.expect_node(mapping=True) + + def expect_block_mapping_value(self): + self.write_indent() + self.write_indicator(':', True, indention=True) + self.states.append(self.expect_block_mapping_key) + self.expect_node(mapping=True) + + # Checkers. + + def check_empty_sequence(self): + return (isinstance(self.event, SequenceStartEvent) and self.events + and isinstance(self.events[0], SequenceEndEvent)) + + def check_empty_mapping(self): + return (isinstance(self.event, MappingStartEvent) and self.events + and isinstance(self.events[0], MappingEndEvent)) + + def check_empty_document(self): + if not isinstance(self.event, DocumentStartEvent) or not self.events: + return False + event = self.events[0] + return (isinstance(event, ScalarEvent) and event.anchor is None + and event.tag is None and event.implicit and event.value == '') + + def check_simple_key(self): + length = 0 + if isinstance(self.event, NodeEvent) and self.event.anchor is not None: + if self.prepared_anchor is None: + self.prepared_anchor = self.prepare_anchor(self.event.anchor) + length += len(self.prepared_anchor) + if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \ + and self.event.tag is not None: + if self.prepared_tag is None: + self.prepared_tag = self.prepare_tag(self.event.tag) + length += len(self.prepared_tag) + if isinstance(self.event, ScalarEvent): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + length += len(self.analysis.scalar) + return (length < 128 and (isinstance(self.event, AliasEvent) + or (isinstance(self.event, ScalarEvent) + and not self.analysis.empty and not self.analysis.multiline) + or self.check_empty_sequence() or self.check_empty_mapping())) + + # Anchor, Tag, and Scalar processors. + + def process_anchor(self, indicator): + if self.event.anchor is None: + self.prepared_anchor = None + return + if self.prepared_anchor is None: + self.prepared_anchor = self.prepare_anchor(self.event.anchor) + if self.prepared_anchor: + self.write_indicator(indicator+self.prepared_anchor, True) + self.prepared_anchor = None + + def process_tag(self): + tag = self.event.tag + if isinstance(self.event, ScalarEvent): + if self.style is None: + self.style = self.choose_scalar_style() + if ((not self.canonical or tag is None) and + ((self.style == '' and self.event.implicit[0]) + or (self.style != '' and self.event.implicit[1]))): + self.prepared_tag = None + return + if self.event.implicit[0] and tag is None: + tag = '!' + self.prepared_tag = None + else: + if (not self.canonical or tag is None) and self.event.implicit: + self.prepared_tag = None + return + if tag is None: + raise EmitterError("tag is not specified") + if self.prepared_tag is None: + self.prepared_tag = self.prepare_tag(tag) + if self.prepared_tag: + self.write_indicator(self.prepared_tag, True) + self.prepared_tag = None + + def choose_scalar_style(self): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + if self.event.style == '"' or self.canonical: + return '"' + if not self.event.style and self.event.implicit[0]: + if (not (self.simple_key_context and + (self.analysis.empty or self.analysis.multiline)) + and (self.flow_level and self.analysis.allow_flow_plain + or (not self.flow_level and self.analysis.allow_block_plain))): + return '' + if self.event.style and self.event.style in '|>': + if (not self.flow_level and not self.simple_key_context + and self.analysis.allow_block): + return self.event.style + if not self.event.style or self.event.style == '\'': + if (self.analysis.allow_single_quoted and + not (self.simple_key_context and self.analysis.multiline)): + return '\'' + return '"' + + def process_scalar(self): + if self.analysis is None: + self.analysis = self.analyze_scalar(self.event.value) + if self.style is None: + self.style = self.choose_scalar_style() + split = (not self.simple_key_context) + #if self.analysis.multiline and split \ + # and (not self.style or self.style in '\'\"'): + # self.write_indent() + if self.style == '"': + self.write_double_quoted(self.analysis.scalar, split) + elif self.style == '\'': + self.write_single_quoted(self.analysis.scalar, split) + elif self.style == '>': + self.write_folded(self.analysis.scalar) + elif self.style == '|': + self.write_literal(self.analysis.scalar) + else: + self.write_plain(self.analysis.scalar, split) + self.analysis = None + self.style = None + + # Analyzers. + + def prepare_version(self, version): + major, minor = version + if major != 1: + raise EmitterError("unsupported YAML version: %d.%d" % (major, minor)) + return '%d.%d' % (major, minor) + + def prepare_tag_handle(self, handle): + if not handle: + raise EmitterError("tag handle must not be empty") + if handle[0] != '!' or handle[-1] != '!': + raise EmitterError("tag handle must start and end with '!': %r" % handle) + for ch in handle[1:-1]: + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): + raise EmitterError("invalid character %r in the tag handle: %r" + % (ch, handle)) + return handle + + def prepare_tag_prefix(self, prefix): + if not prefix: + raise EmitterError("tag prefix must not be empty") + chunks = [] + start = end = 0 + if prefix[0] == '!': + end = 1 + while end < len(prefix): + ch = prefix[end] + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?!:@&=+$,_.~*\'()[]': + end += 1 + else: + if start < end: + chunks.append(prefix[start:end]) + start = end = end+1 + data = ch.encode('utf-8') + for ch in data: + chunks.append('%%%02X' % ord(ch)) + if start < end: + chunks.append(prefix[start:end]) + return ''.join(chunks) + + def prepare_tag(self, tag): + if not tag: + raise EmitterError("tag must not be empty") + if tag == '!': + return tag + handle = None + suffix = tag + prefixes = sorted(self.tag_prefixes.keys()) + for prefix in prefixes: + if tag.startswith(prefix) \ + and (prefix == '!' or len(prefix) < len(tag)): + handle = self.tag_prefixes[prefix] + suffix = tag[len(prefix):] + chunks = [] + start = end = 0 + while end < len(suffix): + ch = suffix[end] + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.~*\'()[]' \ + or (ch == '!' and handle != '!'): + end += 1 + else: + if start < end: + chunks.append(suffix[start:end]) + start = end = end+1 + data = ch.encode('utf-8') + for ch in data: + chunks.append('%%%02X' % ch) + if start < end: + chunks.append(suffix[start:end]) + suffix_text = ''.join(chunks) + if handle: + return '%s%s' % (handle, suffix_text) + else: + return '!<%s>' % suffix_text + + def prepare_anchor(self, anchor): + if not anchor: + raise EmitterError("anchor must not be empty") + for ch in anchor: + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): + raise EmitterError("invalid character %r in the anchor: %r" + % (ch, anchor)) + return anchor + + def analyze_scalar(self, scalar): + + # Empty scalar is a special case. + if not scalar: + return ScalarAnalysis(scalar=scalar, empty=True, multiline=False, + allow_flow_plain=False, allow_block_plain=True, + allow_single_quoted=True, allow_double_quoted=True, + allow_block=False) + + # Indicators and special characters. + block_indicators = False + flow_indicators = False + line_breaks = False + special_characters = False + + # Important whitespace combinations. + leading_space = False + leading_break = False + trailing_space = False + trailing_break = False + break_space = False + space_break = False + + # Check document indicators. + if scalar.startswith('---') or scalar.startswith('...'): + block_indicators = True + flow_indicators = True + + # First character or preceded by a whitespace. + preceded_by_whitespace = True + + # Last character or followed by a whitespace. + followed_by_whitespace = (len(scalar) == 1 or + scalar[1] in '\0 \t\r\n\x85\u2028\u2029') + + # The previous character is a space. + previous_space = False + + # The previous character is a break. + previous_break = False + + index = 0 + while index < len(scalar): + ch = scalar[index] + + # Check for indicators. + if index == 0: + # Leading indicators are special characters. + if ch in '#,[]{}&*!|>\'\"%@`': + flow_indicators = True + block_indicators = True + if ch in '?:': + flow_indicators = True + if followed_by_whitespace: + block_indicators = True + if ch == '-' and followed_by_whitespace: + flow_indicators = True + block_indicators = True + else: + # Some indicators cannot appear within a scalar as well. + if ch in ',?[]{}': + flow_indicators = True + if ch == ':': + flow_indicators = True + if followed_by_whitespace: + block_indicators = True + if ch == '#' and preceded_by_whitespace: + flow_indicators = True + block_indicators = True + + # Check for line breaks, special, and unicode characters. + if ch in '\n\x85\u2028\u2029': + line_breaks = True + if not (ch == '\n' or '\x20' <= ch <= '\x7E'): + if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD' + or '\U00010000' <= ch < '\U0010ffff') and ch != '\uFEFF': + unicode_characters = True + if not self.allow_unicode: + special_characters = True + else: + special_characters = True + + # Detect important whitespace combinations. + if ch == ' ': + if index == 0: + leading_space = True + if index == len(scalar)-1: + trailing_space = True + if previous_break: + break_space = True + previous_space = True + previous_break = False + elif ch in '\n\x85\u2028\u2029': + if index == 0: + leading_break = True + if index == len(scalar)-1: + trailing_break = True + if previous_space: + space_break = True + previous_space = False + previous_break = True + else: + previous_space = False + previous_break = False + + # Prepare for the next character. + index += 1 + preceded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029') + followed_by_whitespace = (index+1 >= len(scalar) or + scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029') + + # Let's decide what styles are allowed. + allow_flow_plain = True + allow_block_plain = True + allow_single_quoted = True + allow_double_quoted = True + allow_block = True + + # Leading and trailing whitespaces are bad for plain scalars. + if (leading_space or leading_break + or trailing_space or trailing_break): + allow_flow_plain = allow_block_plain = False + + # We do not permit trailing spaces for block scalars. + if trailing_space: + allow_block = False + + # Spaces at the beginning of a new line are only acceptable for block + # scalars. + if break_space: + allow_flow_plain = allow_block_plain = allow_single_quoted = False + + # Spaces followed by breaks, as well as special character are only + # allowed for double quoted scalars. + if space_break or special_characters: + allow_flow_plain = allow_block_plain = \ + allow_single_quoted = allow_block = False + + # Although the plain scalar writer supports breaks, we never emit + # multiline plain scalars. + if line_breaks: + allow_flow_plain = allow_block_plain = False + + # Flow indicators are forbidden for flow plain scalars. + if flow_indicators: + allow_flow_plain = False + + # Block indicators are forbidden for block plain scalars. + if block_indicators: + allow_block_plain = False + + return ScalarAnalysis(scalar=scalar, + empty=False, multiline=line_breaks, + allow_flow_plain=allow_flow_plain, + allow_block_plain=allow_block_plain, + allow_single_quoted=allow_single_quoted, + allow_double_quoted=allow_double_quoted, + allow_block=allow_block) + + # Writers. + + def flush_stream(self): + if hasattr(self.stream, 'flush'): + self.stream.flush() + + def write_stream_start(self): + # Write BOM if needed. + if self.encoding and self.encoding.startswith('utf-16'): + self.stream.write('\uFEFF'.encode(self.encoding)) + + def write_stream_end(self): + self.flush_stream() + + def write_indicator(self, indicator, need_whitespace, + whitespace=False, indention=False): + if self.whitespace or not need_whitespace: + data = indicator + else: + data = ' '+indicator + self.whitespace = whitespace + self.indention = self.indention and indention + self.column += len(data) + self.open_ended = False + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_indent(self): + indent = self.indent or 0 + if not self.indention or self.column > indent \ + or (self.column == indent and not self.whitespace): + self.write_line_break() + if self.column < indent: + self.whitespace = True + data = ' '*(indent-self.column) + self.column = indent + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_line_break(self, data=None): + if data is None: + data = self.best_line_break + self.whitespace = True + self.indention = True + self.line += 1 + self.column = 0 + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + + def write_version_directive(self, version_text): + data = '%%YAML %s' % version_text + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_line_break() + + def write_tag_directive(self, handle_text, prefix_text): + data = '%%TAG %s %s' % (handle_text, prefix_text) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_line_break() + + # Scalar streams. + + def write_single_quoted(self, text, split=True): + self.write_indicator('\'', True) + spaces = False + breaks = False + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if spaces: + if ch is None or ch != ' ': + if start+1 == end and self.column > self.best_width and split \ + and start != 0 and end != len(text): + self.write_indent() + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + elif breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': + self.write_line_break() + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + self.write_indent() + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'': + if start < end: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch == '\'': + data = '\'\'' + self.column += 2 + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + 1 + if ch is not None: + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 + self.write_indicator('\'', False) + + ESCAPE_REPLACEMENTS = { + '\0': '0', + '\x07': 'a', + '\x08': 'b', + '\x09': 't', + '\x0A': 'n', + '\x0B': 'v', + '\x0C': 'f', + '\x0D': 'r', + '\x1B': 'e', + '\"': '\"', + '\\': '\\', + '\x85': 'N', + '\xA0': '_', + '\u2028': 'L', + '\u2029': 'P', + } + + def write_double_quoted(self, text, split=True): + self.write_indicator('"', True) + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \ + or not ('\x20' <= ch <= '\x7E' + or (self.allow_unicode + and ('\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD'))): + if start < end: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch is not None: + if ch in self.ESCAPE_REPLACEMENTS: + data = '\\'+self.ESCAPE_REPLACEMENTS[ch] + elif ch <= '\xFF': + data = '\\x%02X' % ord(ch) + elif ch <= '\uFFFF': + data = '\\u%04X' % ord(ch) + else: + data = '\\U%08X' % ord(ch) + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end+1 + if 0 < end < len(text)-1 and (ch == ' ' or start >= end) \ + and self.column+(end-start) > self.best_width and split: + data = text[start:end]+'\\' + if start < end: + start = end + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.write_indent() + self.whitespace = False + self.indention = False + if text[start] == ' ': + data = '\\' + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + end += 1 + self.write_indicator('"', False) + + def determine_block_hints(self, text): + hints = '' + if text: + if text[0] in ' \n\x85\u2028\u2029': + hints += str(self.best_indent) + if text[-1] not in '\n\x85\u2028\u2029': + hints += '-' + elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029': + hints += '+' + return hints + + def write_folded(self, text): + hints = self.determine_block_hints(text) + self.write_indicator('>'+hints, True) + if hints[-1:] == '+': + self.open_ended = True + self.write_line_break() + leading_space = True + spaces = False + breaks = True + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + if not leading_space and ch is not None and ch != ' ' \ + and text[start] == '\n': + self.write_line_break() + leading_space = (ch == ' ') + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + if ch is not None: + self.write_indent() + start = end + elif spaces: + if ch != ' ': + if start+1 == end and self.column > self.best_width: + self.write_indent() + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029': + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + if ch is None: + self.write_line_break() + start = end + if ch is not None: + breaks = (ch in '\n\x85\u2028\u2029') + spaces = (ch == ' ') + end += 1 + + def write_literal(self, text): + hints = self.determine_block_hints(text) + self.write_indicator('|'+hints, True) + if hints[-1:] == '+': + self.open_ended = True + self.write_line_break() + breaks = True + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if breaks: + if ch is None or ch not in '\n\x85\u2028\u2029': + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + if ch is not None: + self.write_indent() + start = end + else: + if ch is None or ch in '\n\x85\u2028\u2029': + data = text[start:end] + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + if ch is None: + self.write_line_break() + start = end + if ch is not None: + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 + + def write_plain(self, text, split=True): + if self.root_context: + self.open_ended = True + if not text: + return + if not self.whitespace: + data = ' ' + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + self.whitespace = False + self.indention = False + spaces = False + breaks = False + start = end = 0 + while end <= len(text): + ch = None + if end < len(text): + ch = text[end] + if spaces: + if ch != ' ': + if start+1 == end and self.column > self.best_width and split: + self.write_indent() + self.whitespace = False + self.indention = False + else: + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + elif breaks: + if ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': + self.write_line_break() + for br in text[start:end]: + if br == '\n': + self.write_line_break() + else: + self.write_line_break(br) + self.write_indent() + self.whitespace = False + self.indention = False + start = end + else: + if ch is None or ch in ' \n\x85\u2028\u2029': + data = text[start:end] + self.column += len(data) + if self.encoding: + data = data.encode(self.encoding) + self.stream.write(data) + start = end + if ch is not None: + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') + end += 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/error.py b/.venv_haddock/lib/python3.12/site-packages/yaml/error.py new file mode 100644 index 0000000000000000000000000000000000000000..b796b4dc519512c4825ff539a2e6aa20f4d370d0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/error.py @@ -0,0 +1,75 @@ + +__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] + +class Mark: + + def __init__(self, name, index, line, column, buffer, pointer): + self.name = name + self.index = index + self.line = line + self.column = column + self.buffer = buffer + self.pointer = pointer + + def get_snippet(self, indent=4, max_length=75): + if self.buffer is None: + return None + head = '' + start = self.pointer + while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': + start -= 1 + if self.pointer-start > max_length/2-1: + head = ' ... ' + start += 5 + break + tail = '' + end = self.pointer + while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': + end += 1 + if end-self.pointer > max_length/2-1: + tail = ' ... ' + end -= 5 + break + snippet = self.buffer[start:end] + return ' '*indent + head + snippet + tail + '\n' \ + + ' '*(indent+self.pointer-start+len(head)) + '^' + + def __str__(self): + snippet = self.get_snippet() + where = " in \"%s\", line %d, column %d" \ + % (self.name, self.line+1, self.column+1) + if snippet is not None: + where += ":\n"+snippet + return where + +class YAMLError(Exception): + pass + +class MarkedYAMLError(YAMLError): + + def __init__(self, context=None, context_mark=None, + problem=None, problem_mark=None, note=None): + self.context = context + self.context_mark = context_mark + self.problem = problem + self.problem_mark = problem_mark + self.note = note + + def __str__(self): + lines = [] + if self.context is not None: + lines.append(self.context) + if self.context_mark is not None \ + and (self.problem is None or self.problem_mark is None + or self.context_mark.name != self.problem_mark.name + or self.context_mark.line != self.problem_mark.line + or self.context_mark.column != self.problem_mark.column): + lines.append(str(self.context_mark)) + if self.problem is not None: + lines.append(self.problem) + if self.problem_mark is not None: + lines.append(str(self.problem_mark)) + if self.note is not None: + lines.append(self.note) + return '\n'.join(lines) + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/events.py b/.venv_haddock/lib/python3.12/site-packages/yaml/events.py new file mode 100644 index 0000000000000000000000000000000000000000..f79ad389cb6c9517e391dcd25534866bc9ccd36a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/events.py @@ -0,0 +1,86 @@ + +# Abstract classes. + +class Event(object): + def __init__(self, start_mark=None, end_mark=None): + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + attributes = [key for key in ['anchor', 'tag', 'implicit', 'value'] + if hasattr(self, key)] + arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) + for key in attributes]) + return '%s(%s)' % (self.__class__.__name__, arguments) + +class NodeEvent(Event): + def __init__(self, anchor, start_mark=None, end_mark=None): + self.anchor = anchor + self.start_mark = start_mark + self.end_mark = end_mark + +class CollectionStartEvent(NodeEvent): + def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None, + flow_style=None): + self.anchor = anchor + self.tag = tag + self.implicit = implicit + self.start_mark = start_mark + self.end_mark = end_mark + self.flow_style = flow_style + +class CollectionEndEvent(Event): + pass + +# Implementations. + +class StreamStartEvent(Event): + def __init__(self, start_mark=None, end_mark=None, encoding=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.encoding = encoding + +class StreamEndEvent(Event): + pass + +class DocumentStartEvent(Event): + def __init__(self, start_mark=None, end_mark=None, + explicit=None, version=None, tags=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.explicit = explicit + self.version = version + self.tags = tags + +class DocumentEndEvent(Event): + def __init__(self, start_mark=None, end_mark=None, + explicit=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.explicit = explicit + +class AliasEvent(NodeEvent): + pass + +class ScalarEvent(NodeEvent): + def __init__(self, anchor, tag, implicit, value, + start_mark=None, end_mark=None, style=None): + self.anchor = anchor + self.tag = tag + self.implicit = implicit + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + +class SequenceStartEvent(CollectionStartEvent): + pass + +class SequenceEndEvent(CollectionEndEvent): + pass + +class MappingStartEvent(CollectionStartEvent): + pass + +class MappingEndEvent(CollectionEndEvent): + pass + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/loader.py b/.venv_haddock/lib/python3.12/site-packages/yaml/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..e90c11224c38e559cdf0cb205f0692ebd4fb8681 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/loader.py @@ -0,0 +1,63 @@ + +__all__ = ['BaseLoader', 'FullLoader', 'SafeLoader', 'Loader', 'UnsafeLoader'] + +from .reader import * +from .scanner import * +from .parser import * +from .composer import * +from .constructor import * +from .resolver import * + +class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + BaseConstructor.__init__(self) + BaseResolver.__init__(self) + +class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + FullConstructor.__init__(self) + Resolver.__init__(self) + +class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + SafeConstructor.__init__(self) + Resolver.__init__(self) + +class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + Constructor.__init__(self) + Resolver.__init__(self) + +# UnsafeLoader is the same as Loader (which is and was always unsafe on +# untrusted input). Use of either Loader or UnsafeLoader should be rare, since +# FullLoad should be able to load almost all YAML safely. Loader is left intact +# to ensure backwards compatibility. +class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + + def __init__(self, stream): + Reader.__init__(self, stream) + Scanner.__init__(self) + Parser.__init__(self) + Composer.__init__(self) + Constructor.__init__(self) + Resolver.__init__(self) diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/nodes.py b/.venv_haddock/lib/python3.12/site-packages/yaml/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..c4f070c41e1fb1bc01af27d69329e92dded38908 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/nodes.py @@ -0,0 +1,49 @@ + +class Node(object): + def __init__(self, tag, value, start_mark, end_mark): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + value = self.value + #if isinstance(value, list): + # if len(value) == 0: + # value = '' + # elif len(value) == 1: + # value = '<1 item>' + # else: + # value = '<%d items>' % len(value) + #else: + # if len(value) > 75: + # value = repr(value[:70]+u' ... ') + # else: + # value = repr(value) + value = repr(value) + return '%s(tag=%r, value=%s)' % (self.__class__.__name__, self.tag, value) + +class ScalarNode(Node): + id = 'scalar' + def __init__(self, tag, value, + start_mark=None, end_mark=None, style=None): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style + +class CollectionNode(Node): + def __init__(self, tag, value, + start_mark=None, end_mark=None, flow_style=None): + self.tag = tag + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + self.flow_style = flow_style + +class SequenceNode(CollectionNode): + id = 'sequence' + +class MappingNode(CollectionNode): + id = 'mapping' + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/parser.py b/.venv_haddock/lib/python3.12/site-packages/yaml/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..13a5995d292045d0f865a99abf692bd35dc87814 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/parser.py @@ -0,0 +1,589 @@ + +# The following YAML grammar is LL(1) and is parsed by a recursive descent +# parser. +# +# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END +# implicit_document ::= block_node DOCUMENT-END* +# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* +# block_node_or_indentless_sequence ::= +# ALIAS +# | properties (block_content | indentless_block_sequence)? +# | block_content +# | indentless_block_sequence +# block_node ::= ALIAS +# | properties block_content? +# | block_content +# flow_node ::= ALIAS +# | properties flow_content? +# | flow_content +# properties ::= TAG ANCHOR? | ANCHOR TAG? +# block_content ::= block_collection | flow_collection | SCALAR +# flow_content ::= flow_collection | SCALAR +# block_collection ::= block_sequence | block_mapping +# flow_collection ::= flow_sequence | flow_mapping +# block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END +# indentless_sequence ::= (BLOCK-ENTRY block_node?)+ +# block_mapping ::= BLOCK-MAPPING_START +# ((KEY block_node_or_indentless_sequence?)? +# (VALUE block_node_or_indentless_sequence?)?)* +# BLOCK-END +# flow_sequence ::= FLOW-SEQUENCE-START +# (flow_sequence_entry FLOW-ENTRY)* +# flow_sequence_entry? +# FLOW-SEQUENCE-END +# flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +# flow_mapping ::= FLOW-MAPPING-START +# (flow_mapping_entry FLOW-ENTRY)* +# flow_mapping_entry? +# FLOW-MAPPING-END +# flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? +# +# FIRST sets: +# +# stream: { STREAM-START } +# explicit_document: { DIRECTIVE DOCUMENT-START } +# implicit_document: FIRST(block_node) +# block_node: { ALIAS TAG ANCHOR SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START } +# flow_node: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START } +# block_content: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } +# flow_content: { FLOW-SEQUENCE-START FLOW-MAPPING-START SCALAR } +# block_collection: { BLOCK-SEQUENCE-START BLOCK-MAPPING-START } +# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } +# block_sequence: { BLOCK-SEQUENCE-START } +# block_mapping: { BLOCK-MAPPING-START } +# block_node_or_indentless_sequence: { ALIAS ANCHOR TAG SCALAR BLOCK-SEQUENCE-START BLOCK-MAPPING-START FLOW-SEQUENCE-START FLOW-MAPPING-START BLOCK-ENTRY } +# indentless_sequence: { ENTRY } +# flow_collection: { FLOW-SEQUENCE-START FLOW-MAPPING-START } +# flow_sequence: { FLOW-SEQUENCE-START } +# flow_mapping: { FLOW-MAPPING-START } +# flow_sequence_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } +# flow_mapping_entry: { ALIAS ANCHOR TAG SCALAR FLOW-SEQUENCE-START FLOW-MAPPING-START KEY } + +__all__ = ['Parser', 'ParserError'] + +from .error import MarkedYAMLError +from .tokens import * +from .events import * +from .scanner import * + +class ParserError(MarkedYAMLError): + pass + +class Parser: + # Since writing a recursive-descendant parser is a straightforward task, we + # do not give many comments here. + + DEFAULT_TAGS = { + '!': '!', + '!!': 'tag:yaml.org,2002:', + } + + def __init__(self): + self.current_event = None + self.yaml_version = None + self.tag_handles = {} + self.states = [] + self.marks = [] + self.state = self.parse_stream_start + + def dispose(self): + # Reset the state attributes (to clear self-references) + self.states = [] + self.state = None + + def check_event(self, *choices): + # Check the type of the next event. + if self.current_event is None: + if self.state: + self.current_event = self.state() + if self.current_event is not None: + if not choices: + return True + for choice in choices: + if isinstance(self.current_event, choice): + return True + return False + + def peek_event(self): + # Get the next event. + if self.current_event is None: + if self.state: + self.current_event = self.state() + return self.current_event + + def get_event(self): + # Get the next event and proceed further. + if self.current_event is None: + if self.state: + self.current_event = self.state() + value = self.current_event + self.current_event = None + return value + + # stream ::= STREAM-START implicit_document? explicit_document* STREAM-END + # implicit_document ::= block_node DOCUMENT-END* + # explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* + + def parse_stream_start(self): + + # Parse the stream start. + token = self.get_token() + event = StreamStartEvent(token.start_mark, token.end_mark, + encoding=token.encoding) + + # Prepare the next state. + self.state = self.parse_implicit_document_start + + return event + + def parse_implicit_document_start(self): + + # Parse an implicit document. + if not self.check_token(DirectiveToken, DocumentStartToken, + StreamEndToken): + self.tag_handles = self.DEFAULT_TAGS + token = self.peek_token() + start_mark = end_mark = token.start_mark + event = DocumentStartEvent(start_mark, end_mark, + explicit=False) + + # Prepare the next state. + self.states.append(self.parse_document_end) + self.state = self.parse_block_node + + return event + + else: + return self.parse_document_start() + + def parse_document_start(self): + + # Parse any extra document end indicators. + while self.check_token(DocumentEndToken): + self.get_token() + + # Parse an explicit document. + if not self.check_token(StreamEndToken): + token = self.peek_token() + start_mark = token.start_mark + version, tags = self.process_directives() + if not self.check_token(DocumentStartToken): + raise ParserError(None, None, + "expected '', but found %r" + % self.peek_token().id, + self.peek_token().start_mark) + token = self.get_token() + end_mark = token.end_mark + event = DocumentStartEvent(start_mark, end_mark, + explicit=True, version=version, tags=tags) + self.states.append(self.parse_document_end) + self.state = self.parse_document_content + else: + # Parse the end of the stream. + token = self.get_token() + event = StreamEndEvent(token.start_mark, token.end_mark) + assert not self.states + assert not self.marks + self.state = None + return event + + def parse_document_end(self): + + # Parse the document end. + token = self.peek_token() + start_mark = end_mark = token.start_mark + explicit = False + if self.check_token(DocumentEndToken): + token = self.get_token() + end_mark = token.end_mark + explicit = True + event = DocumentEndEvent(start_mark, end_mark, + explicit=explicit) + + # Prepare the next state. + self.state = self.parse_document_start + + return event + + def parse_document_content(self): + if self.check_token(DirectiveToken, + DocumentStartToken, DocumentEndToken, StreamEndToken): + event = self.process_empty_scalar(self.peek_token().start_mark) + self.state = self.states.pop() + return event + else: + return self.parse_block_node() + + def process_directives(self): + self.yaml_version = None + self.tag_handles = {} + while self.check_token(DirectiveToken): + token = self.get_token() + if token.name == 'YAML': + if self.yaml_version is not None: + raise ParserError(None, None, + "found duplicate YAML directive", token.start_mark) + major, minor = token.value + if major != 1: + raise ParserError(None, None, + "found incompatible YAML document (version 1.* is required)", + token.start_mark) + self.yaml_version = token.value + elif token.name == 'TAG': + handle, prefix = token.value + if handle in self.tag_handles: + raise ParserError(None, None, + "duplicate tag handle %r" % handle, + token.start_mark) + self.tag_handles[handle] = prefix + if self.tag_handles: + value = self.yaml_version, self.tag_handles.copy() + else: + value = self.yaml_version, None + for key in self.DEFAULT_TAGS: + if key not in self.tag_handles: + self.tag_handles[key] = self.DEFAULT_TAGS[key] + return value + + # block_node_or_indentless_sequence ::= ALIAS + # | properties (block_content | indentless_block_sequence)? + # | block_content + # | indentless_block_sequence + # block_node ::= ALIAS + # | properties block_content? + # | block_content + # flow_node ::= ALIAS + # | properties flow_content? + # | flow_content + # properties ::= TAG ANCHOR? | ANCHOR TAG? + # block_content ::= block_collection | flow_collection | SCALAR + # flow_content ::= flow_collection | SCALAR + # block_collection ::= block_sequence | block_mapping + # flow_collection ::= flow_sequence | flow_mapping + + def parse_block_node(self): + return self.parse_node(block=True) + + def parse_flow_node(self): + return self.parse_node() + + def parse_block_node_or_indentless_sequence(self): + return self.parse_node(block=True, indentless_sequence=True) + + def parse_node(self, block=False, indentless_sequence=False): + if self.check_token(AliasToken): + token = self.get_token() + event = AliasEvent(token.value, token.start_mark, token.end_mark) + self.state = self.states.pop() + else: + anchor = None + tag = None + start_mark = end_mark = tag_mark = None + if self.check_token(AnchorToken): + token = self.get_token() + start_mark = token.start_mark + end_mark = token.end_mark + anchor = token.value + if self.check_token(TagToken): + token = self.get_token() + tag_mark = token.start_mark + end_mark = token.end_mark + tag = token.value + elif self.check_token(TagToken): + token = self.get_token() + start_mark = tag_mark = token.start_mark + end_mark = token.end_mark + tag = token.value + if self.check_token(AnchorToken): + token = self.get_token() + end_mark = token.end_mark + anchor = token.value + if tag is not None: + handle, suffix = tag + if handle is not None: + if handle not in self.tag_handles: + raise ParserError("while parsing a node", start_mark, + "found undefined tag handle %r" % handle, + tag_mark) + tag = self.tag_handles[handle]+suffix + else: + tag = suffix + #if tag == '!': + # raise ParserError("while parsing a node", start_mark, + # "found non-specific tag '!'", tag_mark, + # "Please check 'http://pyyaml.org/wiki/YAMLNonSpecificTag' and share your opinion.") + if start_mark is None: + start_mark = end_mark = self.peek_token().start_mark + event = None + implicit = (tag is None or tag == '!') + if indentless_sequence and self.check_token(BlockEntryToken): + end_mark = self.peek_token().end_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark) + self.state = self.parse_indentless_sequence_entry + else: + if self.check_token(ScalarToken): + token = self.get_token() + end_mark = token.end_mark + if (token.plain and tag is None) or tag == '!': + implicit = (True, False) + elif tag is None: + implicit = (False, True) + else: + implicit = (False, False) + event = ScalarEvent(anchor, tag, implicit, token.value, + start_mark, end_mark, style=token.style) + self.state = self.states.pop() + elif self.check_token(FlowSequenceStartToken): + end_mark = self.peek_token().end_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=True) + self.state = self.parse_flow_sequence_first_entry + elif self.check_token(FlowMappingStartToken): + end_mark = self.peek_token().end_mark + event = MappingStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=True) + self.state = self.parse_flow_mapping_first_key + elif block and self.check_token(BlockSequenceStartToken): + end_mark = self.peek_token().start_mark + event = SequenceStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=False) + self.state = self.parse_block_sequence_first_entry + elif block and self.check_token(BlockMappingStartToken): + end_mark = self.peek_token().start_mark + event = MappingStartEvent(anchor, tag, implicit, + start_mark, end_mark, flow_style=False) + self.state = self.parse_block_mapping_first_key + elif anchor is not None or tag is not None: + # Empty scalars are allowed even if a tag or an anchor is + # specified. + event = ScalarEvent(anchor, tag, (implicit, False), '', + start_mark, end_mark) + self.state = self.states.pop() + else: + if block: + node = 'block' + else: + node = 'flow' + token = self.peek_token() + raise ParserError("while parsing a %s node" % node, start_mark, + "expected the node content, but found %r" % token.id, + token.start_mark) + return event + + # block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END + + def parse_block_sequence_first_entry(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_block_sequence_entry() + + def parse_block_sequence_entry(self): + if self.check_token(BlockEntryToken): + token = self.get_token() + if not self.check_token(BlockEntryToken, BlockEndToken): + self.states.append(self.parse_block_sequence_entry) + return self.parse_block_node() + else: + self.state = self.parse_block_sequence_entry + return self.process_empty_scalar(token.end_mark) + if not self.check_token(BlockEndToken): + token = self.peek_token() + raise ParserError("while parsing a block collection", self.marks[-1], + "expected , but found %r" % token.id, token.start_mark) + token = self.get_token() + event = SequenceEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + # indentless_sequence ::= (BLOCK-ENTRY block_node?)+ + + def parse_indentless_sequence_entry(self): + if self.check_token(BlockEntryToken): + token = self.get_token() + if not self.check_token(BlockEntryToken, + KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_indentless_sequence_entry) + return self.parse_block_node() + else: + self.state = self.parse_indentless_sequence_entry + return self.process_empty_scalar(token.end_mark) + token = self.peek_token() + event = SequenceEndEvent(token.start_mark, token.start_mark) + self.state = self.states.pop() + return event + + # block_mapping ::= BLOCK-MAPPING_START + # ((KEY block_node_or_indentless_sequence?)? + # (VALUE block_node_or_indentless_sequence?)?)* + # BLOCK-END + + def parse_block_mapping_first_key(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_block_mapping_key() + + def parse_block_mapping_key(self): + if self.check_token(KeyToken): + token = self.get_token() + if not self.check_token(KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_block_mapping_value) + return self.parse_block_node_or_indentless_sequence() + else: + self.state = self.parse_block_mapping_value + return self.process_empty_scalar(token.end_mark) + if not self.check_token(BlockEndToken): + token = self.peek_token() + raise ParserError("while parsing a block mapping", self.marks[-1], + "expected , but found %r" % token.id, token.start_mark) + token = self.get_token() + event = MappingEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_block_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(KeyToken, ValueToken, BlockEndToken): + self.states.append(self.parse_block_mapping_key) + return self.parse_block_node_or_indentless_sequence() + else: + self.state = self.parse_block_mapping_key + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_block_mapping_key + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + # flow_sequence ::= FLOW-SEQUENCE-START + # (flow_sequence_entry FLOW-ENTRY)* + # flow_sequence_entry? + # FLOW-SEQUENCE-END + # flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + # + # Note that while production rules for both flow_sequence_entry and + # flow_mapping_entry are equal, their interpretations are different. + # For `flow_sequence_entry`, the part `KEY flow_node? (VALUE flow_node?)?` + # generate an inline mapping (set syntax). + + def parse_flow_sequence_first_entry(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_flow_sequence_entry(first=True) + + def parse_flow_sequence_entry(self, first=False): + if not self.check_token(FlowSequenceEndToken): + if not first: + if self.check_token(FlowEntryToken): + self.get_token() + else: + token = self.peek_token() + raise ParserError("while parsing a flow sequence", self.marks[-1], + "expected ',' or ']', but got %r" % token.id, token.start_mark) + + if self.check_token(KeyToken): + token = self.peek_token() + event = MappingStartEvent(None, None, True, + token.start_mark, token.end_mark, + flow_style=True) + self.state = self.parse_flow_sequence_entry_mapping_key + return event + elif not self.check_token(FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry) + return self.parse_flow_node() + token = self.get_token() + event = SequenceEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_flow_sequence_entry_mapping_key(self): + token = self.get_token() + if not self.check_token(ValueToken, + FlowEntryToken, FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry_mapping_value) + return self.parse_flow_node() + else: + self.state = self.parse_flow_sequence_entry_mapping_value + return self.process_empty_scalar(token.end_mark) + + def parse_flow_sequence_entry_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(FlowEntryToken, FlowSequenceEndToken): + self.states.append(self.parse_flow_sequence_entry_mapping_end) + return self.parse_flow_node() + else: + self.state = self.parse_flow_sequence_entry_mapping_end + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_flow_sequence_entry_mapping_end + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + def parse_flow_sequence_entry_mapping_end(self): + self.state = self.parse_flow_sequence_entry + token = self.peek_token() + return MappingEndEvent(token.start_mark, token.start_mark) + + # flow_mapping ::= FLOW-MAPPING-START + # (flow_mapping_entry FLOW-ENTRY)* + # flow_mapping_entry? + # FLOW-MAPPING-END + # flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? + + def parse_flow_mapping_first_key(self): + token = self.get_token() + self.marks.append(token.start_mark) + return self.parse_flow_mapping_key(first=True) + + def parse_flow_mapping_key(self, first=False): + if not self.check_token(FlowMappingEndToken): + if not first: + if self.check_token(FlowEntryToken): + self.get_token() + else: + token = self.peek_token() + raise ParserError("while parsing a flow mapping", self.marks[-1], + "expected ',' or '}', but got %r" % token.id, token.start_mark) + if self.check_token(KeyToken): + token = self.get_token() + if not self.check_token(ValueToken, + FlowEntryToken, FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_value) + return self.parse_flow_node() + else: + self.state = self.parse_flow_mapping_value + return self.process_empty_scalar(token.end_mark) + elif not self.check_token(FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_empty_value) + return self.parse_flow_node() + token = self.get_token() + event = MappingEndEvent(token.start_mark, token.end_mark) + self.state = self.states.pop() + self.marks.pop() + return event + + def parse_flow_mapping_value(self): + if self.check_token(ValueToken): + token = self.get_token() + if not self.check_token(FlowEntryToken, FlowMappingEndToken): + self.states.append(self.parse_flow_mapping_key) + return self.parse_flow_node() + else: + self.state = self.parse_flow_mapping_key + return self.process_empty_scalar(token.end_mark) + else: + self.state = self.parse_flow_mapping_key + token = self.peek_token() + return self.process_empty_scalar(token.start_mark) + + def parse_flow_mapping_empty_value(self): + self.state = self.parse_flow_mapping_key + return self.process_empty_scalar(self.peek_token().start_mark) + + def process_empty_scalar(self, mark): + return ScalarEvent(None, None, (True, False), '', mark, mark) + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/reader.py b/.venv_haddock/lib/python3.12/site-packages/yaml/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..774b0219b5932a0ee1c27e637371de5ba8d9cb16 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/reader.py @@ -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/.venv_haddock/lib/python3.12/site-packages/yaml/representer.py b/.venv_haddock/lib/python3.12/site-packages/yaml/representer.py new file mode 100644 index 0000000000000000000000000000000000000000..808ca06dfbd60c9a23eb079151b74a82ef688749 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/representer.py @@ -0,0 +1,389 @@ + +__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer', + 'RepresenterError'] + +from .error import * +from .nodes import * + +import datetime, copyreg, types, base64, collections + +class RepresenterError(YAMLError): + pass + +class BaseRepresenter: + + yaml_representers = {} + yaml_multi_representers = {} + + def __init__(self, default_style=None, default_flow_style=False, sort_keys=True): + self.default_style = default_style + self.sort_keys = sort_keys + self.default_flow_style = default_flow_style + self.represented_objects = {} + self.object_keeper = [] + self.alias_key = None + + def represent(self, data): + node = self.represent_data(data) + self.serialize(node) + self.represented_objects = {} + self.object_keeper = [] + self.alias_key = None + + def represent_data(self, data): + if self.ignore_aliases(data): + self.alias_key = None + else: + self.alias_key = id(data) + if self.alias_key is not None: + if self.alias_key in self.represented_objects: + node = self.represented_objects[self.alias_key] + #if node is None: + # raise RepresenterError("recursive objects are not allowed: %r" % data) + return node + #self.represented_objects[alias_key] = None + self.object_keeper.append(data) + data_types = type(data).__mro__ + if data_types[0] in self.yaml_representers: + node = self.yaml_representers[data_types[0]](self, data) + else: + for data_type in data_types: + if data_type in self.yaml_multi_representers: + node = self.yaml_multi_representers[data_type](self, data) + break + else: + if None in self.yaml_multi_representers: + node = self.yaml_multi_representers[None](self, data) + elif None in self.yaml_representers: + node = self.yaml_representers[None](self, data) + else: + node = ScalarNode(None, str(data)) + #if alias_key is not None: + # self.represented_objects[alias_key] = node + return node + + @classmethod + def add_representer(cls, data_type, representer): + if not 'yaml_representers' in cls.__dict__: + cls.yaml_representers = cls.yaml_representers.copy() + cls.yaml_representers[data_type] = representer + + @classmethod + def add_multi_representer(cls, data_type, representer): + if not 'yaml_multi_representers' in cls.__dict__: + cls.yaml_multi_representers = cls.yaml_multi_representers.copy() + cls.yaml_multi_representers[data_type] = representer + + def represent_scalar(self, tag, value, style=None): + if style is None: + style = self.default_style + node = ScalarNode(tag, value, style=style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + return node + + def represent_sequence(self, tag, sequence, flow_style=None): + value = [] + node = SequenceNode(tag, value, flow_style=flow_style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + best_style = True + for item in sequence: + node_item = self.represent_data(item) + if not (isinstance(node_item, ScalarNode) and not node_item.style): + best_style = False + value.append(node_item) + if flow_style is None: + if self.default_flow_style is not None: + node.flow_style = self.default_flow_style + else: + node.flow_style = best_style + return node + + def represent_mapping(self, tag, mapping, flow_style=None): + value = [] + node = MappingNode(tag, value, flow_style=flow_style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + best_style = True + if hasattr(mapping, 'items'): + mapping = list(mapping.items()) + if self.sort_keys: + try: + mapping = sorted(mapping) + except TypeError: + pass + for item_key, item_value in mapping: + node_key = self.represent_data(item_key) + node_value = self.represent_data(item_value) + if not (isinstance(node_key, ScalarNode) and not node_key.style): + best_style = False + if not (isinstance(node_value, ScalarNode) and not node_value.style): + best_style = False + value.append((node_key, node_value)) + if flow_style is None: + if self.default_flow_style is not None: + node.flow_style = self.default_flow_style + else: + node.flow_style = best_style + return node + + def ignore_aliases(self, data): + return False + +class SafeRepresenter(BaseRepresenter): + + def ignore_aliases(self, data): + if data is None: + return True + if isinstance(data, tuple) and data == (): + return True + if isinstance(data, (str, bytes, bool, int, float)): + return True + + def represent_none(self, data): + return self.represent_scalar('tag:yaml.org,2002:null', 'null') + + def represent_str(self, data): + return self.represent_scalar('tag:yaml.org,2002:str', data) + + def represent_binary(self, data): + if hasattr(base64, 'encodebytes'): + data = base64.encodebytes(data).decode('ascii') + else: + data = base64.encodestring(data).decode('ascii') + return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|') + + def represent_bool(self, data): + if data: + value = 'true' + else: + value = 'false' + return self.represent_scalar('tag:yaml.org,2002:bool', value) + + def represent_int(self, data): + return self.represent_scalar('tag:yaml.org,2002:int', str(data)) + + inf_value = 1e300 + while repr(inf_value) != repr(inf_value*inf_value): + inf_value *= inf_value + + def represent_float(self, data): + if data != data or (data == 0.0 and data == 1.0): + value = '.nan' + elif data == self.inf_value: + value = '.inf' + elif data == -self.inf_value: + value = '-.inf' + else: + value = repr(data).lower() + # Note that in some cases `repr(data)` represents a float number + # without the decimal parts. For instance: + # >>> repr(1e17) + # '1e17' + # Unfortunately, this is not a valid float representation according + # to the definition of the `!!float` tag. We fix this by adding + # '.0' before the 'e' symbol. + if '.' not in value and 'e' in value: + value = value.replace('e', '.0e', 1) + return self.represent_scalar('tag:yaml.org,2002:float', value) + + def represent_list(self, data): + #pairs = (len(data) > 0 and isinstance(data, list)) + #if pairs: + # for item in data: + # if not isinstance(item, tuple) or len(item) != 2: + # pairs = False + # break + #if not pairs: + return self.represent_sequence('tag:yaml.org,2002:seq', data) + #value = [] + #for item_key, item_value in data: + # value.append(self.represent_mapping(u'tag:yaml.org,2002:map', + # [(item_key, item_value)])) + #return SequenceNode(u'tag:yaml.org,2002:pairs', value) + + def represent_dict(self, data): + return self.represent_mapping('tag:yaml.org,2002:map', data) + + def represent_set(self, data): + value = {} + for key in data: + value[key] = None + return self.represent_mapping('tag:yaml.org,2002:set', value) + + def represent_date(self, data): + value = data.isoformat() + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) + + def represent_datetime(self, data): + value = data.isoformat(' ') + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) + + def represent_yaml_object(self, tag, data, cls, flow_style=None): + if hasattr(data, '__getstate__'): + state = data.__getstate__() + else: + state = data.__dict__.copy() + return self.represent_mapping(tag, state, flow_style=flow_style) + + def represent_undefined(self, data): + raise RepresenterError("cannot represent an object", data) + +SafeRepresenter.add_representer(type(None), + SafeRepresenter.represent_none) + +SafeRepresenter.add_representer(str, + SafeRepresenter.represent_str) + +SafeRepresenter.add_representer(bytes, + SafeRepresenter.represent_binary) + +SafeRepresenter.add_representer(bool, + SafeRepresenter.represent_bool) + +SafeRepresenter.add_representer(int, + SafeRepresenter.represent_int) + +SafeRepresenter.add_representer(float, + SafeRepresenter.represent_float) + +SafeRepresenter.add_representer(list, + SafeRepresenter.represent_list) + +SafeRepresenter.add_representer(tuple, + SafeRepresenter.represent_list) + +SafeRepresenter.add_representer(dict, + SafeRepresenter.represent_dict) + +SafeRepresenter.add_representer(set, + SafeRepresenter.represent_set) + +SafeRepresenter.add_representer(datetime.date, + SafeRepresenter.represent_date) + +SafeRepresenter.add_representer(datetime.datetime, + SafeRepresenter.represent_datetime) + +SafeRepresenter.add_representer(None, + SafeRepresenter.represent_undefined) + +class Representer(SafeRepresenter): + + def represent_complex(self, data): + if data.imag == 0.0: + data = '%r' % data.real + elif data.real == 0.0: + data = '%rj' % data.imag + elif data.imag > 0: + data = '%r+%rj' % (data.real, data.imag) + else: + data = '%r%rj' % (data.real, data.imag) + return self.represent_scalar('tag:yaml.org,2002:python/complex', data) + + def represent_tuple(self, data): + return self.represent_sequence('tag:yaml.org,2002:python/tuple', data) + + def represent_name(self, data): + name = '%s.%s' % (data.__module__, data.__name__) + return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '') + + def represent_module(self, data): + return self.represent_scalar( + 'tag:yaml.org,2002:python/module:'+data.__name__, '') + + def represent_object(self, data): + # We use __reduce__ API to save the data. data.__reduce__ returns + # a tuple of length 2-5: + # (function, args, state, listitems, dictitems) + + # For reconstructing, we calls function(*args), then set its state, + # listitems, and dictitems if they are not None. + + # A special case is when function.__name__ == '__newobj__'. In this + # case we create the object with args[0].__new__(*args). + + # Another special case is when __reduce__ returns a string - we don't + # support it. + + # We produce a !!python/object, !!python/object/new or + # !!python/object/apply node. + + cls = type(data) + if cls in copyreg.dispatch_table: + reduce = copyreg.dispatch_table[cls](data) + elif hasattr(data, '__reduce_ex__'): + reduce = data.__reduce_ex__(2) + elif hasattr(data, '__reduce__'): + reduce = data.__reduce__() + else: + raise RepresenterError("cannot represent an object", data) + reduce = (list(reduce)+[None]*5)[:5] + function, args, state, listitems, dictitems = reduce + args = list(args) + if state is None: + state = {} + if listitems is not None: + listitems = list(listitems) + if dictitems is not None: + dictitems = dict(dictitems) + if function.__name__ == '__newobj__': + function = args[0] + args = args[1:] + tag = 'tag:yaml.org,2002:python/object/new:' + newobj = True + else: + tag = 'tag:yaml.org,2002:python/object/apply:' + newobj = False + function_name = '%s.%s' % (function.__module__, function.__name__) + if not args and not listitems and not dictitems \ + and isinstance(state, dict) and newobj: + return self.represent_mapping( + 'tag:yaml.org,2002:python/object:'+function_name, state) + if not listitems and not dictitems \ + and isinstance(state, dict) and not state: + return self.represent_sequence(tag+function_name, args) + value = {} + if args: + value['args'] = args + if state or not isinstance(state, dict): + value['state'] = state + if listitems: + value['listitems'] = listitems + if dictitems: + value['dictitems'] = dictitems + return self.represent_mapping(tag+function_name, value) + + def represent_ordered_dict(self, data): + # Provide uniform representation across different Python versions. + data_type = type(data) + tag = 'tag:yaml.org,2002:python/object/apply:%s.%s' \ + % (data_type.__module__, data_type.__name__) + items = [[key, value] for key, value in data.items()] + return self.represent_sequence(tag, [items]) + +Representer.add_representer(complex, + Representer.represent_complex) + +Representer.add_representer(tuple, + Representer.represent_tuple) + +Representer.add_multi_representer(type, + Representer.represent_name) + +Representer.add_representer(collections.OrderedDict, + Representer.represent_ordered_dict) + +Representer.add_representer(types.FunctionType, + Representer.represent_name) + +Representer.add_representer(types.BuiltinFunctionType, + Representer.represent_name) + +Representer.add_representer(types.ModuleType, + Representer.represent_module) + +Representer.add_multi_representer(object, + Representer.represent_object) + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/resolver.py b/.venv_haddock/lib/python3.12/site-packages/yaml/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..3522bdaaf6358110b608f4e6503b9d314c82d887 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/resolver.py @@ -0,0 +1,227 @@ + +__all__ = ['BaseResolver', 'Resolver'] + +from .error import * +from .nodes import * + +import re + +class ResolverError(YAMLError): + pass + +class BaseResolver: + + DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str' + DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq' + DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' + + yaml_implicit_resolvers = {} + yaml_path_resolvers = {} + + def __init__(self): + self.resolver_exact_paths = [] + self.resolver_prefix_paths = [] + + @classmethod + def add_implicit_resolver(cls, tag, regexp, first): + if not 'yaml_implicit_resolvers' in cls.__dict__: + implicit_resolvers = {} + for key in cls.yaml_implicit_resolvers: + implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:] + cls.yaml_implicit_resolvers = implicit_resolvers + if first is None: + first = [None] + for ch in first: + cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp)) + + @classmethod + def add_path_resolver(cls, tag, path, kind=None): + # Note: `add_path_resolver` is experimental. The API could be changed. + # `new_path` is a pattern that is matched against the path from the + # root to the node that is being considered. `node_path` elements are + # tuples `(node_check, index_check)`. `node_check` is a node class: + # `ScalarNode`, `SequenceNode`, `MappingNode` or `None`. `None` + # matches any kind of a node. `index_check` could be `None`, a boolean + # value, a string value, or a number. `None` and `False` match against + # any _value_ of sequence and mapping nodes. `True` matches against + # any _key_ of a mapping node. A string `index_check` matches against + # a mapping value that corresponds to a scalar key which content is + # equal to the `index_check` value. An integer `index_check` matches + # against a sequence value with the index equal to `index_check`. + if not 'yaml_path_resolvers' in cls.__dict__: + cls.yaml_path_resolvers = cls.yaml_path_resolvers.copy() + new_path = [] + for element in path: + if isinstance(element, (list, tuple)): + if len(element) == 2: + node_check, index_check = element + elif len(element) == 1: + node_check = element[0] + index_check = True + else: + raise ResolverError("Invalid path element: %s" % element) + else: + node_check = None + index_check = element + if node_check is str: + node_check = ScalarNode + elif node_check is list: + node_check = SequenceNode + elif node_check is dict: + node_check = MappingNode + elif node_check not in [ScalarNode, SequenceNode, MappingNode] \ + and not isinstance(node_check, str) \ + and node_check is not None: + raise ResolverError("Invalid node checker: %s" % node_check) + if not isinstance(index_check, (str, int)) \ + and index_check is not None: + raise ResolverError("Invalid index checker: %s" % index_check) + new_path.append((node_check, index_check)) + if kind is str: + kind = ScalarNode + elif kind is list: + kind = SequenceNode + elif kind is dict: + kind = MappingNode + elif kind not in [ScalarNode, SequenceNode, MappingNode] \ + and kind is not None: + raise ResolverError("Invalid node kind: %s" % kind) + cls.yaml_path_resolvers[tuple(new_path), kind] = tag + + def descend_resolver(self, current_node, current_index): + if not self.yaml_path_resolvers: + return + exact_paths = {} + prefix_paths = [] + if current_node: + depth = len(self.resolver_prefix_paths) + for path, kind in self.resolver_prefix_paths[-1]: + if self.check_resolver_prefix(depth, path, kind, + current_node, current_index): + if len(path) > depth: + prefix_paths.append((path, kind)) + else: + exact_paths[kind] = self.yaml_path_resolvers[path, kind] + else: + for path, kind in self.yaml_path_resolvers: + if not path: + exact_paths[kind] = self.yaml_path_resolvers[path, kind] + else: + prefix_paths.append((path, kind)) + self.resolver_exact_paths.append(exact_paths) + self.resolver_prefix_paths.append(prefix_paths) + + def ascend_resolver(self): + if not self.yaml_path_resolvers: + return + self.resolver_exact_paths.pop() + self.resolver_prefix_paths.pop() + + def check_resolver_prefix(self, depth, path, kind, + current_node, current_index): + node_check, index_check = path[depth-1] + if isinstance(node_check, str): + if current_node.tag != node_check: + return + elif node_check is not None: + if not isinstance(current_node, node_check): + return + if index_check is True and current_index is not None: + return + if (index_check is False or index_check is None) \ + and current_index is None: + return + if isinstance(index_check, str): + if not (isinstance(current_index, ScalarNode) + and index_check == current_index.value): + return + elif isinstance(index_check, int) and not isinstance(index_check, bool): + if index_check != current_index: + return + return True + + def resolve(self, kind, value, implicit): + if kind is ScalarNode and implicit[0]: + if value == '': + resolvers = self.yaml_implicit_resolvers.get('', []) + else: + resolvers = self.yaml_implicit_resolvers.get(value[0], []) + wildcard_resolvers = self.yaml_implicit_resolvers.get(None, []) + for tag, regexp in resolvers + wildcard_resolvers: + if regexp.match(value): + return tag + implicit = implicit[1] + if self.yaml_path_resolvers: + exact_paths = self.resolver_exact_paths[-1] + if kind in exact_paths: + return exact_paths[kind] + if None in exact_paths: + return exact_paths[None] + if kind is ScalarNode: + return self.DEFAULT_SCALAR_TAG + elif kind is SequenceNode: + return self.DEFAULT_SEQUENCE_TAG + elif kind is MappingNode: + return self.DEFAULT_MAPPING_TAG + +class Resolver(BaseResolver): + pass + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:bool', + re.compile(r'''^(?:yes|Yes|YES|no|No|NO + |true|True|TRUE|false|False|FALSE + |on|On|ON|off|Off|OFF)$''', re.X), + list('yYnNtTfFoO')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:float', + re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? + |\.[0-9][0-9_]*(?:[eE][-+][0-9]+)? + |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]* + |[-+]?\.(?:inf|Inf|INF) + |\.(?:nan|NaN|NAN))$''', re.X), + list('-+0123456789.')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:int', + re.compile(r'''^(?:[-+]?0b[0-1_]+ + |[-+]?0[0-7_]+ + |[-+]?(?:0|[1-9][0-9_]*) + |[-+]?0x[0-9a-fA-F_]+ + |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), + list('-+0123456789')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:merge', + re.compile(r'^(?:<<)$'), + ['<']) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:null', + re.compile(r'''^(?: ~ + |null|Null|NULL + | )$''', re.X), + ['~', 'n', 'N', '']) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:timestamp', + re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] + |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? + (?:[Tt]|[ \t]+)[0-9][0-9]? + :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)? + (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), + list('0123456789')) + +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:value', + re.compile(r'^(?:=)$'), + ['=']) + +# The following resolver is only for documentation purposes. It cannot work +# because plain scalars cannot start with '!', '&', or '*'. +Resolver.add_implicit_resolver( + 'tag:yaml.org,2002:yaml', + re.compile(r'^(?:!|&|\*)$'), + list('!&*')) + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/scanner.py b/.venv_haddock/lib/python3.12/site-packages/yaml/scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..de925b07f1eaec33c9c305a8a69f9eb7ac5983c5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/scanner.py @@ -0,0 +1,1435 @@ + +# Scanner produces tokens of the following types: +# STREAM-START +# STREAM-END +# DIRECTIVE(name, value) +# DOCUMENT-START +# DOCUMENT-END +# BLOCK-SEQUENCE-START +# BLOCK-MAPPING-START +# BLOCK-END +# FLOW-SEQUENCE-START +# FLOW-MAPPING-START +# FLOW-SEQUENCE-END +# FLOW-MAPPING-END +# BLOCK-ENTRY +# FLOW-ENTRY +# KEY +# VALUE +# ALIAS(value) +# ANCHOR(value) +# TAG(value) +# SCALAR(value, plain, style) +# +# Read comments in the Scanner code for more details. +# + +__all__ = ['Scanner', 'ScannerError'] + +from .error import MarkedYAMLError +from .tokens import * + +class ScannerError(MarkedYAMLError): + pass + +class SimpleKey: + # See below simple keys treatment. + + def __init__(self, token_number, required, index, line, column, mark): + self.token_number = token_number + self.required = required + self.index = index + self.line = line + self.column = column + self.mark = mark + +class Scanner: + + def __init__(self): + """Initialize the scanner.""" + # It is assumed that Scanner and Reader will have a common descendant. + # Reader do the dirty work of checking for BOM and converting the + # input data to Unicode. It also adds NUL to the end. + # + # Reader supports the following methods + # self.peek(i=0) # peek the next i-th character + # self.prefix(l=1) # peek the next l characters + # self.forward(l=1) # read the next l characters and move the pointer. + + # Had we reached the end of the stream? + self.done = False + + # The number of unclosed '{' and '['. `flow_level == 0` means block + # context. + self.flow_level = 0 + + # List of processed tokens that are not yet emitted. + self.tokens = [] + + # Add the STREAM-START token. + self.fetch_stream_start() + + # Number of tokens that were emitted through the `get_token` method. + self.tokens_taken = 0 + + # The current indentation level. + self.indent = -1 + + # Past indentation levels. + self.indents = [] + + # Variables related to simple keys treatment. + + # A simple key is a key that is not denoted by the '?' indicator. + # Example of simple keys: + # --- + # block simple key: value + # ? not a simple key: + # : { flow simple key: value } + # We emit the KEY token before all keys, so when we find a potential + # simple key, we try to locate the corresponding ':' indicator. + # Simple keys should be limited to a single line and 1024 characters. + + # Can a simple key start at the current position? A simple key may + # start: + # - at the beginning of the line, not counting indentation spaces + # (in block context), + # - after '{', '[', ',' (in the flow context), + # - after '?', ':', '-' (in the block context). + # In the block context, this flag also signifies if a block collection + # may start at the current position. + self.allow_simple_key = True + + # Keep track of possible simple keys. This is a dictionary. The key + # is `flow_level`; there can be no more that one possible simple key + # for each level. The value is a SimpleKey record: + # (token_number, required, index, line, column, mark) + # A simple key may start with ALIAS, ANCHOR, TAG, SCALAR(flow), + # '[', or '{' tokens. + self.possible_simple_keys = {} + + # Public methods. + + def check_token(self, *choices): + # Check if the next token is one of the given types. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + if not choices: + return True + for choice in choices: + if isinstance(self.tokens[0], choice): + return True + return False + + def peek_token(self): + # Return the next token, but do not delete if from the queue. + # Return None if no more tokens. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + return self.tokens[0] + else: + return None + + def get_token(self): + # Return the next token. + while self.need_more_tokens(): + self.fetch_more_tokens() + if self.tokens: + self.tokens_taken += 1 + return self.tokens.pop(0) + + # Private methods. + + def need_more_tokens(self): + if self.done: + return False + if not self.tokens: + return True + # The current token may be a potential simple key, so we + # need to look further. + self.stale_possible_simple_keys() + if self.next_possible_simple_key() == self.tokens_taken: + return True + + def fetch_more_tokens(self): + + # Eat whitespaces and comments until we reach the next token. + self.scan_to_next_token() + + # Remove obsolete possible simple keys. + self.stale_possible_simple_keys() + + # Compare the current indentation and column. It may add some tokens + # and decrease the current indentation level. + self.unwind_indent(self.column) + + # Peek the next character. + ch = self.peek() + + # Is it the end of stream? + if ch == '\0': + return self.fetch_stream_end() + + # Is it a directive? + if ch == '%' and self.check_directive(): + return self.fetch_directive() + + # Is it the document start? + if ch == '-' and self.check_document_start(): + return self.fetch_document_start() + + # Is it the document end? + if ch == '.' and self.check_document_end(): + return self.fetch_document_end() + + # TODO: support for BOM within a stream. + #if ch == '\uFEFF': + # return self.fetch_bom() <-- issue BOMToken + + # Note: the order of the following checks is NOT significant. + + # Is it the flow sequence start indicator? + if ch == '[': + return self.fetch_flow_sequence_start() + + # Is it the flow mapping start indicator? + if ch == '{': + return self.fetch_flow_mapping_start() + + # Is it the flow sequence end indicator? + if ch == ']': + return self.fetch_flow_sequence_end() + + # Is it the flow mapping end indicator? + if ch == '}': + return self.fetch_flow_mapping_end() + + # Is it the flow entry indicator? + if ch == ',': + return self.fetch_flow_entry() + + # Is it the block entry indicator? + if ch == '-' and self.check_block_entry(): + return self.fetch_block_entry() + + # Is it the key indicator? + if ch == '?' and self.check_key(): + return self.fetch_key() + + # Is it the value indicator? + if ch == ':' and self.check_value(): + return self.fetch_value() + + # Is it an alias? + if ch == '*': + return self.fetch_alias() + + # Is it an anchor? + if ch == '&': + return self.fetch_anchor() + + # Is it a tag? + if ch == '!': + return self.fetch_tag() + + # Is it a literal scalar? + if ch == '|' and not self.flow_level: + return self.fetch_literal() + + # Is it a folded scalar? + if ch == '>' and not self.flow_level: + return self.fetch_folded() + + # Is it a single quoted scalar? + if ch == '\'': + return self.fetch_single() + + # Is it a double quoted scalar? + if ch == '\"': + return self.fetch_double() + + # It must be a plain scalar then. + if self.check_plain(): + return self.fetch_plain() + + # No? It's an error. Let's produce a nice error message. + raise ScannerError("while scanning for the next token", None, + "found character %r that cannot start any token" % ch, + self.get_mark()) + + # Simple keys treatment. + + def next_possible_simple_key(self): + # Return the number of the nearest possible simple key. Actually we + # don't need to loop through the whole dictionary. We may replace it + # with the following code: + # if not self.possible_simple_keys: + # return None + # return self.possible_simple_keys[ + # min(self.possible_simple_keys.keys())].token_number + min_token_number = None + for level in self.possible_simple_keys: + key = self.possible_simple_keys[level] + if min_token_number is None or key.token_number < min_token_number: + min_token_number = key.token_number + return min_token_number + + def stale_possible_simple_keys(self): + # Remove entries that are no longer possible simple keys. According to + # the YAML specification, simple keys + # - should be limited to a single line, + # - should be no longer than 1024 characters. + # Disabling this procedure will allow simple keys of any length and + # height (may cause problems if indentation is broken though). + for level in list(self.possible_simple_keys): + key = self.possible_simple_keys[level] + if key.line != self.line \ + or self.index-key.index > 1024: + if key.required: + raise ScannerError("while scanning a simple key", key.mark, + "could not find expected ':'", self.get_mark()) + del self.possible_simple_keys[level] + + def save_possible_simple_key(self): + # The next token may start a simple key. We check if it's possible + # and save its position. This function is called for + # ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'. + + # Check if a simple key is required at the current position. + required = not self.flow_level and self.indent == self.column + + # The next token might be a simple key. Let's save it's number and + # position. + if self.allow_simple_key: + self.remove_possible_simple_key() + token_number = self.tokens_taken+len(self.tokens) + key = SimpleKey(token_number, required, + self.index, self.line, self.column, self.get_mark()) + self.possible_simple_keys[self.flow_level] = key + + def remove_possible_simple_key(self): + # Remove the saved possible key position at the current flow level. + if self.flow_level in self.possible_simple_keys: + key = self.possible_simple_keys[self.flow_level] + + if key.required: + raise ScannerError("while scanning a simple key", key.mark, + "could not find expected ':'", self.get_mark()) + + del self.possible_simple_keys[self.flow_level] + + # Indentation functions. + + def unwind_indent(self, column): + + ## In flow context, tokens should respect indentation. + ## Actually the condition should be `self.indent >= column` according to + ## the spec. But this condition will prohibit intuitively correct + ## constructions such as + ## key : { + ## } + #if self.flow_level and self.indent > column: + # raise ScannerError(None, None, + # "invalid indentation or unclosed '[' or '{'", + # self.get_mark()) + + # In the flow context, indentation is ignored. We make the scanner less + # restrictive then specification requires. + if self.flow_level: + return + + # In block context, we may need to issue the BLOCK-END tokens. + while self.indent > column: + mark = self.get_mark() + self.indent = self.indents.pop() + self.tokens.append(BlockEndToken(mark, mark)) + + def add_indent(self, column): + # Check if we need to increase indentation. + if self.indent < column: + self.indents.append(self.indent) + self.indent = column + return True + return False + + # Fetchers. + + def fetch_stream_start(self): + # We always add STREAM-START as the first token and STREAM-END as the + # last token. + + # Read the token. + mark = self.get_mark() + + # Add STREAM-START. + self.tokens.append(StreamStartToken(mark, mark, + encoding=self.encoding)) + + + def fetch_stream_end(self): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. + self.remove_possible_simple_key() + self.allow_simple_key = False + self.possible_simple_keys = {} + + # Read the token. + mark = self.get_mark() + + # Add STREAM-END. + self.tokens.append(StreamEndToken(mark, mark)) + + # The steam is finished. + self.done = True + + def fetch_directive(self): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. + self.remove_possible_simple_key() + self.allow_simple_key = False + + # Scan and add DIRECTIVE. + self.tokens.append(self.scan_directive()) + + def fetch_document_start(self): + self.fetch_document_indicator(DocumentStartToken) + + def fetch_document_end(self): + self.fetch_document_indicator(DocumentEndToken) + + def fetch_document_indicator(self, TokenClass): + + # Set the current indentation to -1. + self.unwind_indent(-1) + + # Reset simple keys. Note that there could not be a block collection + # after '---'. + self.remove_possible_simple_key() + self.allow_simple_key = False + + # Add DOCUMENT-START or DOCUMENT-END. + start_mark = self.get_mark() + self.forward(3) + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_sequence_start(self): + self.fetch_flow_collection_start(FlowSequenceStartToken) + + def fetch_flow_mapping_start(self): + self.fetch_flow_collection_start(FlowMappingStartToken) + + def fetch_flow_collection_start(self, TokenClass): + + # '[' and '{' may start a simple key. + self.save_possible_simple_key() + + # Increase the flow level. + self.flow_level += 1 + + # Simple keys are allowed after '[' and '{'. + self.allow_simple_key = True + + # Add FLOW-SEQUENCE-START or FLOW-MAPPING-START. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_sequence_end(self): + self.fetch_flow_collection_end(FlowSequenceEndToken) + + def fetch_flow_mapping_end(self): + self.fetch_flow_collection_end(FlowMappingEndToken) + + def fetch_flow_collection_end(self, TokenClass): + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Decrease the flow level. + self.flow_level -= 1 + + # No simple keys after ']' or '}'. + self.allow_simple_key = False + + # Add FLOW-SEQUENCE-END or FLOW-MAPPING-END. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(TokenClass(start_mark, end_mark)) + + def fetch_flow_entry(self): + + # Simple keys are allowed after ','. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add FLOW-ENTRY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(FlowEntryToken(start_mark, end_mark)) + + def fetch_block_entry(self): + + # Block context needs additional checks. + if not self.flow_level: + + # Are we allowed to start a new entry? + if not self.allow_simple_key: + raise ScannerError(None, None, + "sequence entries are not allowed here", + self.get_mark()) + + # We may need to add BLOCK-SEQUENCE-START. + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockSequenceStartToken(mark, mark)) + + # It's an error for the block entry to occur in the flow context, + # but we let the parser detect this. + else: + pass + + # Simple keys are allowed after '-'. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add BLOCK-ENTRY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(BlockEntryToken(start_mark, end_mark)) + + def fetch_key(self): + + # Block context needs additional checks. + if not self.flow_level: + + # Are we allowed to start a key (not necessary a simple)? + if not self.allow_simple_key: + raise ScannerError(None, None, + "mapping keys are not allowed here", + self.get_mark()) + + # We may need to add BLOCK-MAPPING-START. + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockMappingStartToken(mark, mark)) + + # Simple keys are allowed after '?' in the block context. + self.allow_simple_key = not self.flow_level + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add KEY. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(KeyToken(start_mark, end_mark)) + + def fetch_value(self): + + # Do we determine a simple key? + if self.flow_level in self.possible_simple_keys: + + # Add KEY. + key = self.possible_simple_keys[self.flow_level] + del self.possible_simple_keys[self.flow_level] + self.tokens.insert(key.token_number-self.tokens_taken, + KeyToken(key.mark, key.mark)) + + # If this key starts a new block mapping, we need to add + # BLOCK-MAPPING-START. + if not self.flow_level: + if self.add_indent(key.column): + self.tokens.insert(key.token_number-self.tokens_taken, + BlockMappingStartToken(key.mark, key.mark)) + + # There cannot be two simple keys one after another. + self.allow_simple_key = False + + # It must be a part of a complex key. + else: + + # Block context needs additional checks. + # (Do we really need them? They will be caught by the parser + # anyway.) + if not self.flow_level: + + # We are allowed to start a complex value if and only if + # we can start a simple key. + if not self.allow_simple_key: + raise ScannerError(None, None, + "mapping values are not allowed here", + self.get_mark()) + + # If this value starts a new block mapping, we need to add + # BLOCK-MAPPING-START. It will be detected as an error later by + # the parser. + if not self.flow_level: + if self.add_indent(self.column): + mark = self.get_mark() + self.tokens.append(BlockMappingStartToken(mark, mark)) + + # Simple keys are allowed after ':' in the block context. + self.allow_simple_key = not self.flow_level + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Add VALUE. + start_mark = self.get_mark() + self.forward() + end_mark = self.get_mark() + self.tokens.append(ValueToken(start_mark, end_mark)) + + def fetch_alias(self): + + # ALIAS could be a simple key. + self.save_possible_simple_key() + + # No simple keys after ALIAS. + self.allow_simple_key = False + + # Scan and add ALIAS. + self.tokens.append(self.scan_anchor(AliasToken)) + + def fetch_anchor(self): + + # ANCHOR could start a simple key. + self.save_possible_simple_key() + + # No simple keys after ANCHOR. + self.allow_simple_key = False + + # Scan and add ANCHOR. + self.tokens.append(self.scan_anchor(AnchorToken)) + + def fetch_tag(self): + + # TAG could start a simple key. + self.save_possible_simple_key() + + # No simple keys after TAG. + self.allow_simple_key = False + + # Scan and add TAG. + self.tokens.append(self.scan_tag()) + + def fetch_literal(self): + self.fetch_block_scalar(style='|') + + def fetch_folded(self): + self.fetch_block_scalar(style='>') + + def fetch_block_scalar(self, style): + + # A simple key may follow a block scalar. + self.allow_simple_key = True + + # Reset possible simple key on the current level. + self.remove_possible_simple_key() + + # Scan and add SCALAR. + self.tokens.append(self.scan_block_scalar(style)) + + def fetch_single(self): + self.fetch_flow_scalar(style='\'') + + def fetch_double(self): + self.fetch_flow_scalar(style='"') + + def fetch_flow_scalar(self, style): + + # A flow scalar could be a simple key. + self.save_possible_simple_key() + + # No simple keys after flow scalars. + self.allow_simple_key = False + + # Scan and add SCALAR. + self.tokens.append(self.scan_flow_scalar(style)) + + def fetch_plain(self): + + # A plain scalar could be a simple key. + self.save_possible_simple_key() + + # No simple keys after plain scalars. But note that `scan_plain` will + # change this flag if the scan is finished at the beginning of the + # line. + self.allow_simple_key = False + + # Scan and add SCALAR. May change `allow_simple_key`. + self.tokens.append(self.scan_plain()) + + # Checkers. + + def check_directive(self): + + # DIRECTIVE: ^ '%' ... + # The '%' indicator is already checked. + if self.column == 0: + return True + + def check_document_start(self): + + # DOCUMENT-START: ^ '---' (' '|'\n') + if self.column == 0: + if self.prefix(3) == '---' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return True + + def check_document_end(self): + + # DOCUMENT-END: ^ '...' (' '|'\n') + if self.column == 0: + if self.prefix(3) == '...' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return True + + def check_block_entry(self): + + # BLOCK-ENTRY: '-' (' '|'\n') + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_key(self): + + # KEY(flow context): '?' + if self.flow_level: + return True + + # KEY(block context): '?' (' '|'\n') + else: + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_value(self): + + # VALUE(flow context): ':' + if self.flow_level: + return True + + # VALUE(block context): ':' (' '|'\n') + else: + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' + + def check_plain(self): + + # A plain scalar may start with any non-space character except: + # '-', '?', ':', ',', '[', ']', '{', '}', + # '#', '&', '*', '!', '|', '>', '\'', '\"', + # '%', '@', '`'. + # + # It may also start with + # '-', '?', ':' + # if it is followed by a non-space character. + # + # Note that we limit the last rule to the block context (except the + # '-' character) because we want the flow context to be space + # independent. + ch = self.peek() + return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \ + or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029' + and (ch == '-' or (not self.flow_level and ch in '?:'))) + + # Scanners. + + def scan_to_next_token(self): + # We ignore spaces, line breaks and comments. + # If we find a line break in the block context, we set the flag + # `allow_simple_key` on. + # The byte order mark is stripped if it's the first character in the + # stream. We do not yet support BOM inside the stream as the + # specification requires. Any such mark will be considered as a part + # of the document. + # + # TODO: We need to make tab handling rules more sane. A good rule is + # Tabs cannot precede tokens + # BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END, + # KEY(block), VALUE(block), BLOCK-ENTRY + # So the checking code is + # if : + # self.allow_simple_keys = False + # We also need to add the check for `allow_simple_keys == True` to + # `unwind_indent` before issuing BLOCK-END. + # Scanners for block, flow, and plain scalars need to be modified. + + if self.index == 0 and self.peek() == '\uFEFF': + self.forward() + found = False + while not found: + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + if self.scan_line_break(): + if not self.flow_level: + self.allow_simple_key = True + else: + found = True + + def scan_directive(self): + # See the specification for details. + start_mark = self.get_mark() + self.forward() + name = self.scan_directive_name(start_mark) + value = None + if name == 'YAML': + value = self.scan_yaml_directive_value(start_mark) + end_mark = self.get_mark() + elif name == 'TAG': + value = self.scan_tag_directive_value(start_mark) + end_mark = self.get_mark() + else: + end_mark = self.get_mark() + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + self.scan_directive_ignored_line(start_mark) + return DirectiveToken(name, value, start_mark, end_mark) + + def scan_directive_name(self, start_mark): + # See the specification for details. + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if not length: + raise ScannerError("while scanning a directive", start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + value = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + return value + + def scan_yaml_directive_value(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + major = self.scan_yaml_directive_number(start_mark) + if self.peek() != '.': + raise ScannerError("while scanning a directive", start_mark, + "expected a digit or '.', but found %r" % self.peek(), + self.get_mark()) + self.forward() + minor = self.scan_yaml_directive_number(start_mark) + if self.peek() not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected a digit or ' ', but found %r" % self.peek(), + self.get_mark()) + return (major, minor) + + def scan_yaml_directive_number(self, start_mark): + # See the specification for details. + ch = self.peek() + if not ('0' <= ch <= '9'): + raise ScannerError("while scanning a directive", start_mark, + "expected a digit, but found %r" % ch, self.get_mark()) + length = 0 + while '0' <= self.peek(length) <= '9': + length += 1 + value = int(self.prefix(length)) + self.forward(length) + return value + + def scan_tag_directive_value(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + handle = self.scan_tag_directive_handle(start_mark) + while self.peek() == ' ': + self.forward() + prefix = self.scan_tag_directive_prefix(start_mark) + return (handle, prefix) + + def scan_tag_directive_handle(self, start_mark): + # See the specification for details. + value = self.scan_tag_handle('directive', start_mark) + ch = self.peek() + if ch != ' ': + raise ScannerError("while scanning a directive", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + return value + + def scan_tag_directive_prefix(self, start_mark): + # See the specification for details. + value = self.scan_tag_uri('directive', start_mark) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + return value + + def scan_directive_ignored_line(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + ch = self.peek() + if ch not in '\0\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a directive", start_mark, + "expected a comment or a line break, but found %r" + % ch, self.get_mark()) + self.scan_line_break() + + def scan_anchor(self, TokenClass): + # The specification does not restrict characters for anchors and + # aliases. This may lead to problems, for instance, the document: + # [ *alias, value ] + # can be interpreted in two ways, as + # [ "value" ] + # and + # [ *alias , "value" ] + # Therefore we restrict aliases to numbers and ASCII letters. + start_mark = self.get_mark() + indicator = self.peek() + if indicator == '*': + name = 'alias' + else: + name = 'anchor' + self.forward() + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if not length: + raise ScannerError("while scanning an %s" % name, start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + value = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`': + raise ScannerError("while scanning an %s" % name, start_mark, + "expected alphabetic or numeric character, but found %r" + % ch, self.get_mark()) + end_mark = self.get_mark() + return TokenClass(value, start_mark, end_mark) + + def scan_tag(self): + # See the specification for details. + start_mark = self.get_mark() + ch = self.peek(1) + if ch == '<': + handle = None + self.forward(2) + suffix = self.scan_tag_uri('tag', start_mark) + if self.peek() != '>': + raise ScannerError("while parsing a tag", start_mark, + "expected '>', but found %r" % self.peek(), + self.get_mark()) + self.forward() + elif ch in '\0 \t\r\n\x85\u2028\u2029': + handle = None + suffix = '!' + self.forward() + else: + length = 1 + use_handle = False + while ch not in '\0 \r\n\x85\u2028\u2029': + if ch == '!': + use_handle = True + break + length += 1 + ch = self.peek(length) + handle = '!' + if use_handle: + handle = self.scan_tag_handle('tag', start_mark) + else: + handle = '!' + self.forward() + suffix = self.scan_tag_uri('tag', start_mark) + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a tag", start_mark, + "expected ' ', but found %r" % ch, self.get_mark()) + value = (handle, suffix) + end_mark = self.get_mark() + return TagToken(value, start_mark, end_mark) + + def scan_block_scalar(self, style): + # See the specification for details. + + if style == '>': + folded = True + else: + folded = False + + chunks = [] + start_mark = self.get_mark() + + # Scan the header. + self.forward() + chomping, increment = self.scan_block_scalar_indicators(start_mark) + self.scan_block_scalar_ignored_line(start_mark) + + # Determine the indentation level and go to the first non-empty line. + min_indent = self.indent+1 + if min_indent < 1: + min_indent = 1 + if increment is None: + breaks, max_indent, end_mark = self.scan_block_scalar_indentation() + indent = max(min_indent, max_indent) + else: + indent = min_indent+increment-1 + breaks, end_mark = self.scan_block_scalar_breaks(indent) + line_break = '' + + # Scan the inner part of the block scalar. + while self.column == indent and self.peek() != '\0': + chunks.extend(breaks) + leading_non_space = self.peek() not in ' \t' + length = 0 + while self.peek(length) not in '\0\r\n\x85\u2028\u2029': + length += 1 + chunks.append(self.prefix(length)) + self.forward(length) + line_break = self.scan_line_break() + breaks, end_mark = self.scan_block_scalar_breaks(indent) + if self.column == indent and self.peek() != '\0': + + # Unfortunately, folding rules are ambiguous. + # + # This is the folding according to the specification: + + if folded and line_break == '\n' \ + and leading_non_space and self.peek() not in ' \t': + if not breaks: + chunks.append(' ') + else: + chunks.append(line_break) + + # This is Clark Evans's interpretation (also in the spec + # examples): + # + #if folded and line_break == '\n': + # if not breaks: + # if self.peek() not in ' \t': + # chunks.append(' ') + # else: + # chunks.append(line_break) + #else: + # chunks.append(line_break) + else: + break + + # Chomp the tail. + if chomping is not False: + chunks.append(line_break) + if chomping is True: + chunks.extend(breaks) + + # We are done. + return ScalarToken(''.join(chunks), False, start_mark, end_mark, + style) + + def scan_block_scalar_indicators(self, start_mark): + # See the specification for details. + chomping = None + increment = None + ch = self.peek() + if ch in '+-': + if ch == '+': + chomping = True + else: + chomping = False + self.forward() + ch = self.peek() + if ch in '0123456789': + increment = int(ch) + if increment == 0: + raise ScannerError("while scanning a block scalar", start_mark, + "expected indentation indicator in the range 1-9, but found 0", + self.get_mark()) + self.forward() + elif ch in '0123456789': + increment = int(ch) + if increment == 0: + raise ScannerError("while scanning a block scalar", start_mark, + "expected indentation indicator in the range 1-9, but found 0", + self.get_mark()) + self.forward() + ch = self.peek() + if ch in '+-': + if ch == '+': + chomping = True + else: + chomping = False + self.forward() + ch = self.peek() + if ch not in '\0 \r\n\x85\u2028\u2029': + raise ScannerError("while scanning a block scalar", start_mark, + "expected chomping or indentation indicators, but found %r" + % ch, self.get_mark()) + return chomping, increment + + def scan_block_scalar_ignored_line(self, start_mark): + # See the specification for details. + while self.peek() == ' ': + self.forward() + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': + self.forward() + ch = self.peek() + if ch not in '\0\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a block scalar", start_mark, + "expected a comment or a line break, but found %r" % ch, + self.get_mark()) + self.scan_line_break() + + def scan_block_scalar_indentation(self): + # See the specification for details. + chunks = [] + max_indent = 0 + end_mark = self.get_mark() + while self.peek() in ' \r\n\x85\u2028\u2029': + if self.peek() != ' ': + chunks.append(self.scan_line_break()) + end_mark = self.get_mark() + else: + self.forward() + if self.column > max_indent: + max_indent = self.column + return chunks, max_indent, end_mark + + def scan_block_scalar_breaks(self, indent): + # See the specification for details. + chunks = [] + end_mark = self.get_mark() + while self.column < indent and self.peek() == ' ': + self.forward() + while self.peek() in '\r\n\x85\u2028\u2029': + chunks.append(self.scan_line_break()) + end_mark = self.get_mark() + while self.column < indent and self.peek() == ' ': + self.forward() + return chunks, end_mark + + def scan_flow_scalar(self, style): + # See the specification for details. + # Note that we loose indentation rules for quoted scalars. Quoted + # scalars don't need to adhere indentation because " and ' clearly + # mark the beginning and the end of them. Therefore we are less + # restrictive then the specification requires. We only need to check + # that document separators are not included in scalars. + if style == '"': + double = True + else: + double = False + chunks = [] + start_mark = self.get_mark() + quote = self.peek() + self.forward() + chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) + while self.peek() != quote: + chunks.extend(self.scan_flow_scalar_spaces(double, start_mark)) + chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) + self.forward() + end_mark = self.get_mark() + return ScalarToken(''.join(chunks), False, start_mark, end_mark, + style) + + ESCAPE_REPLACEMENTS = { + '0': '\0', + 'a': '\x07', + 'b': '\x08', + 't': '\x09', + '\t': '\x09', + 'n': '\x0A', + 'v': '\x0B', + 'f': '\x0C', + 'r': '\x0D', + 'e': '\x1B', + ' ': '\x20', + '\"': '\"', + '\\': '\\', + '/': '/', + 'N': '\x85', + '_': '\xA0', + 'L': '\u2028', + 'P': '\u2029', + } + + ESCAPE_CODES = { + 'x': 2, + 'u': 4, + 'U': 8, + } + + def scan_flow_scalar_non_spaces(self, double, start_mark): + # See the specification for details. + chunks = [] + while True: + length = 0 + while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029': + length += 1 + if length: + chunks.append(self.prefix(length)) + self.forward(length) + ch = self.peek() + if not double and ch == '\'' and self.peek(1) == '\'': + chunks.append('\'') + self.forward(2) + elif (double and ch == '\'') or (not double and ch in '\"\\'): + chunks.append(ch) + self.forward() + elif double and ch == '\\': + self.forward() + ch = self.peek() + if ch in self.ESCAPE_REPLACEMENTS: + chunks.append(self.ESCAPE_REPLACEMENTS[ch]) + self.forward() + elif ch in self.ESCAPE_CODES: + length = self.ESCAPE_CODES[ch] + self.forward() + for k in range(length): + if self.peek(k) not in '0123456789ABCDEFabcdef': + raise ScannerError("while scanning a double-quoted scalar", start_mark, + "expected escape sequence of %d hexadecimal numbers, but found %r" % + (length, self.peek(k)), self.get_mark()) + code = int(self.prefix(length), 16) + chunks.append(chr(code)) + self.forward(length) + elif ch in '\r\n\x85\u2028\u2029': + self.scan_line_break() + chunks.extend(self.scan_flow_scalar_breaks(double, start_mark)) + else: + raise ScannerError("while scanning a double-quoted scalar", start_mark, + "found unknown escape character %r" % ch, self.get_mark()) + else: + return chunks + + def scan_flow_scalar_spaces(self, double, start_mark): + # See the specification for details. + chunks = [] + length = 0 + while self.peek(length) in ' \t': + length += 1 + whitespaces = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch == '\0': + raise ScannerError("while scanning a quoted scalar", start_mark, + "found unexpected end of stream", self.get_mark()) + elif ch in '\r\n\x85\u2028\u2029': + line_break = self.scan_line_break() + breaks = self.scan_flow_scalar_breaks(double, start_mark) + if line_break != '\n': + chunks.append(line_break) + elif not breaks: + chunks.append(' ') + chunks.extend(breaks) + else: + chunks.append(whitespaces) + return chunks + + def scan_flow_scalar_breaks(self, double, start_mark): + # See the specification for details. + chunks = [] + while True: + # Instead of checking indentation, we check for document + # separators. + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + raise ScannerError("while scanning a quoted scalar", start_mark, + "found unexpected document separator", self.get_mark()) + while self.peek() in ' \t': + self.forward() + if self.peek() in '\r\n\x85\u2028\u2029': + chunks.append(self.scan_line_break()) + else: + return chunks + + def scan_plain(self): + # See the specification for details. + # We add an additional restriction for the flow context: + # plain scalars in the flow context cannot contain ',' or '?'. + # We also keep track of the `allow_simple_key` flag here. + # Indentation rules are loosed for the flow context. + chunks = [] + start_mark = self.get_mark() + end_mark = start_mark + indent = self.indent+1 + # We allow zero indentation for scalars, but then we need to check for + # document separators at the beginning of the line. + #if indent == 0: + # indent = 1 + spaces = [] + while True: + length = 0 + if self.peek() == '#': + break + while True: + ch = self.peek(length) + if ch in '\0 \t\r\n\x85\u2028\u2029' \ + or (ch == ':' and + self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029' + + (u',[]{}' if self.flow_level else u''))\ + or (self.flow_level and ch in ',?[]{}'): + break + length += 1 + if length == 0: + break + self.allow_simple_key = False + chunks.extend(spaces) + chunks.append(self.prefix(length)) + self.forward(length) + end_mark = self.get_mark() + spaces = self.scan_plain_spaces(indent, start_mark) + if not spaces or self.peek() == '#' \ + or (not self.flow_level and self.column < indent): + break + return ScalarToken(''.join(chunks), True, start_mark, end_mark) + + def scan_plain_spaces(self, indent, start_mark): + # See the specification for details. + # The specification is really confusing about tabs in plain scalars. + # We just forbid them completely. Do not use tabs in YAML! + chunks = [] + length = 0 + while self.peek(length) in ' ': + length += 1 + whitespaces = self.prefix(length) + self.forward(length) + ch = self.peek() + if ch in '\r\n\x85\u2028\u2029': + line_break = self.scan_line_break() + self.allow_simple_key = True + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return + breaks = [] + while self.peek() in ' \r\n\x85\u2028\u2029': + if self.peek() == ' ': + self.forward() + else: + breaks.append(self.scan_line_break()) + prefix = self.prefix(3) + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': + return + if line_break != '\n': + chunks.append(line_break) + elif not breaks: + chunks.append(' ') + chunks.extend(breaks) + elif whitespaces: + chunks.append(whitespaces) + return chunks + + def scan_tag_handle(self, name, start_mark): + # See the specification for details. + # For some strange reasons, the specification does not allow '_' in + # tag handles. I have allowed it anyway. + ch = self.peek() + if ch != '!': + raise ScannerError("while scanning a %s" % name, start_mark, + "expected '!', but found %r" % ch, self.get_mark()) + length = 1 + ch = self.peek(length) + if ch != ' ': + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': + length += 1 + ch = self.peek(length) + if ch != '!': + self.forward(length) + raise ScannerError("while scanning a %s" % name, start_mark, + "expected '!', but found %r" % ch, self.get_mark()) + length += 1 + value = self.prefix(length) + self.forward(length) + return value + + def scan_tag_uri(self, name, start_mark): + # See the specification for details. + # Note: we do not check if URI is well-formed. + chunks = [] + length = 0 + ch = self.peek(length) + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.!~*\'()[]%': + if ch == '%': + chunks.append(self.prefix(length)) + self.forward(length) + length = 0 + chunks.append(self.scan_uri_escapes(name, start_mark)) + else: + length += 1 + ch = self.peek(length) + if length: + chunks.append(self.prefix(length)) + self.forward(length) + length = 0 + if not chunks: + raise ScannerError("while parsing a %s" % name, start_mark, + "expected URI, but found %r" % ch, self.get_mark()) + return ''.join(chunks) + + def scan_uri_escapes(self, name, start_mark): + # See the specification for details. + codes = [] + mark = self.get_mark() + while self.peek() == '%': + self.forward() + for k in range(2): + if self.peek(k) not in '0123456789ABCDEFabcdef': + raise ScannerError("while scanning a %s" % name, start_mark, + "expected URI escape sequence of 2 hexadecimal numbers, but found %r" + % self.peek(k), self.get_mark()) + codes.append(int(self.prefix(2), 16)) + self.forward(2) + try: + value = bytes(codes).decode('utf-8') + except UnicodeDecodeError as exc: + raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark) + return value + + def scan_line_break(self): + # Transforms: + # '\r\n' : '\n' + # '\r' : '\n' + # '\n' : '\n' + # '\x85' : '\n' + # '\u2028' : '\u2028' + # '\u2029 : '\u2029' + # default : '' + ch = self.peek() + if ch in '\r\n\x85': + if self.prefix(2) == '\r\n': + self.forward(2) + else: + self.forward() + return '\n' + elif ch in '\u2028\u2029': + self.forward() + return ch + return '' diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/serializer.py b/.venv_haddock/lib/python3.12/site-packages/yaml/serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..fe911e67ae7a739abb491fbbc6834b9c37bbda4b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/serializer.py @@ -0,0 +1,111 @@ + +__all__ = ['Serializer', 'SerializerError'] + +from .error import YAMLError +from .events import * +from .nodes import * + +class SerializerError(YAMLError): + pass + +class Serializer: + + ANCHOR_TEMPLATE = 'id%03d' + + def __init__(self, encoding=None, + explicit_start=None, explicit_end=None, version=None, tags=None): + self.use_encoding = encoding + self.use_explicit_start = explicit_start + self.use_explicit_end = explicit_end + self.use_version = version + self.use_tags = tags + self.serialized_nodes = {} + self.anchors = {} + self.last_anchor_id = 0 + self.closed = None + + def open(self): + if self.closed is None: + self.emit(StreamStartEvent(encoding=self.use_encoding)) + self.closed = False + elif self.closed: + raise SerializerError("serializer is closed") + else: + raise SerializerError("serializer is already opened") + + def close(self): + if self.closed is None: + raise SerializerError("serializer is not opened") + elif not self.closed: + self.emit(StreamEndEvent()) + self.closed = True + + #def __del__(self): + # self.close() + + def serialize(self, node): + if self.closed is None: + raise SerializerError("serializer is not opened") + elif self.closed: + raise SerializerError("serializer is closed") + self.emit(DocumentStartEvent(explicit=self.use_explicit_start, + version=self.use_version, tags=self.use_tags)) + self.anchor_node(node) + self.serialize_node(node, None, None) + self.emit(DocumentEndEvent(explicit=self.use_explicit_end)) + self.serialized_nodes = {} + self.anchors = {} + self.last_anchor_id = 0 + + def anchor_node(self, node): + if node in self.anchors: + if self.anchors[node] is None: + self.anchors[node] = self.generate_anchor(node) + else: + self.anchors[node] = None + if isinstance(node, SequenceNode): + for item in node.value: + self.anchor_node(item) + elif isinstance(node, MappingNode): + for key, value in node.value: + self.anchor_node(key) + self.anchor_node(value) + + def generate_anchor(self, node): + self.last_anchor_id += 1 + return self.ANCHOR_TEMPLATE % self.last_anchor_id + + def serialize_node(self, node, parent, index): + alias = self.anchors[node] + if node in self.serialized_nodes: + self.emit(AliasEvent(alias)) + else: + self.serialized_nodes[node] = True + self.descend_resolver(parent, index) + if isinstance(node, ScalarNode): + detected_tag = self.resolve(ScalarNode, node.value, (True, False)) + default_tag = self.resolve(ScalarNode, node.value, (False, True)) + implicit = (node.tag == detected_tag), (node.tag == default_tag) + self.emit(ScalarEvent(alias, node.tag, implicit, node.value, + style=node.style)) + elif isinstance(node, SequenceNode): + implicit = (node.tag + == self.resolve(SequenceNode, node.value, True)) + self.emit(SequenceStartEvent(alias, node.tag, implicit, + flow_style=node.flow_style)) + index = 0 + for item in node.value: + self.serialize_node(item, node, index) + index += 1 + self.emit(SequenceEndEvent()) + elif isinstance(node, MappingNode): + implicit = (node.tag + == self.resolve(MappingNode, node.value, True)) + self.emit(MappingStartEvent(alias, node.tag, implicit, + flow_style=node.flow_style)) + for key, value in node.value: + self.serialize_node(key, node, None) + self.serialize_node(value, node, key) + self.emit(MappingEndEvent()) + self.ascend_resolver() + diff --git a/.venv_haddock/lib/python3.12/site-packages/yaml/tokens.py b/.venv_haddock/lib/python3.12/site-packages/yaml/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0b48a394ac8c019b401516a12f688df361cf90 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/yaml/tokens.py @@ -0,0 +1,104 @@ + +class Token(object): + def __init__(self, start_mark, end_mark): + self.start_mark = start_mark + self.end_mark = end_mark + def __repr__(self): + attributes = [key for key in self.__dict__ + if not key.endswith('_mark')] + attributes.sort() + arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) + for key in attributes]) + return '%s(%s)' % (self.__class__.__name__, arguments) + +#class BOMToken(Token): +# id = '' + +class DirectiveToken(Token): + id = '' + def __init__(self, name, value, start_mark, end_mark): + self.name = name + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class DocumentStartToken(Token): + id = '' + +class DocumentEndToken(Token): + id = '' + +class StreamStartToken(Token): + id = '' + def __init__(self, start_mark=None, end_mark=None, + encoding=None): + self.start_mark = start_mark + self.end_mark = end_mark + self.encoding = encoding + +class StreamEndToken(Token): + id = '' + +class BlockSequenceStartToken(Token): + id = '' + +class BlockMappingStartToken(Token): + id = '' + +class BlockEndToken(Token): + id = '' + +class FlowSequenceStartToken(Token): + id = '[' + +class FlowMappingStartToken(Token): + id = '{' + +class FlowSequenceEndToken(Token): + id = ']' + +class FlowMappingEndToken(Token): + id = '}' + +class KeyToken(Token): + id = '?' + +class ValueToken(Token): + id = ':' + +class BlockEntryToken(Token): + id = '-' + +class FlowEntryToken(Token): + id = ',' + +class AliasToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class AnchorToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class TagToken(Token): + id = '' + def __init__(self, value, start_mark, end_mark): + self.value = value + self.start_mark = start_mark + self.end_mark = end_mark + +class ScalarToken(Token): + id = '' + def __init__(self, value, plain, start_mark, end_mark, style=None): + self.value = value + self.plain = plain + self.start_mark = start_mark + self.end_mark = end_mark + self.style = style +