language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
Netflix__metaflow
metaflow/user_configs/config_parameters.py
{ "start": 13538, "end": 21640 }
class ____(Parameter, collections.abc.Mapping): """ Includes a configuration for this flow. `Config` is a special type of `Parameter` but differs in a few key areas: - it is immutable and determined at deploy time (or prior to running if not deploying to a scheduler) - as such, it can be used anywhere in your code including in Metaflow decorators The value of the configuration is determines as follows: - use the user-provided file path or value. It is an error to provide both - if none are present: - if a default file path (default) is provided, attempt to read this file - if the file is present, use that value. Note that the file will be used even if it has an invalid syntax - if the file is not present, and a default value is present, use that - if still None and is required, this is an error. Parameters ---------- name : str User-visible configuration name. default : Union[str, Callable[[ParameterContext], str], optional, default None Default path from where to read this configuration. A function implies that the value will be computed using that function. You can only specify default or default_value, not both. default_value : Union[str, Dict[str, Any], Callable[[ParameterContext, Union[str, Dict[str, Any]]], Any], optional, default None Default value for the parameter. A function implies that the value will be computed using that function. You can only specify default or default_value, not both. help : str, optional, default None Help text to show in `run --help`. required : bool, optional, default None Require that the user specifies a value for the configuration. Note that if a default or default_value is provided, the required flag is ignored. A value of None is equivalent to False. parser : Union[str, Callable[[str], Dict[Any, Any]]], optional, default None If a callable, it is a function that can parse the configuration string into an arbitrarily nested dictionary. If a string, the string should refer to a function (like "my_parser_package.my_parser.my_parser_function") which should be able to parse the configuration string into an arbitrarily nested dictionary. If the name starts with a ".", it is assumed to be relative to "metaflow". show_default : bool, default True If True, show the default value in the help text. plain : bool, default False If True, the configuration value is just returned as is and not converted to a ConfigValue. Use this is you just want to directly access your configuration. Note that modifications are not persisted across steps (ie: ConfigValue prevents modifications and raises and error -- if you have your own object, no error is raised but no modifications are persisted). You can also use this to return any arbitrary object (not just dictionary-like objects). """ IS_CONFIG_PARAMETER = True def __init__( self, name: str, default: Optional[Union[str, Callable[[ParameterContext], str]]] = None, default_value: Optional[ Union[ str, Dict[str, Any], Callable[[ParameterContext], Union[str, Dict[str, Any]]], ] ] = None, help: Optional[str] = None, required: Optional[bool] = None, parser: Optional[Union[str, Callable[[str], Dict[Any, Any]]]] = None, plain: Optional[bool] = False, **kwargs: Dict[str, str] ): if default is not None and default_value is not None: raise MetaflowException( "For config '%s', you can only specify default or default_value, not both" % name ) self._default_is_file = default is not None kwargs["default"] = default if default is not None else default_value kwargs["plain"] = plain super(Config, self).__init__( name, required=required, help=help, type=str, **kwargs ) super(Config, self).init() if isinstance(kwargs.get("default", None), str): kwargs["default"] = json.dumps(kwargs["default"]) self.parser = parser self._computed_value = None self._delayed_evaluator = None def load_parameter(self, v): return v if v is None or self.kwargs["plain"] else ConfigValue(v) def _store_value(self, v: Any) -> None: self._computed_value = v def _init_delayed_evaluator(self) -> None: if self._delayed_evaluator is None: self._delayed_evaluator = DelayEvaluator(self.name) # Support <config>.<var> syntax def __getattr__(self, name): # Need to return a new DelayEvaluator everytime because the evaluator will # contain the "path" (ie: .name) and can be further accessed. return getattr(DelayEvaluator(self.name), name) # Next three methods are to implement mapping to support **<config> syntax. We # need to be careful, however, to also support a regular `config["key"]` syntax # which calls into `__getitem__` and therefore behaves like __getattr__ above. def __iter__(self): self._init_delayed_evaluator() yield from self._delayed_evaluator def __len__(self): self._init_delayed_evaluator() return len(self._delayed_evaluator) def __getitem__(self, key): self._init_delayed_evaluator() if isinstance(key, str) and key.startswith(UNPACK_KEY): return self._delayed_evaluator[key] return DelayEvaluator(self.name)[key] def resolve_delayed_evaluator( v: Any, ignore_errors: bool = False, to_dict: bool = False ) -> Any: # NOTE: We don't ignore errors in downstream calls because we want to have either # all or nothing for the top-level call by the user. try: if isinstance(v, DelayEvaluator): to_return = v() if to_dict and isinstance(to_return, ConfigValue): to_return = to_return.to_dict() return to_return if isinstance(v, dict): return { resolve_delayed_evaluator( k, to_dict=to_dict ): resolve_delayed_evaluator(v, to_dict=to_dict) for k, v in v.items() } if isinstance(v, list): return [resolve_delayed_evaluator(x, to_dict=to_dict) for x in v] if isinstance(v, tuple): return tuple(resolve_delayed_evaluator(x, to_dict=to_dict) for x in v) if isinstance(v, set): return {resolve_delayed_evaluator(x, to_dict=to_dict) for x in v} return v except Exception as e: if ignore_errors: # Assumption is that default value of None is always allowed. # This code path is *only* used when evaluating Parameters AND they # use configs in their attributes AND the runner/deployer is being used # AND CLICK_API_PROCESS_CONFIG is False. In those cases, all attributes in # Parameter can be set to None except for required and show_default # and even in those cases, a wrong value will have very limited consequence. return None raise e def unpack_delayed_evaluator( to_unpack: Dict[str, Any], ignore_errors: bool = False ) -> Tuple[Dict[str, Any], List[str]]: result = {} new_keys = [] for k, v in to_unpack.items(): if not isinstance(k, str) or not k.startswith(UNPACK_KEY): result[k] = v else: # k.startswith(UNPACK_KEY) try: new_vals = resolve_delayed_evaluator(v, to_dict=True) new_keys.extend(new_vals.keys()) result.update(new_vals) except Exception as e: if ignore_errors: continue raise e return result, new_keys
Config
python
python-excel__xlwt
xlwt/BIFFRecords.py
{ "start": 8012, "end": 8131 }
class ____(BiffRecord): _REC_ID = 0x00C1 def __init__(self): self._rec_data = pack('<H', 0x00)
MMSRecord
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py
{ "start": 30666, "end": 33357 }
class ____(ShopifyBulkQuery): """ { collections(query: "updated_at:>='2023-02-07T00:00:00+00:00' AND updated_at:<='2023-12-04T00:00:00+00:00'", sortKey: UPDATED_AT) { edges { node { __typename id handle title updatedAt bodyHtml: descriptionHtml publications { edges { node { __typename publishedAt: publishDate } } } sortOrder templateSuffix productsCount } } } } """ query_name = "collections" sort_key = "UPDATED_AT" publications_fields: List[Field] = [ Field(name="edges", fields=[Field(name="node", fields=["__typename", Field(name="publishDate", alias="publishedAt")])]) ] query_nodes: List[Field] = [ "__typename", "id", Field(name="handle"), Field(name="title"), Field(name="updatedAt"), Field(name="descriptionHtml", alias="bodyHtml"), Field(name="publications", fields=publications_fields), Field(name="sortOrder"), Field(name="templateSuffix"), Field(name="productsCount", fields=[Field(name="count", alias="products_count")]), ] record_composition = { "new_record": "Collection", # each collection has `publications` "record_components": ["CollectionPublication"], } def record_process_components(self, record: MutableMapping[str, Any]) -> Iterable[MutableMapping[str, Any]]: """ Defines how to process collected components. """ record_components = record.get("record_components", {}) if record_components: publications = record_components.get("CollectionPublication", []) if len(publications) > 0: record["published_at"] = publications[0].get("publishedAt") record.pop("record_components") # convert dates from ISO-8601 to RFC-3339 record["published_at"] = self.tools.from_iso8601_to_rfc3339(record, "published_at") record["updatedAt"] = self.tools.from_iso8601_to_rfc3339(record, "updatedAt") # unnest `product_count` to the root lvl record["products_count"] = record.get("productsCount", {}).get("products_count") # remove leftovers record.pop(BULK_PARENT_KEY, None) yield record
Collection
python
PyCQA__pylint
doc/data/messages/n/not-context-manager/bad.py
{ "start": 0, "end": 128 }
class ____: def __enter__(self): pass with MyContextManager() as c: # [not-context-manager] pass
MyContextManager
python
simonw__datasette
datasette/views/special.py
{ "start": 38819, "end": 40025 }
class ____(SchemaBaseView): """ Displays schema for a specific database. Supports HTML, JSON, and Markdown formats. """ name = "database_schema" async def get(self, request): database_name = request.url_vars["database"] format_ = request.url_vars.get("format") or "html" # Check if database exists if database_name not in self.ds.databases: return self.format_error_response("Database not found", format_) # Check view-database permission await self.ds.ensure_permission( action="view-database", resource=DatabaseResource(database=database_name), actor=request.actor, ) schema = await self.get_database_schema(database_name) if format_ == "json": return self.format_json_response( {"database": database_name, "schema": schema} ) elif format_ == "md": return self.format_markdown_response(f"Schema for {database_name}", schema) else: schemas = [{"database": database_name, "schema": schema}] return await self.format_html_response(request, schemas)
DatabaseSchemaView
python
facebook__pyre-check
client/commands/tests/server_setup.py
{ "start": 3831, "end": 4212 }
class ____(connections.AsyncBytesWriter): """ An AsyncBytesWriter that always raises a given except when write is invoked. """ def __init__(self, exception: Exception) -> None: self.exception = exception async def write(self, data: bytes) -> None: raise self.exception async def close(self) -> None: pass
ExceptionRaisingBytesWriter
python
facebook__pyre-check
client/commands/tests/servers_test.py
{ "start": 1135, "end": 7322 }
class ____(testslide.TestCase): def test_parse_running_server_status(self) -> None: def assert_parsed( input: str, expected: servers.RunningServerStatus, flavor: identifiers.PyreFlavor = identifiers.PyreFlavor.CLASSIC, ) -> None: self.assertEqual( servers.RunningServerStatus.from_server_response(input, flavor), expected, ) def assert_raises(input: str) -> None: with self.assertRaises(servers.InvalidServerResponse): servers.RunningServerStatus.from_server_response( input, identifiers.PyreFlavor.CLASSIC ) assert_raises("42") assert_raises("[]") assert_raises("{}") assert_raises('["Info"]') assert_raises('["Info", 42]') assert_raises('["Derp", "Derp"]') assert_raises('["Info", {"pid": 42}]') assert_raises('["Info", {"pid": 42, "version": "derp"}]') assert_raises( json.dumps( [ "Info", { "pid": "42", "version": "derp", "global_root": "/global", "log_path": "/log", }, ] ) ) assert_raises( json.dumps( [ "Info", { "pid": 42, "version": "derp", "global_root": "/global", "relative_local_root": 0, }, ] ) ) assert_parsed( json.dumps( [ "Info", { "pid": 42, "version": "abc", "global_root": "/global", }, ] ), expected=servers.RunningServerStatus( pid=42, version="abc", global_root="/global", flavor=identifiers.PyreFlavor.CLASSIC.value, ), ) assert_parsed( json.dumps( [ "Info", { "pid": 42, "version": "abc", "global_root": "/global", "extra_field": 0, }, ] ), expected=servers.RunningServerStatus( pid=42, version="abc", global_root="/global", flavor="classic", ), ) assert_parsed( json.dumps( [ "Info", { "pid": 42, "version": "abc", "global_root": "/global", "extra_field": 0, }, ] ), expected=servers.RunningServerStatus( pid=42, version="abc", global_root="/global", flavor="classic", ), ) assert_parsed( json.dumps( [ "Info", { "pid": 42, "version": "abc", "global_root": "/global", "relative_local_root": "local", }, ] ), expected=servers.RunningServerStatus( pid=42, version="abc", global_root="/global", relative_local_root="local", flavor="classic", ), ) def test_find_all_servers(self) -> None: with tempfile.TemporaryDirectory(dir="/tmp") as socket_root: socket_root_path = Path(socket_root) good_socket = socket_root_path / "good.sock" with setup.spawn_unix_stream_server_with_socket( MockServerRequestHandler, socket_path=good_socket ): bad_socket = socket_root_path / "bad.sock" bad_socket.touch() all_server_status = servers.find_all_servers([good_socket, bad_socket]) self.assertListEqual( all_server_status.running, [ servers.RunningServerStatus( pid=42, version="abc", global_root="/global", flavor=identifiers.PyreFlavor.CLASSIC.value, ) ], ) self.assertCountEqual( all_server_status.defunct, [ servers.DefunctServerStatus(str(bad_socket)), ], ) def test_to_json(self) -> None: self.assertCountEqual( servers.AllServerStatus( running=[ servers.RunningServerStatus( pid=123, version="abc", global_root="/g0", flavor=identifiers.PyreFlavor.CLASSIC.value, ), ], defunct=[ servers.DefunctServerStatus(socket_path="/p0.sock"), servers.DefunctServerStatus("/p1.sock"), ], ).to_json(), [ { "status": "running", "pid": 123, "version": "abc", "global_root": "/g0", "relative_local_root": None, "flavor": "classic", }, {"status": "defunct", "socket": "/p0.sock"}, {"status": "defunct", "socket": "/p1.sock"}, ], )
ServersTest
python
pola-rs__polars
py-polars/src/polars/io/partition.py
{ "start": 1554, "end": 3091 }
class ____: """ Callback context for a partition creation using keys. .. warning:: This functionality is currently considered **unstable**. It may be changed at any point without it being considered a breaking change. See Also -------- PartitionByKey PartitionParted """ def __init__( self, file_idx: int, part_idx: int, in_part_idx: int, keys: list[KeyedPartition], file_path: Path, full_path: Path, ) -> None: self.file_idx = file_idx self.part_idx = part_idx self.in_part_idx = in_part_idx self.keys = keys self.file_path = file_path self.full_path = full_path file_idx: int #: The index of the created file starting from zero. part_idx: int #: The index of the created partition starting from zero. in_part_idx: int #: The index of the file within this partition starting from zero. keys: list[KeyedPartition] #: All the key names and values used for this partition. file_path: Path #: The chosen output path before the callback was called without `base_path`. full_path: ( Path #: The chosen output path before the callback was called with `base_path`. ) def hive_dirs(self) -> Path: """The keys mapped to hive directories.""" assert len(self.keys) > 0 p = Path(self.keys[0].hive_name()) for key in self.keys[1:]: p /= Path(key.hive_name()) return p
KeyedPartitionContext
python
ansible__ansible
lib/ansible/plugins/doc_fragments/constructed.py
{ "start": 194, "end": 3320 }
class ____(object): DOCUMENTATION = r""" options: strict: description: - If V(yes) make invalid entries a fatal error, otherwise skip and continue. - Since it is possible to use facts in the expressions they might not always be available and we ignore those errors by default. type: bool default: no compose: description: Create vars from jinja2 expressions. type: dict default: {} groups: description: Add hosts to group based on Jinja2 conditionals. type: dict default: {} keyed_groups: description: Add hosts to group based on the values of a variable. type: list default: [] elements: dict suboptions: parent_group: type: str description: parent group for keyed group. prefix: type: str description: A keyed group name will start with this prefix. default: '' separator: type: str description: separator used to build the keyed group name. default: "_" key: type: str description: - The key from input dictionary used to generate groups. default_value: description: - The default value when the host variable's value is V(None) or an empty string. - This option is mutually exclusive with O(keyed_groups[].trailing_separator). type: str version_added: '2.12' trailing_separator: description: - Set this option to V(false) to omit the O(keyed_groups[].separator) after the host variable when the value is V(None) or an empty string. - This option is mutually exclusive with O(keyed_groups[].default_value). type: bool default: true version_added: '2.12' use_extra_vars: version_added: '2.11' description: Merge extra vars into the available variables for composition (highest precedence). type: bool default: false ini: - section: inventory_plugins key: use_extra_vars env: - name: ANSIBLE_INVENTORY_USE_EXTRA_VARS leading_separator: description: - Use in conjunction with O(keyed_groups). - By default, a keyed group that does not have a prefix or a separator provided will have a name that starts with an underscore. - This is because the default prefix is V("") and the default separator is V("_"). - Set this option to V(false) to omit the leading underscore (or other separator) if no prefix is given. - If the group name is derived from a mapping the separator is still used to concatenate the items. - To not use a separator in the group name at all, set the separator for the keyed group to an empty string instead. type: boolean default: True version_added: '2.11' notes: - Inventories are not finalized at this stage, so the auto populated C(all) and C(ungrouped) groups will only reflect what previous inventory sources explicitly added to them. - Runtime 'magic variables' are not available during inventory construction. For example, C(groups) and C(hostvars) do not exist yet. """
ModuleDocFragment
python
huggingface__transformers
src/transformers/models/olmo2/configuration_olmo2.py
{ "start": 1572, "end": 8851 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Olmo2Model`]. It is used to instantiate an OLMo2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [allenai/Olmo2-7B-1124-hf](https://huggingface.co/allenai/Olmo2-7B-1124-hf). Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 50304): Vocabulary size of the Olmo2 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Olmo2Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 11008): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. pad_token_id (`int`, *optional*, defaults to 1): Padding token id. bos_token_id (`int`, *optional*): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 50279): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings rope_parameters (`RopeParameters`, *optional*): Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. rms_norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. ```python >>> from transformers import Olmo2Model, Olmo2Config >>> # Initializing a Olmo2 7B style configuration >>> configuration = Olmo2Config() >>> # Initializing a model from the Olmo2 7B style configuration >>> model = Olmo2Model(configuration) >>> # Accessing the model configuration >>> configuration = model.config ``` """ model_type = "olmo2" keys_to_ignore_at_inference = ["past_key_values"] base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k "layers.*.self_attn.k_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k "layers.*.self_attn.v_proj": "colwise_rep", # we need to replicate here due to the added norm on q and k "layers.*.self_attn.o_proj": "rowwise_rep", # we need to replicate here due to the added norm on q and k "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), } def __init__( self, vocab_size: Optional[int] = 50304, hidden_size: Optional[int] = 4096, intermediate_size: Optional[int] = 11008, num_hidden_layers: Optional[int] = 32, num_attention_heads: Optional[int] = 32, num_key_value_heads: Optional[int] = None, hidden_act: Optional[str] = "silu", max_position_embeddings: Optional[int] = 2048, initializer_range: Optional[float] = 0.02, use_cache: Optional[bool] = True, pad_token_id: Optional[int] = 1, bos_token_id: Optional[int] = None, eos_token_id: Optional[int] = 50279, tie_word_embeddings: Optional[bool] = False, rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None, attention_bias: Optional[bool] = False, attention_dropout: Optional[float] = 0.0, rms_norm_eps: Optional[int] = 1e-5, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.use_cache = use_cache self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.rope_parameters = rope_parameters super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) self.rms_norm_eps = rms_norm_eps __all__ = ["Olmo2Config"]
Olmo2Config
python
streamlit__streamlit
lib/tests/streamlit/web/cli_test.py
{ "start": 26394, "end": 29970 }
class ____(unittest.TestCase): def tearDown(self) -> None: from streamlit.watcher.event_based_path_watcher import EventBasedPathWatcher EventBasedPathWatcher.close_all() def get_http_session(self) -> requests.Session: http_session = requests.Session() http_session.mount( "https://", HTTPAdapter(max_retries=Retry(total=10, backoff_factor=0.2)) ) http_session.mount("http://", HTTPAdapter(max_retries=None)) return http_session @unittest.skipIf( "win32" in sys.platform, "openssl not present on windows by default" ) def test_ssl(self): with contextlib.ExitStack() as exit_stack: tmp_home = exit_stack.enter_context(tempfile.TemporaryDirectory()) (Path(tmp_home) / ".streamlit").mkdir() (Path(tmp_home) / ".streamlit" / "credentials.toml").write_text( '[general]\nemail = ""', encoding="utf-8" ) cert_file = Path(tmp_home) / "cert.cert" key_file = Path(tmp_home) / "key.key" pem_file = Path(tmp_home) / "public.pem" subprocess.check_call( [ "openssl", "req", "-x509", "-newkey", "rsa:4096", "-keyout", str(key_file), "-out", str(cert_file), "-sha256", "-days", "365", "-nodes", "-subj", "/CN=localhost", # sublectAltName is required by modern browsers # See: https://github.com/urllib3/urllib3/issues/497 "-addext", "subjectAltName = DNS:localhost", ] ) subprocess.check_call( [ "openssl", "x509", "-inform", "PEM", "-in", str(cert_file), "-out", str(pem_file), ] ) https_session = exit_stack.enter_context(self.get_http_session()) proc = exit_stack.enter_context( subprocess.Popen( [ sys.executable, "-m", "streamlit", "hello", "--global.developmentMode=False", "--server.sslCertFile", str(cert_file), "--server.sslKeyFile", str(key_file), "--server.headless", "true", "--server.port=8510", ], env={**os.environ, "HOME": tmp_home}, ) ) try: response = https_session.get( "https://localhost:8510/healthz", verify=str(pem_file) ) response.raise_for_status() assert response.text == "ok" # HTTP traffic is restricted with pytest.raises(requests.exceptions.ConnectionError): response = https_session.get("http://localhost:8510/healthz") response.raise_for_status() finally: proc.kill()
HTTPServerIntegrationTest
python
plotly__plotly.py
plotly/graph_objs/sunburst/marker/colorbar/_tickfont.py
{ "start": 233, "end": 9959 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "sunburst.marker.colorbar" _path_str = "sunburst.marker.colorbar.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @property def color(self): """ The 'color' 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 Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') Returns ------- Any """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] Returns ------- Any """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] Returns ------- Any """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] Returns ------- Any """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') Returns ------- int """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def _prop_descriptions(self): return """\ color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. """ def __init__( self, arg=None, color=None, family=None, lineposition=None, shadow=None, size=None, style=None, textcase=None, variant=None, weight=None, **kwargs, ): """ Construct a new Tickfont object Sets the color bar's tick label font Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.sunburst.marke r.colorbar.Tickfont` color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. Returns ------- Tickfont """ super().__init__("tickfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.sunburst.marker.colorbar.Tickfont constructor must be a dict or an instance of :class:`plotly.graph_objs.sunburst.marker.colorbar.Tickfont`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("family", arg, family) self._set_property("lineposition", arg, lineposition) self._set_property("shadow", arg, shadow) self._set_property("size", arg, size) self._set_property("style", arg, style) self._set_property("textcase", arg, textcase) self._set_property("variant", arg, variant) self._set_property("weight", arg, weight) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Tickfont
python
doocs__leetcode
solution/1900-1999/1947.Maximum Compatibility Score Sum/Solution.py
{ "start": 0, "end": 733 }
class ____: def maxCompatibilitySum( self, students: List[List[int]], mentors: List[List[int]] ) -> int: def dfs(i: int, s: int): if i >= m: nonlocal ans ans = max(ans, s) return for j in range(m): if not vis[j]: vis[j] = True dfs(i + 1, s + g[i][j]) vis[j] = False ans = 0 m = len(students) vis = [False] * m g = [[0] * m for _ in range(m)] for i, x in enumerate(students): for j, y in enumerate(mentors): g[i][j] = sum(a == b for a, b in zip(x, y)) dfs(0, 0) return ans
Solution
python
pyca__cryptography
tests/hazmat/primitives/test_ed448.py
{ "start": 1396, "end": 12650 }
class ____: @pytest.mark.parametrize( "vector", load_vectors_from_file( os.path.join("asymmetric", "Ed448", "rfc8032.txt"), load_nist_vectors, ), ) def test_sign_input(self, vector, backend): if vector.get("context") is not None: pytest.skip("ed448 contexts are not currently supported") sk = binascii.unhexlify(vector["secret"]) pk = binascii.unhexlify(vector["public"]) message = binascii.unhexlify(vector["message"]) signature = binascii.unhexlify(vector["signature"]) private_key = Ed448PrivateKey.from_private_bytes(sk) computed_sig = private_key.sign(message) assert computed_sig == signature public_key = private_key.public_key() assert ( public_key.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw ) == pk ) public_key.verify(signature, message) def test_invalid_signature(self, backend): key = Ed448PrivateKey.generate() signature = key.sign(b"test data") with pytest.raises(InvalidSignature): key.public_key().verify(signature, b"wrong data") with pytest.raises(InvalidSignature): key.public_key().verify(b"0" * 64, b"test data") def test_sign_verify_buffer(self, backend): key = Ed448PrivateKey.generate() data = bytearray(b"test data") signature = key.sign(data) key.public_key().verify(bytearray(signature), data) def test_generate(self, backend): key = Ed448PrivateKey.generate() assert key assert key.public_key() @pytest.mark.parametrize( "vector", load_vectors_from_file( os.path.join("asymmetric", "Ed448", "rfc8032.txt"), load_nist_vectors, ), ) def test_pub_priv_bytes_raw(self, vector, backend): sk = binascii.unhexlify(vector["secret"]) pk = binascii.unhexlify(vector["public"]) private_key = Ed448PrivateKey.from_private_bytes(sk) assert ( private_key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption(), ) == sk ) assert private_key.private_bytes_raw() == sk assert ( private_key.public_key().public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw ) == pk ) assert private_key.public_key().public_bytes_raw() == pk public_key = Ed448PublicKey.from_public_bytes(pk) assert ( public_key.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw ) == pk ) assert public_key.public_bytes_raw() == pk @pytest.mark.parametrize( ("encoding", "fmt", "encryption", "passwd", "load_func"), [ ( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.BestAvailableEncryption(b"password"), b"password", serialization.load_pem_private_key, ), ( serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.BestAvailableEncryption(b"password"), b"password", serialization.load_der_private_key, ), ( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption(), None, serialization.load_pem_private_key, ), ( serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.NoEncryption(), None, serialization.load_der_private_key, ), ], ) def test_round_trip_private_serialization( self, encoding, fmt, encryption, passwd, load_func, backend ): key = Ed448PrivateKey.generate() serialized = key.private_bytes(encoding, fmt, encryption) loaded_key = load_func(serialized, passwd, backend) assert isinstance(loaded_key, Ed448PrivateKey) def test_invalid_type_public_bytes(self, backend): with pytest.raises(TypeError): Ed448PublicKey.from_public_bytes( object() # type: ignore[arg-type] ) def test_invalid_type_private_bytes(self, backend): with pytest.raises(TypeError): Ed448PrivateKey.from_private_bytes( object() # type: ignore[arg-type] ) def test_invalid_length_from_public_bytes(self, backend): with pytest.raises(ValueError): Ed448PublicKey.from_public_bytes(b"a" * 56) with pytest.raises(ValueError): Ed448PublicKey.from_public_bytes(b"a" * 58) def test_invalid_length_from_private_bytes(self, backend): with pytest.raises(ValueError): Ed448PrivateKey.from_private_bytes(b"a" * 56) with pytest.raises(ValueError): Ed448PrivateKey.from_private_bytes(b"a" * 58) def test_invalid_private_bytes(self, backend): key = Ed448PrivateKey.generate() with pytest.raises(TypeError): key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, None, # type: ignore[arg-type] ) with pytest.raises(ValueError): key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, DummyKeySerializationEncryption(), ) with pytest.raises(ValueError): key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.PKCS8, DummyKeySerializationEncryption(), ) with pytest.raises(ValueError): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.Raw, serialization.NoEncryption(), ) def test_invalid_public_bytes(self, backend): key = Ed448PrivateKey.generate().public_key() with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.SubjectPublicKeyInfo, ) with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.PKCS1 ) with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.Raw ) def test_invalid_public_key_pem(self): with pytest.raises(ValueError): serialization.load_pem_public_key( textwrap.dedent(""" -----BEGIN PUBLIC KEY----- MCswBQYDK2VxAyIA//////////////////////////////////////////// -----END PUBLIC KEY-----""").encode() ) def test_buffer_protocol(self, backend): private_bytes = os.urandom(57) key = Ed448PrivateKey.from_private_bytes(bytearray(private_bytes)) assert ( key.private_bytes( serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption(), ) == private_bytes ) def test_malleability(self, backend): # This is a signature where r > the group order. It should be # rejected to prevent signature malleability issues. This test can # be removed when wycheproof grows ed448 vectors public_bytes = binascii.unhexlify( "fedb02a658d74990244d9d10cf338e977565cbbda6b24c716829ed6ee1e4f28cf" "2620c052db8d878f6243bffc22242816c1aaa67d2f3603600" ) signature = binascii.unhexlify( "0cc16ba24d69277f927c1554b0f08a2a711bbdd20b058ccc660d00ca13542a3ce" "f9e5c44c54ab23a2eb14f947e167b990b080863e28b399380f30db6e54d5d1406" "d23378ffde11b1fb81b2b438a3b8e8aa7f7f4e1befcc905023fab5a5465053844" "f04cf0c1b51d84760f869588687f57500" ) key = Ed448PublicKey.from_public_bytes(public_bytes) with pytest.raises(InvalidSignature): key.verify(signature, b"8") @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), skip_message="Requires OpenSSL with Ed448 support", ) def test_public_key_equality(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "Ed448", "ed448-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None).public_key() key2 = serialization.load_der_private_key(key_bytes, None).public_key() key3 = Ed448PrivateKey.generate().public_key() assert key1 == key2 assert key1 != key3 assert key1 != object() with pytest.raises(TypeError): key1 < key2 # type: ignore[operator] @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), skip_message="Requires OpenSSL with Ed448 support", ) def test_public_key_copy(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "Ed448", "ed448-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None).public_key() key2 = copy.copy(key1) assert key1 == key2 @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), skip_message="Requires OpenSSL with Ed448 support", ) def test_public_key_deepcopy(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "Ed448", "ed448-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None).public_key() key2 = copy.deepcopy(key1) assert key1 == key2 @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), skip_message="Requires OpenSSL with Ed448 support", ) def test_private_key_copy(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "Ed448", "ed448-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None) key2 = copy.copy(key1) assert key1 == key2 @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), skip_message="Requires OpenSSL with Ed448 support", ) def test_private_key_deepcopy(backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "Ed448", "ed448-pkcs8.der"), lambda derfile: derfile.read(), mode="rb", ) key1 = serialization.load_der_private_key(key_bytes, None) key2 = copy.deepcopy(key1) assert key1 == key2
TestEd448Signing
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/class_interval.py
{ "start": 7290, "end": 7762 }
class ____(A17): @classmethod def m1(cls, arg): sink_c(arg) def test_class_methods(): # Expect no issue B17.m0(_test_source()) # Expect no issue as well b = B17() b.m0(_test_source()) # Expect an issue, which is not pruned away by class intervals (unlike the # above call to B17.m0), because the receiver objects on the sink trace # change from B17 to D17 (instead of remaining the same B17) B17.m2(_test_source())
D17
python
python-poetry__poetry
tests/console/test_application_global_options.py
{ "start": 857, "end": 1236 }
class ____(Command): name = "check-project-path" description = "Check Project Path Command" def handle(self) -> int: if not self.poetry.pyproject_path.exists(): raise RuntimeError( f"Wrong project path in handle: {self.poetry.pyproject_path}\nWorking directory: {Path.cwd()}" ) return 0
CheckProjectPathCommand
python
pandas-dev__pandas
pandas/io/formats/info.py
{ "start": 14266, "end": 15828 }
class ____(_BaseInfo): """ Class storing series-specific info. """ def __init__( self, data: Series, memory_usage: bool | str | None = None, ) -> None: self.data: Series = data self.memory_usage = _initialize_memory_usage(memory_usage) def render( self, *, buf: WriteBuffer[str] | None = None, max_cols: int | None = None, verbose: bool | None = None, show_counts: bool | None = None, ) -> None: if max_cols is not None: raise ValueError( "Argument `max_cols` can only be passed " "in DataFrame.info, not Series.info" ) printer = _SeriesInfoPrinter( info=self, verbose=verbose, show_counts=show_counts, ) printer.to_buffer(buf) @property def non_null_counts(self) -> list[int]: return [self.data.count()] @property def dtypes(self) -> Iterable[Dtype]: return [self.data.dtypes] @property def dtype_counts(self) -> Mapping[str, int]: from pandas.core.frame import DataFrame return _get_dataframe_dtype_counts(DataFrame(self.data)) @property def memory_usage_bytes(self) -> int: """Memory usage in bytes. Returns ------- memory_usage_bytes : int Object's total memory usage in bytes. """ deep = self.memory_usage == "deep" return self.data.memory_usage(index=True, deep=deep)
SeriesInfo
python
sanic-org__sanic
sanic/signals.py
{ "start": 4011, "end": 4114 }
class ____(RouteGroup): """A `RouteGroup` that is used to dispatch signals to handlers"""
SignalGroup
python
miyuchina__mistletoe
test/test_cli.py
{ "start": 123, "end": 5579 }
class ____(TestCase): @patch('mistletoe.cli.parse', return_value=Mock(filenames=[], renderer=sentinel.Renderer)) @patch('mistletoe.cli.interactive') def test_main_to_interactive(self, mock_interactive, mock_parse): cli.main(None) mock_interactive.assert_called_with(sentinel.Renderer) @patch('mistletoe.cli.parse', return_value=Mock(filenames=['foo.md'], renderer=sentinel.Renderer)) @patch('mistletoe.cli.convert') def test_main_to_convert(self, mock_convert, mock_parse): cli.main(None) mock_convert.assert_called_with(['foo.md'], sentinel.Renderer) @patch('importlib.import_module', return_value=Mock(Renderer=sentinel.RendererCls)) def test_parse_renderer(self, mock_import_module): namespace = cli.parse(['-r', 'foo.Renderer']) mock_import_module.assert_called_with('foo') self.assertEqual(namespace.renderer, sentinel.RendererCls) def test_parse_filenames(self): filenames = ['foo.md', 'bar.md'] namespace = cli.parse(filenames) self.assertEqual(namespace.filenames, filenames) @patch('mistletoe.cli.convert_file') def test_convert(self, mock_convert_file): filenames = ['foo', 'bar'] cli.convert(filenames, sentinel.RendererCls) calls = [call(filename, sentinel.RendererCls) for filename in filenames] mock_convert_file.assert_has_calls(calls) @patch('mistletoe.markdown', return_value='rendered text') @patch('sys.stdout.buffer.write') @patch('builtins.open', new_callable=mock_open) def test_convert_file_success(self, mock_open_, mock_write, mock_markdown): filename = 'foo' cli.convert_file(filename, sentinel.RendererCls) mock_open_.assert_called_with(filename, 'r', encoding='utf-8') mock_write.assert_called_with('rendered text'.encode()) @patch('builtins.open', side_effect=OSError) @patch('sys.exit') def test_convert_file_fail(self, mock_exit, mock_open_): filename = 'foo' cli.convert_file(filename, sentinel.RendererCls) mock_open_.assert_called_with(filename, 'r', encoding='utf-8') mock_exit.assert_called_with('Cannot open file "foo".') @patch('mistletoe.cli._import_readline') @patch('mistletoe.cli._print_heading') @patch('mistletoe.markdown', return_value='rendered text') @patch('builtins.print') def test_interactive(self, mock_print, mock_markdown, mock_print_heading, mock_import_readline): def MockInputFactory(return_values): _counter = -1 def mock_input(prompt=''): nonlocal _counter _counter += 1 if _counter < len(return_values): return return_values[_counter] elif _counter == len(return_values): raise EOFError else: raise KeyboardInterrupt return mock_input return_values = ['foo', 'bar', 'baz'] with patch('builtins.input', MockInputFactory(return_values)): cli.interactive(sentinel.RendererCls) mock_import_readline.assert_called_with() mock_print_heading.assert_called_with(sentinel.RendererCls) mock_markdown.assert_called_with(['foo\n', 'bar\n', 'baz\n'], sentinel.RendererCls) calls = [call('\nrendered text', end=''), call('\nExiting.')] mock_print.assert_has_calls(calls) @patch('importlib.import_module', return_value=Mock(Renderer=sentinel.RendererCls)) def test_import_success(self, mock_import_module): self.assertEqual(sentinel.RendererCls, cli._import('foo.Renderer')) @patch('sys.exit') def test_import_incomplete_path(self, mock_exit): cli._import('foo') error_msg = '[error] please supply full path to your custom renderer.' mock_exit.assert_called_with(error_msg) @patch('importlib.import_module', side_effect=ImportError) @patch('sys.exit') def test_import_module_error(self, mock_exit, mock_import_module): cli._import('foo.Renderer') mock_exit.assert_called_with('[error] cannot import module "foo".') @patch('importlib.import_module', return_value=Mock(spec=[])) @patch('sys.exit') def test_import_class_error(self, mock_exit, mock_import_module): cli._import('foo.Renderer') error_msg = '[error] cannot find renderer "Renderer" from module "foo".' mock_exit.assert_called_with(error_msg) @patch('builtins.__import__') @patch('builtins.print') def test_import_readline_success(self, mock_print, mock_import): cli._import_readline() mock_print.assert_not_called() @patch('builtins.__import__', side_effect=ImportError) @patch('builtins.print') def test_import_readline_fail(self, mock_print, mock_import): cli._import_readline() mock_print.assert_called_with('[warning] readline library not available.') @patch('builtins.print') def test_print_heading(self, mock_print): cli._print_heading(Mock(__name__='Renderer')) version = cli.mistletoe.__version__ msgs = ['mistletoe [version {}] (interactive)'.format(version), 'Type Ctrl-D to complete input, or Ctrl-C to exit.', 'Using renderer: Renderer'] calls = [call(msg) for msg in msgs] mock_print.assert_has_calls(calls)
TestCli
python
kamyu104__LeetCode-Solutions
Python/reach-a-number.py
{ "start": 46, "end": 372 }
class ____(object): def reachNumber(self, target): """ :type target: int :rtype: int """ target = abs(target) k = int(math.ceil((-1+math.sqrt(1+8*target))/2)) target -= k*(k+1)/2 return k if target%2 == 0 else k+1+k%2 # Time: O(sqrt(n)) # Space: O(1)
Solution
python
bokeh__bokeh
tests/unit/bokeh/util/test_strings.py
{ "start": 2999, "end": 3444 }
class ____: TEXT = "some text\nto indent\n goes here" def test_default_args(self) -> None: assert bus.indent(self.TEXT) == " some text\n to indent\n goes here" def test_with_n(self) -> None: assert bus.indent(self.TEXT, n=3) == " some text\n to indent\n goes here" def test_with_ch(self) -> None: assert bus.indent(self.TEXT, ch="-") == "--some text\n--to indent\n-- goes here"
Test_indent
python
spyder-ide__spyder
external-deps/python-lsp-server/test/plugins/test_folding.py
{ "start": 644, "end": 1750 }
class ____(): def method(self, x1): def inner(): return x1 if x2: func(3, 4, 5, 6, 7) elif x3 < 2: pass else: more_complex_func(2, 3, 4, 5, 6, 8) return inner a = 2 operation = (a_large_variable_that_fills_all_space + other_embarrasingly_long_variable - 2 * 3 / 5) (a, b, c, d, e, f) = func(3, 4, 5, 6, 7, 8, 9, 10) for i in range(0, 3): i += 1 while x < i: expr = (2, 4) a = func(expr + i, arg2, arg3, arg4, arg5, var(2, 3, 4, 5)) for j in range(0, i): if i % 2 == 1: pass compren = [x for x in range(0, 3) if x == 2] with open('doc', 'r') as f: try: f / 0 except: pass finally: raise SomeException() def testC(): pass """ ) SYNTAX_ERR = dedent( """ def func(arg1, arg2, arg3, arg4, arg5, default=func( 2, 3, 4 )): return (2, 3, 4, 5)
A
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/output.py
{ "start": 12383, "end": 16586 }
class ____( NamedTuple( "_Out", [ ("dagster_type", PublicAttr[Union[DagsterType, type[NoValueSentinel]]]), ("description", PublicAttr[Optional[str]]), ("is_required", PublicAttr[bool]), ("io_manager_key", PublicAttr[str]), ("metadata", PublicAttr[Optional[RawMetadataMapping]]), ("code_version", PublicAttr[Optional[str]]), ], ) ): """Defines an output from an op's compute function. Ops can have multiple outputs, in which case outputs cannot be anonymous. Many ops have only one output, in which case the user can provide a single output definition that will be given the default name, "result". Outs may be typed using the Dagster type system. Args: dagster_type (Optional[Union[Type, DagsterType]]]): The type of this output. Should only be set if the correct type can not be inferred directly from the type signature of the decorated function. description (Optional[str]): Human-readable description of the output. is_required (bool): Whether the presence of this field is required. (default: True) io_manager_key (Optional[str]): The resource key of the output manager used for this output. (default: "io_manager"). metadata (Optional[Dict[str, Any]]): A dict of the metadata for the output. For example, users can provide a file path if the data object will be stored in a filesystem, or provide information of a database table when it is going to load the data into the table. code_version (Optional[str]): Version of the code that generates this output. In general, versions should be set only for code that deterministically produces the same output when given the same inputs. """ def __new__( cls, dagster_type: Optional[Union[type, DagsterType]] = NoValueSentinel, description: Optional[str] = None, is_required: bool = True, io_manager_key: Optional[str] = None, metadata: Optional[ArbitraryMetadataMapping] = None, code_version: Optional[str] = None, # make sure new parameters are updated in combine_with_inferred below ): return super().__new__( cls, dagster_type=( NoValueSentinel if dagster_type is NoValueSentinel else resolve_dagster_type(dagster_type) ), description=description, is_required=check.bool_param(is_required, "is_required"), io_manager_key=check.opt_str_param( io_manager_key, "io_manager_key", default=DEFAULT_IO_MANAGER_KEY ), metadata=metadata, code_version=code_version, ) @classmethod def from_definition(cls, output_def: "OutputDefinition"): klass = Out if not output_def.is_dynamic else DynamicOut return klass( dagster_type=output_def.dagster_type, description=output_def.description, is_required=output_def.is_required, io_manager_key=output_def.io_manager_key, metadata=output_def.metadata, code_version=output_def.code_version, ) def to_definition( self, annotation_type: type, name: Optional[str], description: Optional[str], code_version: Optional[str], ) -> "OutputDefinition": dagster_type = ( self.dagster_type if self.dagster_type is not NoValueSentinel else _checked_inferred_type(annotation_type) ) klass = OutputDefinition if not self.is_dynamic else DynamicOutputDefinition return klass( dagster_type=dagster_type, name=name, description=self.description or description, is_required=self.is_required, io_manager_key=self.io_manager_key, metadata=self.metadata, code_version=self.code_version or code_version, ) @property def is_dynamic(self) -> bool: return False @public
Out
python
kamyu104__LeetCode-Solutions
Python/maximum-deletions-on-a-string.py
{ "start": 36, "end": 706 }
class ____(object): def deleteString(self, s): """ :type s: str :rtype: int """ if all(x == s[0] for x in s): return len(s) dp2 = [[0]*(len(s)+1) for i in xrange(2)] # dp2[i%2][j]: max prefix length of s[i:] and s[j:] dp = [1]*len(s) # dp[i]: max operation count of s[i:] for i in reversed(xrange(len(s)-1)): for j in xrange(i+1, len(s)): dp2[i%2][j] = dp2[(i+1)%2][j+1]+1 if s[j] == s[i] else 0 if dp2[i%2][j] >= j-i: dp[i] = max(dp[i], dp[j]+1) return dp[0] # Time: O(n^2) # Space: O(n) # dp, kmp algorithm
Solution
python
pytorch__pytorch
test/test_legacy_vmap.py
{ "start": 35686, "end": 38398 }
class ____: class TestVmapBaseLegacy(TestCase): def __init__(self, method_name="runTest"): super().__init__(method_name) test_method = getattr(self, method_name, None) if test_method is None: return if not should_allow_vmap_fallback_usage(test_method): setattr( self, method_name, self._wrap_method_with_vmap_fallback_check(test_method), ) def _wrap_method_with_vmap_fallback_check(self, method): msg = ( "Expected the test to not invoke the vmap fallback path, i.e., " "all of the operators being tested in this test should have batching " "rules implemented. If you are intentionally testing something to " "do with the fallback path, use allowVmapFallbackUsage. Otherwise, " "please make sure that batching rules are implemented for the " "operator(s) being tested." ) @functools.wraps(method) def wrapper(self, *args, **kwargs): with warnings.catch_warnings(record=True) as wa: warnings.simplefilter("always") with EnableVmapFallbackWarnings(): method(*args, **kwargs) for captured_warning in wa: self.assertNotRegex( str(captured_warning.message), FALLBACK_REGEX, msg ) return types.MethodType(wrapper, self) @allowVmapFallbackUsage def test_vmap_fallback_check_ok(self): # One day we'll implement a batching rule for torch.var_mean. # When that happens, please change the example to use an # operator that doesn't have a batching rule implemented. op_using_fallback = torch.var_mean vmap(op_using_fallback)(torch.rand(3)) def test_vmap_fallback_check(self): @self._wrap_method_with_vmap_fallback_check def no_fallback(self): pass # One day we'll implement a batching rule for torch.var_mean. # When that happens, please change the example to use an # operator that doesn't have a batching rule implemented. op_using_fallback = torch.var_mean @self._wrap_method_with_vmap_fallback_check def uses_fallback(self): vmap(op_using_fallback)(torch.rand(3)) no_fallback(self) with self.assertRaises(AssertionError): uses_fallback(self)
Namespace
python
keras-team__keras
keras/src/export/saved_model.py
{ "start": 1322, "end": 28425 }
class ____(BackendExportArchive): """ExportArchive is used to write SavedModel artifacts (e.g. for inference). If you have a Keras model or layer that you want to export as SavedModel for serving (e.g. via TensorFlow-Serving), you can use `ExportArchive` to configure the different serving endpoints you need to make available, as well as their signatures. Simply instantiate an `ExportArchive`, use `track()` to register the layer(s) or model(s) to be used, then use the `add_endpoint()` method to register a new serving endpoint. When done, use the `write_out()` method to save the artifact. The resulting artifact is a SavedModel and can be reloaded via `tf.saved_model.load`. Examples: Here's how to export a model for inference. ```python export_archive = ExportArchive() export_archive.track(model) export_archive.add_endpoint( name="serve", fn=model.call, input_signature=[keras.InputSpec(shape=(None, 3), dtype="float32")], ) export_archive.write_out("path/to/location") # Elsewhere, we can reload the artifact and serve it. # The endpoint we added is available as a method: serving_model = tf.saved_model.load("path/to/location") outputs = serving_model.serve(inputs) ``` Here's how to export a model with one endpoint for inference and one endpoint for a training-mode forward pass (e.g. with dropout on). ```python export_archive = ExportArchive() export_archive.track(model) export_archive.add_endpoint( name="call_inference", fn=lambda x: model.call(x, training=False), input_signature=[keras.InputSpec(shape=(None, 3), dtype="float32")], ) export_archive.add_endpoint( name="call_training", fn=lambda x: model.call(x, training=True), input_signature=[keras.InputSpec(shape=(None, 3), dtype="float32")], ) export_archive.write_out("path/to/location") ``` **Note on resource tracking:** `ExportArchive` is able to automatically track all `keras.Variables` used by its endpoints, so most of the time calling `.track(model)` is not strictly required. However, if your model uses lookup layers such as `IntegerLookup`, `StringLookup`, or `TextVectorization`, it will need to be tracked explicitly via `.track(model)`. Explicit tracking is also required if you need to be able to access the properties `variables`, `trainable_variables`, or `non_trainable_variables` on the revived archive. """ def __init__(self): super().__init__() if backend.backend() not in ("tensorflow", "jax", "torch"): raise NotImplementedError( "`ExportArchive` is only compatible with TensorFlow, JAX and " "Torch backends." ) self._endpoint_names = [] self._endpoint_signatures = {} self.tensorflow_version = tf.__version__ self._tf_trackable = tf.__internal__.tracking.AutoTrackable() self._tf_trackable.variables = [] self._tf_trackable.trainable_variables = [] self._tf_trackable.non_trainable_variables = [] @property def variables(self): return self._tf_trackable.variables @property def trainable_variables(self): return self._tf_trackable.trainable_variables @property def non_trainable_variables(self): return self._tf_trackable.non_trainable_variables def track(self, resource): """Track the variables (of a layer or model) and other assets. By default, all variables used by an endpoint function are automatically tracked when you call `add_endpoint()`. However, non-variables assets such as lookup tables need to be tracked manually. Note that lookup tables used by built-in Keras layers (`TextVectorization`, `IntegerLookup`, `StringLookup`) are automatically tracked by `add_endpoint()`. Args: resource: A layer, model or a TensorFlow trackable resource. """ if isinstance(resource, layers.Layer) and not resource.built: raise ValueError( "The layer provided has not yet been built. " "It must be built before export." ) # Note: with the TensorFlow backend, Layers and Models fall into both # the Layer case and the Trackable case. The Trackable case is needed # for preprocessing layers in order to track lookup tables. if isinstance(resource, tf.__internal__.tracking.Trackable): if not hasattr(self, "_tracked"): self._tracked = [] self._tracked.append(resource) if isinstance(resource, layers.Layer): self._track_layer(resource) elif not isinstance(resource, tf.__internal__.tracking.Trackable): raise ValueError( "Invalid resource type. Expected a Keras `Layer` or `Model` " "or a TensorFlow `Trackable` object. " f"Received object {resource} of type '{type(resource)}'. " ) def add_endpoint(self, name, fn, input_signature=None, **kwargs): """Register a new serving endpoint. Args: name: `str`. The name of the endpoint. fn: A callable. It should only leverage resources (e.g. `keras.Variable` objects or `tf.lookup.StaticHashTable` objects) that are available on the models/layers tracked by the `ExportArchive` (you can call `.track(model)` to track a new model). The shape and dtype of the inputs to the function must be known. For that purpose, you can either 1) make sure that `fn` is a `tf.function` that has been called at least once, or 2) provide an `input_signature` argument that specifies the shape and dtype of the inputs (see below). input_signature: Optional. Specifies the shape and dtype of `fn`. Can be a structure of `keras.InputSpec`, `tf.TensorSpec`, `backend.KerasTensor`, or backend tensor (see below for an example showing a `Functional` model with 2 input arguments). If not provided, `fn` must be a `tf.function` that has been called at least once. Defaults to `None`. **kwargs: Additional keyword arguments: - Specific to the JAX backend: - `is_static`: Optional `bool`. Indicates whether `fn` is static. Set to `False` if `fn` involves state updates (e.g., RNG seeds). - `jax2tf_kwargs`: Optional `dict`. Arguments for `jax2tf.convert`. See [`jax2tf.convert`]( https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md). If `native_serialization` and `polymorphic_shapes` are not provided, they are automatically computed. Returns: The `tf.function` wrapping `fn` that was added to the archive. Example: Adding an endpoint using the `input_signature` argument when the model has a single input argument: ```python export_archive = ExportArchive() export_archive.track(model) export_archive.add_endpoint( name="serve", fn=model.call, input_signature=[keras.InputSpec(shape=(None, 3), dtype="float32")], ) ``` Adding an endpoint using the `input_signature` argument when the model has two positional input arguments: ```python export_archive = ExportArchive() export_archive.track(model) export_archive.add_endpoint( name="serve", fn=model.call, input_signature=[ keras.InputSpec(shape=(None, 3), dtype="float32"), keras.InputSpec(shape=(None, 4), dtype="float32"), ], ) ``` Adding an endpoint using the `input_signature` argument when the model has one input argument that is a list of 2 tensors (e.g. a Functional model with 2 inputs): ```python model = keras.Model(inputs=[x1, x2], outputs=outputs) export_archive = ExportArchive() export_archive.track(model) export_archive.add_endpoint( name="serve", fn=model.call, input_signature=[ [ keras.InputSpec(shape=(None, 3), dtype="float32"), keras.InputSpec(shape=(None, 4), dtype="float32"), ], ], ) ``` This also works with dictionary inputs: ```python model = keras.Model(inputs={"x1": x1, "x2": x2}, outputs=outputs) export_archive = ExportArchive() export_archive.track(model) export_archive.add_endpoint( name="serve", fn=model.call, input_signature=[ { "x1": keras.InputSpec(shape=(None, 3), dtype="float32"), "x2": keras.InputSpec(shape=(None, 4), dtype="float32"), }, ], ) ``` Adding an endpoint that is a `tf.function`: ```python @tf.function() def serving_fn(x): return model(x) # The function must be traced, i.e. it must be called at least once. serving_fn(tf.random.normal(shape=(2, 3))) export_archive = ExportArchive() export_archive.track(model) export_archive.add_endpoint(name="serve", fn=serving_fn) ``` Combining a model with some TensorFlow preprocessing, which can use TensorFlow resources: ```python lookup_table = tf.lookup.StaticHashTable(initializer, default_value=0.0) export_archive = ExportArchive() model_fn = export_archive.track_and_add_endpoint( "model_fn", model, input_signature=[tf.TensorSpec(shape=(None, 5), dtype=tf.float32)], ) export_archive.track(lookup_table) @tf.function() def serving_fn(x): x = lookup_table.lookup(x) return model_fn(x) export_archive.add_endpoint(name="serve", fn=serving_fn) ``` """ if name in self._endpoint_names: raise ValueError(f"Endpoint name '{name}' is already taken.") if backend.backend() != "jax": if "jax2tf_kwargs" in kwargs or "is_static" in kwargs: raise ValueError( "'jax2tf_kwargs' and 'is_static' are only supported with " f"the jax backend. Current backend: {backend.backend()}" ) # The fast path if `fn` is already a `tf.function`. if input_signature is None: if isinstance(fn, tf.types.experimental.GenericFunction): if not fn._list_all_concrete_functions(): raise ValueError( f"The provided tf.function '{fn}' " "has never been called. " "To specify the expected shape and dtype " "of the function's arguments, " "you must either provide a function that " "has been called at least once, or alternatively pass " "an `input_signature` argument in `add_endpoint()`." ) decorated_fn = fn else: raise ValueError( "If the `fn` argument provided is not a `tf.function`, " "you must provide an `input_signature` argument to " "specify the shape and dtype of the function arguments. " "Example:\n\n" "export_archive.add_endpoint(\n" " name='call',\n" " fn=model.call,\n" " input_signature=[\n" " keras.InputSpec(\n" " shape=(None, 224, 224, 3),\n" " dtype='float32',\n" " )\n" " ],\n" ")" ) setattr(self._tf_trackable, name, decorated_fn) self._endpoint_names.append(name) return decorated_fn input_signature = tree.map_structure( make_tf_tensor_spec, input_signature ) decorated_fn = super().add_endpoint(name, fn, input_signature, **kwargs) self._endpoint_signatures[name] = input_signature setattr(self._tf_trackable, name, decorated_fn) self._endpoint_names.append(name) return decorated_fn def track_and_add_endpoint(self, name, resource, input_signature, **kwargs): """Track the variables and register a new serving endpoint. This function combines the functionality of `track` and `add_endpoint`. It tracks the variables of the `resource` (either a layer or a model) and registers a serving endpoint using `resource.__call__`. Args: name: `str`. The name of the endpoint. resource: A trackable Keras resource, such as a layer or model. input_signature: Optional. Specifies the shape and dtype of `fn`. Can be a structure of `keras.InputSpec`, `tf.TensorSpec`, `backend.KerasTensor`, or backend tensor (see below for an example showing a `Functional` model with 2 input arguments). If not provided, `fn` must be a `tf.function` that has been called at least once. Defaults to `None`. **kwargs: Additional keyword arguments: - Specific to the JAX backend: - `is_static`: Optional `bool`. Indicates whether `fn` is static. Set to `False` if `fn` involves state updates (e.g., RNG seeds). - `jax2tf_kwargs`: Optional `dict`. Arguments for `jax2tf.convert`. See [`jax2tf.convert`]( https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md). If `native_serialization` and `polymorphic_shapes` are not provided, they are automatically computed. """ if name in self._endpoint_names: raise ValueError(f"Endpoint name '{name}' is already taken.") if not isinstance(resource, layers.Layer): raise ValueError( "Invalid resource type. Expected an instance of a Keras " "`Layer` or `Model`. " f"Received: resource={resource} (of type {type(resource)})" ) if not resource.built: raise ValueError( "The layer provided has not yet been built. " "It must be built before export." ) if backend.backend() != "jax": if "jax2tf_kwargs" in kwargs or "is_static" in kwargs: raise ValueError( "'jax2tf_kwargs' and 'is_static' are only supported with " f"the jax backend. Current backend: {backend.backend()}" ) input_signature = tree.map_structure( make_tf_tensor_spec, input_signature ) if not hasattr(BackendExportArchive, "track_and_add_endpoint"): # Default behavior. self.track(resource) return self.add_endpoint( name, resource.__call__, input_signature, **kwargs ) else: # Special case for the torch backend. decorated_fn = super().track_and_add_endpoint( name, resource, input_signature, **kwargs ) self._endpoint_signatures[name] = input_signature setattr(self._tf_trackable, name, decorated_fn) self._endpoint_names.append(name) return decorated_fn def add_variable_collection(self, name, variables): """Register a set of variables to be retrieved after reloading. Arguments: name: The string name for the collection. variables: A tuple/list/set of `keras.Variable` instances. Example: ```python export_archive = ExportArchive() export_archive.track(model) # Register an endpoint export_archive.add_endpoint( name="serve", fn=model.call, input_signature=[keras.InputSpec(shape=(None, 3), dtype="float32")], ) # Save a variable collection export_archive.add_variable_collection( name="optimizer_variables", variables=model.optimizer.variables) export_archive.write_out("path/to/location") # Reload the object revived_object = tf.saved_model.load("path/to/location") # Retrieve the variables optimizer_variables = revived_object.optimizer_variables ``` """ if not isinstance(variables, (list, tuple, set)): raise ValueError( "Expected `variables` to be a list/tuple/set. " f"Received instead object of type '{type(variables)}'." ) # Ensure that all variables added are either tf.Variables # or Variables created by Keras 3 with the TF or JAX backends. if not all( isinstance(v, (tf.Variable, backend.Variable)) for v in variables ): raise ValueError( "Expected all elements in `variables` to be " "`tf.Variable` instances. Found instead the following types: " f"{list(set(type(v) for v in variables))}" ) if backend.backend() == "jax": variables = tree.flatten( tree.map_structure(self._convert_to_tf_variable, variables) ) setattr(self._tf_trackable, name, list(variables)) def write_out(self, filepath, options=None, verbose=True): """Write the corresponding SavedModel to disk. Arguments: filepath: `str` or `pathlib.Path` object. Path where to save the artifact. options: `tf.saved_model.SaveOptions` object that specifies SavedModel saving options. verbose: whether to print all the variables of an exported SavedModel. **Note on TF-Serving**: all endpoints registered via `add_endpoint()` are made visible for TF-Serving in the SavedModel artifact. In addition, the first endpoint registered is made visible under the alias `"serving_default"` (unless an endpoint with the name `"serving_default"` was already registered manually), since TF-Serving requires this endpoint to be set. """ if not self._endpoint_names: raise ValueError( "No endpoints have been set yet. Call add_endpoint()." ) self._filter_and_track_resources() signatures = {} for name in self._endpoint_names: signatures[name] = self._get_concrete_fn(name) # Add "serving_default" signature key for TFServing if "serving_default" not in self._endpoint_names: signatures["serving_default"] = self._get_concrete_fn( self._endpoint_names[0] ) tf.saved_model.save( self._tf_trackable, filepath, options=options, signatures=signatures, ) # Print out available endpoints if verbose: endpoints = "\n\n".join( _print_signature( getattr(self._tf_trackable, name), name, verbose=verbose ) for name in self._endpoint_names ) io_utils.print_msg( f"Saved artifact at '{filepath}'. " "The following endpoints are available:\n\n" f"{endpoints}" ) def _convert_to_tf_variable(self, backend_variable): if not isinstance(backend_variable, backend.Variable): raise TypeError( "`backend_variable` must be a `backend.Variable`. " f"Recevied: backend_variable={backend_variable} of type " f"({type(backend_variable)})" ) return tf.Variable( backend_variable.value, dtype=backend_variable.dtype, trainable=backend_variable.trainable, name=backend_variable.name, ) def _get_concrete_fn(self, endpoint): """Workaround for some SavedModel quirks.""" if endpoint in self._endpoint_signatures: return getattr(self._tf_trackable, endpoint) else: traces = getattr(self._tf_trackable, endpoint)._trackable_children( "saved_model" ) return list(traces.values())[0] def _get_variables_used_by_endpoints(self): fns = [self._get_concrete_fn(name) for name in self._endpoint_names] return _list_variables_used_by_fns(fns) def _filter_and_track_resources(self): """Track resources used by endpoints / referenced in `track()` calls.""" # Start by extracting variables from endpoints. fns = [self._get_concrete_fn(name) for name in self._endpoint_names] tvs, ntvs = _list_variables_used_by_fns(fns) self._tf_trackable._all_variables = list(tvs + ntvs) # Next, track lookup tables. # Hopefully, one day this will be automated at the tf.function level. self._tf_trackable._misc_assets = [] from tensorflow.saved_model.experimental import TrackableResource if hasattr(self, "_tracked"): for root in self._tracked: descendants = tf.train.TrackableView(root).descendants() for trackable in descendants: if isinstance(trackable, TrackableResource): self._tf_trackable._misc_assets.append(trackable) def export_saved_model( model, filepath, verbose=None, input_signature=None, **kwargs ): """Export the model as a TensorFlow SavedModel artifact for inference. This method lets you export a model to a lightweight SavedModel artifact that contains the model's forward pass only (its `call()` method) and can be served via e.g. TensorFlow Serving. The forward pass is registered under the name `serve()` (see example below). The original code of the model (including any custom layers you may have used) is *no longer* necessary to reload the artifact -- it is entirely standalone. Args: filepath: `str` or `pathlib.Path` object. The path to save the artifact. verbose: `bool`. Whether to print a message during export. Defaults to `None`, which uses the default value set by different backends and formats. input_signature: Optional. Specifies the shape and dtype of the model inputs. Can be a structure of `keras.InputSpec`, `tf.TensorSpec`, `backend.KerasTensor`, or backend tensor. If not provided, it will be automatically computed. Defaults to `None`. **kwargs: Additional keyword arguments: - Specific to the JAX backend: - `is_static`: Optional `bool`. Indicates whether `fn` is static. Set to `False` if `fn` involves state updates (e.g., RNG seeds). - `jax2tf_kwargs`: Optional `dict`. Arguments for `jax2tf.convert`. See [`jax2tf.convert`]( https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md). If `native_serialization` and `polymorphic_shapes` are not provided, they are automatically computed. **Note:** This feature is currently supported only with TensorFlow, JAX and Torch backends. Support for the Torch backend is experimental. **Note:** The dynamic shape feature is not yet supported with Torch backend. As a result, you must fully define the shapes of the inputs using `input_signature`. If `input_signature` is not provided, all instances of `None` (such as the batch size) will be replaced with `1`. Example: ```python # Export the model as a TensorFlow SavedModel artifact model.export("path/to/location", format="tf_saved_model") # Load the artifact in a different process/environment reloaded_artifact = tf.saved_model.load("path/to/location") predictions = reloaded_artifact.serve(input_data) ``` If you would like to customize your serving endpoints, you can use the lower-level `keras.export.ExportArchive` class. The `export()` method relies on `ExportArchive` internally. """ if verbose is None: verbose = True # Defaults to `True` for all backends. export_archive = ExportArchive() if input_signature is None: input_signature = get_input_signature(model) export_archive.track_and_add_endpoint( DEFAULT_ENDPOINT_NAME, model, input_signature, **kwargs ) export_archive.write_out(filepath, verbose=verbose) def _print_signature(fn, name, verbose=True): concrete_fn = fn._list_all_concrete_functions()[0] pprinted_signature = concrete_fn.pretty_printed_signature(verbose=verbose) lines = pprinted_signature.split("\n") lines = [f"* Endpoint '{name}'"] + lines[1:] endpoint = "\n".join(lines) return endpoint def _list_variables_used_by_fns(fns): trainable_variables = [] non_trainable_variables = [] trainable_variables_ids = set() non_trainable_variables_ids = set() for fn in fns: if hasattr(fn, "concrete_functions"): concrete_functions = fn.concrete_functions elif hasattr(fn, "get_concrete_function"): concrete_functions = [fn.get_concrete_function()] else: concrete_functions = [fn] for concrete_fn in concrete_functions: for v in concrete_fn.trainable_variables: if id(v) not in trainable_variables_ids: trainable_variables.append(v) trainable_variables_ids.add(id(v)) for v in concrete_fn.variables: if ( id(v) not in trainable_variables_ids and id(v) not in non_trainable_variables_ids ): non_trainable_variables.append(v) non_trainable_variables_ids.add(id(v)) return trainable_variables, non_trainable_variables
ExportArchive
python
takluyver__flit
flit_core/flit_core/sdist.py
{ "start": 751, "end": 1685 }
class ____: """Manage a set of file inclusion/exclusion patterns relative to basedir""" def __init__(self, patterns, basedir): self.basedir = basedir self.dirs = set() self.files = set() for pattern in patterns: for path in sorted(glob(osp.join(basedir, pattern), recursive=True)): rel = osp.relpath(path, basedir) if osp.isdir(path): self.dirs.add(rel) else: self.files.add(rel) def match_file(self, rel_path): if rel_path in self.files: return True return any(rel_path.startswith(d + os.sep) for d in self.dirs) def match_dir(self, rel_path): if rel_path in self.dirs: return True # Check if it's a subdirectory of any directory in the list return any(rel_path.startswith(d + os.sep) for d in self.dirs)
FilePatterns
python
huggingface__transformers
src/transformers/models/data2vec/modular_data2vec_audio.py
{ "start": 2324, "end": 2386 }
class ____(Wav2Vec2SamePadLayer): pass
Data2VecAudioPadLayer
python
matplotlib__matplotlib
lib/matplotlib/font_manager.py
{ "start": 19748, "end": 32971 }
class ____: """ A class for storing and manipulating font properties. The font properties are the six properties described in the `W3C Cascading Style Sheet, Level 1 <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font specification and *math_fontfamily* for math fonts: - family: A list of font names in decreasing order of priority. The items may include a generic font family name, either 'sans-serif', 'serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actual font to be used will be looked up from the associated rcParam during the search process in `.findfont`. Default: :rc:`font.family` - style: Either 'normal', 'italic' or 'oblique'. Default: :rc:`font.style` - variant: Either 'normal' or 'small-caps'. Default: :rc:`font.variant` - stretch: A numeric value in the range 0-1000 or one of 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded' or 'ultra-expanded'. Default: :rc:`font.stretch` - weight: A numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'. Default: :rc:`font.weight` - size: Either a relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large' or an absolute font size, e.g., 10. Default: :rc:`font.size` - math_fontfamily: The family of fonts used to render math text. Supported values are: 'dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans' and 'custom'. Default: :rc:`mathtext.fontset` Alternatively, a font may be specified using the absolute path to a font file, by using the *fname* kwarg. However, in this case, it is typically simpler to just pass the path (as a `pathlib.Path`, not a `str`) to the *font* kwarg of the `.Text` object. The preferred usage of font sizes is to use the relative values, e.g., 'large', instead of absolute font sizes, e.g., 12. This approach allows all text sizes to be made larger or smaller based on the font manager's default font size. This class accepts a single positional string as fontconfig_ pattern_, or alternatively individual properties as keyword arguments:: FontProperties(pattern) FontProperties(*, family=None, style=None, variant=None, ...) This support does not depend on fontconfig; we are merely borrowing its pattern syntax for use here. .. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/ .. _pattern: https://www.freedesktop.org/software/fontconfig/fontconfig-user.html Note that Matplotlib's internal font manager and fontconfig use a different algorithm to lookup fonts, so the results of the same pattern may be different in Matplotlib than in other applications that use fontconfig. """ @_cleanup_fontproperties_init def __init__(self, family=None, style=None, variant=None, weight=None, stretch=None, size=None, fname=None, # if set, it's a hardcoded filename to use math_fontfamily=None): self.set_family(family) self.set_style(style) self.set_variant(variant) self.set_weight(weight) self.set_stretch(stretch) self.set_file(fname) self.set_size(size) self.set_math_fontfamily(math_fontfamily) # Treat family as a fontconfig pattern if it is the only parameter # provided. Even in that case, call the other setters first to set # attributes not specified by the pattern to the rcParams defaults. if (isinstance(family, str) and style is None and variant is None and weight is None and stretch is None and size is None and fname is None): self.set_fontconfig_pattern(family) @classmethod def _from_any(cls, arg): """ Generic constructor which can build a `.FontProperties` from any of the following: - a `.FontProperties`: it is passed through as is; - `None`: a `.FontProperties` using rc values is used; - an `os.PathLike`: it is used as path to the font file; - a `str`: it is parsed as a fontconfig pattern; - a `dict`: it is passed as ``**kwargs`` to `.FontProperties`. """ if arg is None: return cls() elif isinstance(arg, cls): return arg elif isinstance(arg, os.PathLike): return cls(fname=arg) elif isinstance(arg, str): return cls(arg) else: return cls(**arg) def __hash__(self): l = (tuple(self.get_family()), self.get_slant(), self.get_variant(), self.get_weight(), self.get_stretch(), self.get_size(), self.get_file(), self.get_math_fontfamily()) return hash(l) def __eq__(self, other): return hash(self) == hash(other) def __str__(self): return self.get_fontconfig_pattern() def get_family(self): """ Return a list of individual font family names or generic family names. The font families or generic font families (which will be resolved from their respective rcParams when searching for a matching font) in the order of preference. """ return self._family def get_name(self): """ Return the name of the font that best matches the font properties. """ return get_font(findfont(self)).family_name def get_style(self): """ Return the font style. Values are: 'normal', 'italic' or 'oblique'. """ return self._slant def get_variant(self): """ Return the font variant. Values are: 'normal' or 'small-caps'. """ return self._variant def get_weight(self): """ Set the font weight. Options are: A numeric value in the range 0-1000 or one of 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black' """ return self._weight def get_stretch(self): """ Return the font stretch or width. Options are: 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'. """ return self._stretch def get_size(self): """ Return the font size. """ return self._size def get_file(self): """ Return the filename of the associated font. """ return self._file def get_fontconfig_pattern(self): """ Get a fontconfig_ pattern_ suitable for looking up the font as specified with fontconfig's ``fc-match`` utility. This support does not depend on fontconfig; we are merely borrowing its pattern syntax for use here. """ return generate_fontconfig_pattern(self) def set_family(self, family): """ Change the font family. Can be either an alias (generic name is CSS parlance), such as: 'serif', 'sans-serif', 'cursive', 'fantasy', or 'monospace', a real font name or a list of real font names. Real font names are not supported when :rc:`text.usetex` is `True`. Default: :rc:`font.family` """ family = mpl._val_or_rc(family, 'font.family') if isinstance(family, str): family = [family] self._family = family def set_style(self, style): """ Set the font style. Parameters ---------- style : {'normal', 'italic', 'oblique'}, default: :rc:`font.style` """ style = mpl._val_or_rc(style, 'font.style') _api.check_in_list(['normal', 'italic', 'oblique'], style=style) self._slant = style def set_variant(self, variant): """ Set the font variant. Parameters ---------- variant : {'normal', 'small-caps'}, default: :rc:`font.variant` """ variant = mpl._val_or_rc(variant, 'font.variant') _api.check_in_list(['normal', 'small-caps'], variant=variant) self._variant = variant def set_weight(self, weight): """ Set the font weight. Parameters ---------- weight : int or {'ultralight', 'light', 'normal', 'regular', 'book', \ 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', \ 'extra bold', 'black'}, default: :rc:`font.weight` If int, must be in the range 0-1000. """ weight = mpl._val_or_rc(weight, 'font.weight') if weight in weight_dict: self._weight = weight return try: weight = int(weight) except ValueError: pass else: if 0 <= weight <= 1000: self._weight = weight return raise ValueError(f"{weight=} is invalid") def set_stretch(self, stretch): """ Set the font stretch or width. Parameters ---------- stretch : int or {'ultra-condensed', 'extra-condensed', 'condensed', \ 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', \ 'ultra-expanded'}, default: :rc:`font.stretch` If int, must be in the range 0-1000. """ stretch = mpl._val_or_rc(stretch, 'font.stretch') if stretch in stretch_dict: self._stretch = stretch return try: stretch = int(stretch) except ValueError: pass else: if 0 <= stretch <= 1000: self._stretch = stretch return raise ValueError(f"{stretch=} is invalid") def set_size(self, size): """ Set the font size. Parameters ---------- size : float or {'xx-small', 'x-small', 'small', 'medium', \ 'large', 'x-large', 'xx-large'}, default: :rc:`font.size` If a float, the font size in points. The string values denote sizes relative to the default font size. """ size = mpl._val_or_rc(size, 'font.size') try: size = float(size) except ValueError: try: scale = font_scalings[size] except KeyError as err: raise ValueError( "Size is invalid. Valid font size are " + ", ".join(map(str, font_scalings))) from err else: size = scale * FontManager.get_default_size() if size < 1.0: _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. ' 'Setting fontsize = 1 pt', size) size = 1.0 self._size = size def set_file(self, file): """ Set the filename of the fontfile to use. In this case, all other properties will be ignored. """ self._file = os.fspath(file) if file is not None else None def set_fontconfig_pattern(self, pattern): """ Set the properties by parsing a fontconfig_ *pattern*. This support does not depend on fontconfig; we are merely borrowing its pattern syntax for use here. """ for key, val in parse_fontconfig_pattern(pattern).items(): if type(val) is list: getattr(self, "set_" + key)(val[0]) else: getattr(self, "set_" + key)(val) def get_math_fontfamily(self): """ Return the name of the font family used for math text. The default font is :rc:`mathtext.fontset`. """ return self._math_fontfamily def set_math_fontfamily(self, fontfamily): """ Set the font family for text in math mode. If not set explicitly, :rc:`mathtext.fontset` will be used. Parameters ---------- fontfamily : str The name of the font family. Available font families are defined in the :ref:`default matplotlibrc file <customizing-with-matplotlibrc-files>`. See Also -------- .text.Text.get_math_fontfamily """ if fontfamily is None: fontfamily = mpl.rcParams['mathtext.fontset'] else: valid_fonts = _validators['mathtext.fontset'].valid.values() # _check_in_list() Validates the parameter math_fontfamily as # if it were passed to rcParams['mathtext.fontset'] _api.check_in_list(valid_fonts, math_fontfamily=fontfamily) self._math_fontfamily = fontfamily def copy(self): """Return a copy of self.""" return copy.copy(self) # Aliases set_name = set_family get_slant = get_style set_slant = set_style get_size_in_points = get_size
FontProperties
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/toys/error_monster.py
{ "start": 1468, "end": 6207 }
class ____: pass def resource_init(init_context): if init_context.resource_config["throw_on_resource_init"]: raise Exception("throwing from in resource_fn") return ErrorableResource() def define_errorable_resource(): return ResourceDefinition( resource_fn=resource_init, config_schema={ "throw_on_resource_init": Field(bool, is_required=False, default_value=False) }, ) op_throw_config = { "throw_in_op": Field(bool, is_required=False, default_value=False), "failure_in_op": Field(bool, is_required=False, default_value=False), "crash_in_op": Field(bool, is_required=False, default_value=False), "return_wrong_type": Field(bool, is_required=False, default_value=False), "request_retry": Field(bool, is_required=False, default_value=False), } def _act_on_config(op_config): if op_config["crash_in_op"]: segfault() if op_config["failure_in_op"]: try: raise ExampleException("sample cause exception") except ExampleException as e: raise Failure( description="I'm a Failure", metadata={ "metadata_label": "I am metadata text", }, ) from e elif op_config["throw_in_op"]: raise ExampleException("I threw up") elif op_config["request_retry"]: raise RetryRequested() @op( out=Out(Int), config_schema=op_throw_config, required_resource_keys={"errorable_resource"}, ) def emit_num(context): _act_on_config(context.op_config) if context.op_config["return_wrong_type"]: return "wow" return 13 @op( ins={"num": In(Int)}, out=Out(String), config_schema=op_throw_config, required_resource_keys={"errorable_resource"}, ) def num_to_str(context, num): _act_on_config(context.op_config) if context.op_config["return_wrong_type"]: return num + num return str(num) @op( ins={"string": In(str)}, out=Out(Int), config_schema=op_throw_config, required_resource_keys={"errorable_resource"}, ) def str_to_num(context, string): _act_on_config(context.op_config) if context.op_config["return_wrong_type"]: return string + string return int(string) @graph( description=( "Demo graph that enables configurable types of errors thrown during job execution, " "including op execution errors, type errors, and resource initialization errors." ) ) def error_monster(): start = emit_num.alias("start")() middle = num_to_str.alias("middle")(num=start) str_to_num.alias("end")(string=middle) error_monster_passing_job = error_monster.to_job( resource_defs={ "errorable_resource": define_errorable_resource(), "io_manager": errorable_io_manager, }, config={ "resources": {"errorable_resource": {"config": {"throw_on_resource_init": False}}}, "ops": { "end": {"config": {"return_wrong_type": False, "throw_in_op": False}}, "middle": {"config": {"return_wrong_type": False, "throw_in_op": False}}, "start": {"config": {"return_wrong_type": False, "throw_in_op": False}}, }, }, tags={"monster": "error"}, executor_def=in_process_executor, name="error_monster_passing_job", ) error_monster_failing_job = error_monster.to_job( resource_defs={ "errorable_resource": define_errorable_resource(), "io_manager": errorable_io_manager, }, config={ "resources": {"errorable_resource": {"config": {"throw_on_resource_init": False}}}, "ops": { "end": {"config": {"return_wrong_type": False, "throw_in_op": False}}, "middle": {"config": {"return_wrong_type": False, "throw_in_op": True}}, "start": {"config": {"return_wrong_type": False, "throw_in_op": False}}, }, }, tags={"monster": "error"}, executor_def=in_process_executor, name="error_monster_failing_job", ) if __name__ == "__main__": result = error_monster.to_job( config={ "ops": { "start": {"config": {"throw_in_op": False, "return_wrong_type": False}}, "middle": {"config": {"throw_in_op": False, "return_wrong_type": True}}, "end": {"config": {"throw_in_op": False, "return_wrong_type": False}}, }, "resources": {"errorable_resource": {"config": {"throw_on_resource_init": False}}}, }, tags={"monster": "error"}, resource_defs={ "errorable_resource": define_errorable_resource(), "io_manager": errorable_io_manager, }, ).execute_in_process()
ErrorableResource
python
PyCQA__pylint
tests/functional/p/postponed/postponed_evaluation_pep585.py
{ "start": 1186, "end": 1381 }
class ____(typing.TypedDict): my_var: list[int] # Check dataclasses def my_decorator(*args, **kwargs): def wraps(*args, **kwargs): pass return wraps @dataclass
CustomTypedDict4
python
pytorch__pytorch
torch/_subclasses/fake_utils.py
{ "start": 6266, "end": 10311 }
class ____(TorchDispatchMode): def __init__( self, ignore_op_fn: Union[Callable[[OpOverload], bool], None] = None, *, check_strides=True, check_aliasing=True, only_check_ops_with_meta=True, ): super().__init__() self.ignore_op_fn = ( ignore_op_fn if ignore_op_fn is not None else lambda fn: False ) self.check_strides = check_strides self.check_aliasing = check_aliasing self.only_check_ops_with_meta = only_check_ops_with_meta def __torch_dispatch__(self, func, types, args=(), kwargs=None): kwargs = kwargs or {} fake_r = None # empty_like excluded for now due to sparse complex # aten._to_dense.default this one is getting called with csc if ( func not in ( aten.lift_fresh.default, aten.lift_fresh_copy.default, aten.set_.source_Storage_storage_offset, ) and not self.ignore_op_fn(func) and ( not self.only_check_ops_with_meta or torch._subclasses.fake_impls.has_meta(func) ) and torch.Tag.dynamic_output_shape not in func.tags and torch.Tag.inplace_view not in func.tags and torch.Tag.data_dependent_output not in func.tags ): # Do not import symbolic_shapes at the top of the module as it imports sympy and that's slow from torch.fx.experimental.symbolic_shapes import ShapeEnv try: # TODO: enable_python_dispatcher() here with FakeTensorMode(shape_env=ShapeEnv()) as fake_mode: fake_args, fake_kwargs = pytree.tree_map_only( torch.Tensor, functools.partial(fake_mode.from_tensor, static_shapes=True), (args, kwargs), ) with warnings.catch_warnings(): fake_r = func(*fake_args, **fake_kwargs) except UnsupportedFakeTensorException: pass context = ( f"When comparing the output of {func} on FakeTensor and concrete Tensors, " f"found" ) r = func(*args, **kwargs) if fake_r is not None: r_flat = pytree.tree_leaves(r) f_flat = pytree.tree_leaves(fake_r) assert len(f_flat) == len(r_flat), ( f"{context} mismatch in number of returns {len(f_flat)} != {len(r_flat)}" ) if self.check_aliasing: _check_alias_info( context, r, (args, kwargs), fake_r, (fake_args, fake_kwargs) ) for idx, (r_out, f_out) in enumerate( zip(pytree.tree_leaves(r), pytree.tree_leaves(fake_r)) ): r_is_ten = isinstance(r_out, torch.Tensor) assert r_is_ten == isinstance(f_out, torch.Tensor), ( f"{context} mismatched number of tensor outputs" ) if r_is_ten: try: _check_fake_real_tensors( r_out, f_out, sizes=True, strides=self.check_strides, storage_offset=True, requires_grad=True, ) except Exception as e: if is_sdpa_error(func, idx, e): continue error_message = ( f"{context} mismatched tensor metadata: {e}" if len(r_flat) == 1 else f"{context} mismatched tensor metadata for output[{idx}]: {e}" ) raise MetadataMismatchError(error_message) from e return r
CrossRefFakeMode
python
pytransitions__transitions
transitions/extensions/states.py
{ "start": 2111, "end": 4750 }
class ____(State): """Adds timeout functionality to a state. Timeouts are handled model-specific. Attributes: timeout (float): Seconds after which a timeout function should be called. on_timeout (list): Functions to call when a timeout is triggered. """ dynamic_methods = ['on_timeout'] def __init__(self, *args, **kwargs): """ Args: **kwargs: If kwargs contain 'timeout', assign the float value to self.timeout. If timeout is set, 'on_timeout' needs to be passed with kwargs as well or an AttributeError will be thrown. If timeout is not passed or equal 0. """ self.timeout = kwargs.pop('timeout', 0) self._on_timeout = None if self.timeout > 0: try: self.on_timeout = kwargs.pop('on_timeout') except KeyError: raise AttributeError("Timeout state requires 'on_timeout' when timeout is set.") # from KeyError else: self._on_timeout = kwargs.pop('on_timeout', []) self.runner = {} super(Timeout, self).__init__(*args, **kwargs) def enter(self, event_data): """Extends `transitions.core.State.enter` by starting a timeout timer for the current model when the state is entered and self.timeout is larger than 0. """ if self.timeout > 0: timer = Timer(self.timeout, self._process_timeout, args=(event_data,)) timer.daemon = True timer.start() self.runner[id(event_data.model)] = timer return super(Timeout, self).enter(event_data) def exit(self, event_data): """Extends `transitions.core.State.exit` by canceling a timer for the current model.""" timer = self.runner.get(id(event_data.model), None) if timer is not None and timer.is_alive(): timer.cancel() return super(Timeout, self).exit(event_data) def _process_timeout(self, event_data): _LOGGER.debug("%sTimeout state %s. Processing callbacks...", event_data.machine.name, self.name) for callback in self.on_timeout: event_data.machine.callback(callback, event_data) _LOGGER.info("%sTimeout state %s processed.", event_data.machine.name, self.name) @property def on_timeout(self): """List of strings and callables to be called when the state timeouts.""" return self._on_timeout @on_timeout.setter def on_timeout(self, value): """Listifies passed values and assigns them to on_timeout.""" self._on_timeout = listify(value)
Timeout
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 42894, "end": 43772 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, query_path: str, api_key: str, query_params: Optional[str] = None ): """Airbyte Source for Us Census. Documentation can be found at https://docs.airbyte.com/integrations/sources/us-census Args: name (str): The name of the destination. query_params (Optional[str]): The query parameters portion of the GET request, without the api key query_path (str): The path portion of the GET request api_key (str): Your API Key. Get your key here. """ self.query_params = check.opt_str_param(query_params, "query_params") self.query_path = check.str_param(query_path, "query_path") self.api_key = check.str_param(api_key, "api_key") super().__init__("Us Census", name)
UsCensusSource
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/ci/__init__.py
{ "start": 19618, "end": 22790 }
class ____(Enum): json = "json" markdown = "markdown" @app.command(help="Show status of the current build session") def status( statedir: str = STATEDIR_OPTION, output_format: StatusOutputFormat = typer.Option("json", help="Output format for build status"), ): state_store = state.FileStore(statedir=statedir) location_states = state_store.list_locations() if output_format == StatusOutputFormat.json: for location in location_states: ui.print(location.json()) elif output_format == StatusOutputFormat.markdown: ui.print(report.markdown_report(location_states)) @app.command(help="Update the PR comment with the latest status for branch deployments in Github.") def notify( statedir: str = STATEDIR_OPTION, project_dir: str = typer.Option("."), ): state_store = state.FileStore(statedir=statedir) location_states = state_store.list_locations() source = metrics.get_source() if source == CliEventTags.source.github: event = github_context.get_github_event(project_dir) msg = f"Your pull request at commit `{event.github_sha}` is automatically being deployed to Dagster Cloud." event.update_pr_comment( msg + "\n\n" + report.markdown_report(location_states), orig_author="github-actions[bot]", orig_text="Dagster Cloud", # used to identify original comment ) else: raise ui.error("'dagster-cloud ci notify' is only available within Github actions.") @app.command(help="List locations in the current build session") def locations_list( statedir: str = STATEDIR_OPTION, ): state_store = state.FileStore(statedir=statedir) for location in state_store.list_locations(): if location.selected: ui.print(f"{location.location_name}") else: ui.print(f"{location.location_name} DESELECTED") @app.command(help="Mark the specified locations as excluded from the current build session") def locations_deselect( location_names: list[str], statedir: str = STATEDIR_OPTION, ): state_store = state.FileStore(statedir=statedir) state_store.deselect(location_names) ui.print("Deselected locations: {locations_names}") @app.command(help="Mark the specified locations as included in the current build session") def locations_select( location_names: list[str], statedir: str = STATEDIR_OPTION, ): state_store = state.FileStore(statedir=statedir) state_store.select(location_names) ui.print("Deselected locations: {locations_names}") def _get_selected_locations( state_store: state.Store, location_name: list[str] ) -> dict[str, state.LocationState]: requested_locations = set(location_name) selected = { location.location_name: location for location in state_store.list_selected_locations() if not requested_locations or location.location_name in requested_locations } unknown_locations = requested_locations - set(selected) if unknown_locations: raise ui.error(f"Unknown or deselected location names requested: {unknown_locations}") return selected
StatusOutputFormat
python
getsentry__sentry
src/sentry/issues/ingest.py
{ "start": 5513, "end": 16292 }
class ____(TypedDict): type: str culprit: str | None metadata: Mapping[str, Any] title: str location: str | None last_received: str @sentry_sdk.tracing.trace def materialize_metadata(occurrence: IssueOccurrence, event: Event) -> OccurrenceMetadata: """ Returns the materialized metadata to be merged with issue. """ event_type = get_event_type(event.data) event_metadata = dict(event_type.get_metadata(event.data)) event_metadata = dict(event_metadata) # Don't clobber existing metadata event_metadata.update(event.get_event_metadata()) event_metadata["title"] = occurrence.issue_title event_metadata["value"] = occurrence.subtitle event_metadata["initial_priority"] = occurrence.priority if occurrence.type == FeedbackGroup: # TODO: Should feedbacks be their own event type, so above call to event.get_event_medata # could populate this instead? # Or potentially, could add a method to GroupType called get_metadata event_metadata["contact_email"] = occurrence.evidence_data.get("contact_email") event_metadata["message"] = occurrence.evidence_data.get("message") event_metadata["name"] = occurrence.evidence_data.get("name") event_metadata["source"] = occurrence.evidence_data.get("source") event_metadata["summary"] = occurrence.evidence_data.get("summary") associated_event_id = occurrence.evidence_data.get("associated_event_id") if associated_event_id: event_metadata["associated_event_id"] = associated_event_id return { "type": event_type.key, "title": occurrence.issue_title, "culprit": occurrence.culprit, "metadata": event_metadata, "location": event.location, "last_received": json.datetime_to_str(event.datetime), } @sentry_sdk.tracing.trace @metrics.wraps("issues.ingest.save_issue_from_occurrence") def save_issue_from_occurrence( occurrence: IssueOccurrence, event: Event, release: Release | None ) -> GroupInfo | None: project = event.project issue_kwargs = _create_issue_kwargs(occurrence, event, release) # We need to augment the message with occurrence data here since we can't build a `GroupEvent` # until after we have created a `Group`. issue_kwargs["message"] = augment_message_with_occurrence(issue_kwargs["message"], occurrence) existing_grouphashes = { gh.hash: gh for gh in GroupHash.objects.filter( project=project, hash__in=occurrence.fingerprint ).select_related("group") } primary_grouphash = None for fingerprint_hash in occurrence.fingerprint: if fingerprint_hash in existing_grouphashes: primary_grouphash = existing_grouphashes[fingerprint_hash] break if not primary_grouphash: primary_hash = occurrence.fingerprint[0] cluster_key = settings.SENTRY_ISSUE_PLATFORM_RATE_LIMITER_OPTIONS.get("cluster", "default") client = redis.redis_clusters.get(cluster_key) if not should_create_group(occurrence.type, client, primary_hash, project): metrics.incr( "issues.issue.dropped.noise_reduction", tags={"group_type": occurrence.type.slug}, ) return None with metrics.timer("issues.save_issue_from_occurrence.check_write_limits"): granted_quota = issue_rate_limiter.check_and_use_quotas( [ RequestedQuota( f"issue-platform-issues:{project.id}:{occurrence.type.slug}", # noqa E231 missing whitespace after ':' 1, [occurrence.type.creation_quota], ) ] )[0] if not granted_quota.granted: metrics.incr("issues.issue.dropped.rate_limiting") return None with ( sentry_sdk.start_span(op="issues.save_issue_from_occurrence.transaction") as span, metrics.timer( "issues.save_issue_from_occurrence.transaction", tags={"platform": event.platform or "unknown", "type": occurrence.type.type_id}, sample_rate=1.0, ) as metric_tags, transaction.atomic(router.db_for_write(GroupHash)), ): group, is_new, primary_grouphash = save_grouphash_and_group( project, event, primary_hash, **issue_kwargs ) if is_new: detector_id = None if occurrence.evidence_data: detector_id = occurrence.evidence_data.get("detector_id") associate_new_group_with_detector(group, detector_id) open_period = get_latest_open_period(group) if open_period is not None: highest_seen_priority = group.priority open_period.update( data={**open_period.data, "highest_seen_priority": highest_seen_priority} ) is_regression = False span.set_tag("save_issue_from_occurrence.outcome", "new_group") metric_tags["save_issue_from_occurrence.outcome"] = "new_group" metrics.incr( "group.created", skip_internal=True, tags={ "platform": event.platform or "unknown", "type": occurrence.type.type_id, "sdk": normalized_sdk_tag_from_event(event.data), }, ) group_info = GroupInfo(group=group, is_new=is_new, is_regression=is_regression) # This only applies to events with stacktraces frame_mix = event.get_event_metadata().get("in_app_frame_mix") if is_new and frame_mix: metrics.incr( "grouping.in_app_frame_mix", sample_rate=1.0, tags={ "platform": event.platform or "unknown", "frame_mix": frame_mix, "sdk": normalized_sdk_tag_from_event(event.data), }, ) if is_new and occurrence.assignee: try: # Since this calls hybrid cloud it has to be run outside the transaction assignee = occurrence.assignee.resolve() GroupAssignee.objects.assign(group, assignee, create_only=True) except Exception: logger.exception("Failed process assignment for occurrence") elif primary_grouphash.group is None: return None else: group = primary_grouphash.group if group.issue_type.type_id != occurrence.type.type_id: logger.error( "save_issue_from_occurrence.type_mismatch", extra={ "issue_type": group.issue_type.slug, "occurrence_type": occurrence.type.slug, "event_type": "platform", "group_id": group.id, }, ) return None group_event = GroupEvent.from_event(event, group) group_event.occurrence = occurrence is_regression = _process_existing_aggregate(group, group_event, issue_kwargs, release) group_info = GroupInfo(group=group, is_new=False, is_regression=is_regression) detector_id = None if occurrence.evidence_data: detector_id = occurrence.evidence_data.get("detector_id") ensure_association_with_detector(group, detector_id) # if it's a regression and the priority changed, we should update the existing GroupOpenPeriodActivity # row if applicable. Otherwise, we should record a new row if applicable. if ( issue_kwargs["priority"] and group.priority != issue_kwargs["priority"] and group.priority_locked_at is None ): update_priority( group=group, priority=PriorityLevel(issue_kwargs["priority"]), sender="save_issue_from_occurrence", reason=PriorityChangeReason.ISSUE_PLATFORM, project=project, is_regression=is_regression, ) open_period = get_latest_open_period(group) if open_period is not None: highest_seen_priority = open_period.data.get("highest_seen_priority", None) if highest_seen_priority is None: highest_seen_priority = group.priority elif group.priority is not None: # XXX: we know this is not None, because we just set the group's priority highest_seen_priority = max(highest_seen_priority, group.priority) open_period.update( data={**open_period.data, "highest_seen_priority": highest_seen_priority} ) additional_hashes = [f for f in occurrence.fingerprint if f != primary_grouphash.hash] for fingerprint_hash in additional_hashes: # Attempt to create the additional grouphash links. They shouldn't be linked to other groups, but guard against # that group_hash, created = GroupHash.objects.get_or_create( project=project, hash=fingerprint_hash, defaults={"group": group_info.group} ) if not created: logger.warning( "Failed to create additional grouphash for group, grouphash associated with existing group", extra={ "new_group_id": group_info.group.id, "hash": fingerprint_hash, "existing_group_id": group_hash.group_id, }, ) return group_info @sentry_sdk.tracing.trace def send_issue_occurrence_to_eventstream( event: Event, occurrence: IssueOccurrence, group_info: GroupInfo ) -> None: group_event = event.for_group(group_info.group) group_event.occurrence = occurrence eventstream.backend.insert( event=group_event, is_new=group_info.is_new, is_regression=group_info.is_regression, is_new_group_environment=group_info.is_new_group_environment, primary_hash=occurrence.fingerprint[0], received_timestamp=group_event.data.get("received") or group_event.datetime, skip_consume=False, group_states=[ { "id": group_info.group.id, "is_new": group_info.is_new, "is_regression": group_info.is_regression, "is_new_group_environment": group_info.is_new_group_environment, } ], )
OccurrenceMetadata
python
eventlet__eventlet
tests/test__greenness.py
{ "start": 373, "end": 1483 }
class ____(BaseHTTPServer.BaseHTTPRequestHandler): protocol_version = "HTTP/1.0" def log_message(self, *args, **kw): pass def start_http_server(): server_address = ('localhost', 0) httpd = BaseHTTPServer.HTTPServer(server_address, QuietHandler) sa = httpd.socket.getsockname() # print("Serving HTTP on", sa[0], "port", sa[1], "...") httpd.request_count = 0 def serve(): # increment the request_count before handling the request because # the send() for the response blocks (or at least appeared to be) httpd.request_count += 1 httpd.handle_request() return eventlet.spawn(serve), httpd, sa[1] def test_urllib(): gthread, server, port = start_http_server() try: assert server.request_count == 0 try: urlopen('http://127.0.0.1:{}'.format(port)) assert False, 'should not get there' except HTTPError as ex: assert ex.code == 501, repr(ex) assert server.request_count == 1 finally: server.server_close() eventlet.kill(gthread)
QuietHandler
python
crytic__slither
slither/slithir/operations/lvalue.py
{ "start": 145, "end": 620 }
class ____(Operation): """ Operation with a lvalue """ def __init__(self) -> None: super().__init__() self._lvalue: Optional[Variable] = None @property def lvalue(self) -> Optional[Variable]: return self._lvalue @lvalue.setter def lvalue(self, lvalue: Variable) -> None: self._lvalue = lvalue @property def used(self) -> List[Optional[Any]]: return self.read + [self.lvalue]
OperationWithLValue
python
Pylons__pyramid
tests/test_path.py
{ "start": 12013, "end": 18935 }
class ____(unittest.TestCase): def _makeOne(self, package=None): from pyramid.path import DottedNameResolver return DottedNameResolver(package) def config_exc(self, func, *arg, **kw): try: func(*arg, **kw) except ValueError as e: return e else: raise AssertionError('Invalid not raised') # pragma: no cover def test_zope_dottedname_style_resolve_builtin(self): typ = self._makeOne() result = typ._zope_dottedname_style('builtins.str', None) self.assertEqual(result, str) def test_zope_dottedname_style_resolve_absolute(self): typ = self._makeOne() result = typ._zope_dottedname_style( 'tests.test_path.TestDottedNameResolver', None ) self.assertEqual(result, self.__class__) def test_zope_dottedname_style_irrresolveable_absolute(self): typ = self._makeOne() self.assertRaises( ImportError, typ._zope_dottedname_style, 'pyramid.test_path.nonexisting_name', None, ) def test__zope_dottedname_style_resolve_relative(self): import tests typ = self._makeOne() result = typ._zope_dottedname_style( '.test_path.TestDottedNameResolver', tests ) self.assertEqual(result, self.__class__) def test__zope_dottedname_style_resolve_relative_leading_dots(self): import tests.test_path typ = self._makeOne() result = typ._zope_dottedname_style( '..tests.test_path.TestDottedNameResolver', tests ) self.assertEqual(result, self.__class__) def test__zope_dottedname_style_resolve_relative_is_dot(self): import tests typ = self._makeOne() result = typ._zope_dottedname_style('.', tests) self.assertEqual(result, tests) def test__zope_dottedname_style_irresolveable_relative_is_dot(self): typ = self._makeOne() e = self.config_exc(typ._zope_dottedname_style, '.', None) self.assertEqual( e.args[0], "relative name '.' irresolveable without package" ) def test_zope_dottedname_style_resolve_relative_nocurrentpackage(self): typ = self._makeOne() e = self.config_exc(typ._zope_dottedname_style, '.whatever', None) self.assertEqual( e.args[0], "relative name '.whatever' irresolveable without package", ) def test_zope_dottedname_style_irrresolveable_relative(self): import tests typ = self._makeOne() self.assertRaises( ImportError, typ._zope_dottedname_style, '.notexisting', tests ) def test__zope_dottedname_style_resolveable_relative(self): import tests typ = self._makeOne() result = typ._zope_dottedname_style('.', tests) self.assertEqual(result, tests) def test__zope_dottedname_style_irresolveable_absolute(self): typ = self._makeOne() self.assertRaises( ImportError, typ._zope_dottedname_style, 'pyramid.fudge.bar', None ) def test__zope_dottedname_style_resolveable_absolute(self): typ = self._makeOne() result = typ._zope_dottedname_style( 'tests.test_path.TestDottedNameResolver', None ) self.assertEqual(result, self.__class__) def test__pkg_resources_style_resolve_absolute(self): typ = self._makeOne() result = typ._pkg_resources_style( 'tests.test_path:TestDottedNameResolver', None ) self.assertEqual(result, self.__class__) def test__pkg_resources_style_irrresolveable_absolute(self): typ = self._makeOne() self.assertRaises( ImportError, typ._pkg_resources_style, 'tests:nonexisting', None ) def test__pkg_resources_style_resolve_relative(self): import tests typ = self._makeOne() result = typ._pkg_resources_style( '.test_path:TestDottedNameResolver', tests ) self.assertEqual(result, self.__class__) def test__pkg_resources_style_resolve_relative_is_dot(self): import tests typ = self._makeOne() result = typ._pkg_resources_style('.', tests) self.assertEqual(result, tests) def test__pkg_resources_style_resolve_relative_nocurrentpackage(self): typ = self._makeOne() self.assertRaises( ValueError, typ._pkg_resources_style, '.whatever', None ) def test__pkg_resources_style_irrresolveable_relative(self): import pyramid typ = self._makeOne() self.assertRaises( ImportError, typ._pkg_resources_style, ':notexisting', pyramid ) def test_resolve_not_a_string(self): typ = self._makeOne() e = self.config_exc(typ.resolve, None) self.assertEqual(e.args[0], 'None is not a string') def test_resolve_using_pkgresources_style(self): typ = self._makeOne() result = typ.resolve('tests.test_path:TestDottedNameResolver') self.assertEqual(result, self.__class__) def test_resolve_using_zope_dottedname_style(self): typ = self._makeOne() result = typ.resolve('tests.test_path:TestDottedNameResolver') self.assertEqual(result, self.__class__) def test_resolve_missing_raises(self): typ = self._makeOne() self.assertRaises(ImportError, typ.resolve, 'cant.be.found') def test_resolve_caller_package(self): from pyramid.path import CALLER_PACKAGE typ = self._makeOne(CALLER_PACKAGE) self.assertEqual( typ.resolve('.test_path.TestDottedNameResolver'), self.__class__ ) def test_maybe_resolve_caller_package(self): from pyramid.path import CALLER_PACKAGE typ = self._makeOne(CALLER_PACKAGE) self.assertEqual( typ.maybe_resolve('.test_path.TestDottedNameResolver'), self.__class__, ) def test_ctor_string_module_resolveable(self): import tests typ = self._makeOne('tests.test_path') self.assertEqual(typ.package, tests) def test_ctor_string_package_resolveable(self): import tests typ = self._makeOne('tests') self.assertEqual(typ.package, tests) def test_ctor_string_irresolveable(self): self.assertRaises(ValueError, self._makeOne, 'cant.be.found') def test_ctor_module(self): import tests from . import test_path typ = self._makeOne(test_path) self.assertEqual(typ.package, tests) def test_ctor_package(self): import tests typ = self._makeOne(tests) self.assertEqual(typ.package, tests) def test_ctor_None(self): typ = self._makeOne(None) self.assertEqual(typ.package, None)
TestDottedNameResolver
python
haoel__leetcode
algorithms/python/MiddleOfTheLinkedList/middleOfTheLinkedList.py
{ "start": 135, "end": 602 }
class ____: def middleNode(self, head: ListNode) -> ListNode: aux = head cont = 1 while aux.next: cont += 1 aux = aux.next print(cont) if cont%2 == 0: posicao = (cont/2)+1 else: posicao = (cont//2)+1 aux = head cont = 1 while True: if cont == posicao: return aux aux = aux.next cont += 1
Solution
python
google__jax
jax/_src/pallas/pipelining/schedulers.py
{ "start": 2665, "end": 4634 }
class ____: """Container class containing pipeline state information. Attributes: loop_index: The current grid indices to run for the current stage. linearized_index: The linearized ``loop_index``. pipeline_state: The global pipeline carry state. """ loop_index: tuple[jax.Array, ...] linearized_index: jax.Array pipeline_state: PipelineState @classmethod def aval_pytree(cls, grid, state_avals) -> "PipelineContext": return PipelineContext( loop_index=(jax_core.ShapedArray((), jnp.int32),) * len(grid), linearized_index=jax_core.ShapedArray((), jnp.int32), pipeline_state=state_avals) def check_pipeline(stages: Sequence[internal.PipelineStage]): """Runs sanity checks on the pipeline.""" last_write = collections.defaultdict(lambda: None) last_read = collections.defaultdict(lambda: None) for i, stage in enumerate(stages): for read_idx in stage.get_read_idxs(): if last_write[read_idx] is None: raise ValueError( f"Read before write. {stage} attempted to read ref {read_idx}" " without a prior stage writing to it.") last_read[read_idx] = i for write_idx in stage.get_write_idxs(): if last_write[write_idx] is not None: raise ValueError( f"Write conflict. {stage} writes to ref {write_idx} but it was" f" already written to by stage {stages[last_write[write_idx]]}." " The current scheduler only allows one stage to write to each" " buffer.") last_write[write_idx] = i all_idxs = last_write.keys() | last_read.keys() for i in all_idxs: if last_write[i] > last_read[i]: raise ValueError(f"Ref {i} is written to after its final read.") @functools.partial(jax.tree_util.register_dataclass, data_fields=["stage_counters"], meta_fields=["which_stage_writes", "which_stages_read"]) @dataclasses.dataclass(frozen=True)
PipelineContext
python
doocs__leetcode
solution/2800-2899/2834.Find the Minimum Possible Sum of a Beautiful Array/Solution.py
{ "start": 0, "end": 276 }
class ____: def minimumPossibleSum(self, n: int, target: int) -> int: mod = 10**9 + 7 m = target // 2 if n <= m: return ((1 + n) * n // 2) % mod return ((1 + m) * m // 2 + (target + target + n - m - 1) * (n - m) // 2) % mod
Solution
python
django__django
tests/inspectdb/models.py
{ "start": 3833, "end": 4007 }
class ____(models.Model): char_field = models.CharField(max_length=None) class Meta: required_db_features = {"supports_unlimited_charfield"}
CharFieldUnlimited
python
qdrant__qdrant-client
qdrant_client/parallel_processor.py
{ "start": 488, "end": 583 }
class ____(str, Enum): stop = "stop" confirm = "confirm" error = "error"
QueueSignals
python
pallets__jinja
docs/examples/inline_gettext_extension.py
{ "start": 250, "end": 2397 }
class ____(Extension): """This extension implements support for inline gettext blocks:: <h1>_(Welcome)</h1> <p>_(This is a paragraph)</p> Requires the i18n extension to be loaded and configured. """ def filter_stream(self, stream): paren_stack = 0 for token in stream: if token.type != "data": yield token continue pos = 0 lineno = token.lineno while True: if not paren_stack: match = _outside_re.search(token.value, pos) else: match = _inside_re.search(token.value, pos) if match is None: break new_pos = match.start() if new_pos > pos: preval = token.value[pos:new_pos] yield Token(lineno, "data", preval) lineno += count_newlines(preval) gtok = match.group() if gtok[0] == "\\": yield Token(lineno, "data", gtok[1:]) elif not paren_stack: yield Token(lineno, "block_begin", None) yield Token(lineno, "name", "trans") yield Token(lineno, "block_end", None) paren_stack = 1 else: if gtok == "(" or paren_stack > 1: yield Token(lineno, "data", gtok) paren_stack += -1 if gtok == ")" else 1 if not paren_stack: yield Token(lineno, "block_begin", None) yield Token(lineno, "name", "endtrans") yield Token(lineno, "block_end", None) pos = match.end() if pos < len(token.value): yield Token(lineno, "data", token.value[pos:]) if paren_stack: raise TemplateSyntaxError( "unclosed gettext expression", token.lineno, stream.name, stream.filename, )
InlineGettext
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/interfaces.py
{ "start": 13825, "end": 15374 }
class ____(TypedDict): """Dictionary representing the reflected elements corresponding to :class:`.Index`. The :class:`.ReflectedIndex` structure is returned by the :meth:`.Inspector.get_indexes` method. """ name: Optional[str] """index name""" column_names: List[Optional[str]] """column names which the index references. An element of this list is ``None`` if it's an expression and is returned in the ``expressions`` list. """ expressions: NotRequired[List[str]] """Expressions that compose the index. This list, when present, contains both plain column names (that are also in ``column_names``) and expressions (that are ``None`` in ``column_names``). """ unique: bool """whether or not the index has a unique flag""" duplicates_constraint: NotRequired[Optional[str]] "Indicates if this index mirrors a constraint with this name" include_columns: NotRequired[List[str]] """columns to include in the INCLUDE clause for supporting databases. .. deprecated:: 2.0 Legacy value, will be replaced with ``index_dict["dialect_options"]["<dialect name>_include"]`` """ column_sorting: NotRequired[Dict[str, Tuple[str]]] """optional dict mapping column names or expressions to tuple of sort keywords, which may include ``asc``, ``desc``, ``nulls_first``, ``nulls_last``. """ dialect_options: NotRequired[Dict[str, Any]] """Additional dialect-specific options detected for this index"""
ReflectedIndex
python
django__django
tests/admin_filters/tests.py
{ "start": 4582, "end": 4948 }
class ____(FieldListFilter): list_separator = "|" def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__in" % field_path super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg]
EmployeeNameCustomDividerFilter
python
sqlalchemy__sqlalchemy
test/ext/test_automap.py
{ "start": 20296, "end": 21785 }
class ____(fixtures.TestBase): __only_on__ = "sqlite+pysqlite" def _make_tables(self, e): m = MetaData() for i in range(15): Table( "table_%d" % i, m, Column("id", Integer, primary_key=True), Column("data", String(50)), ( Column( "t_%d_id" % (i - 1), ForeignKey("table_%d.id" % (i - 1)), ) if i > 4 else None ), ) m.drop_all(e) m.create_all(e) def _automap(self, e): Base = automap_base() Base.prepare(autoload_with=e) time.sleep(0.01) configure_mappers() def _chaos(self): e = create_engine("sqlite://") try: self._make_tables(e) for i in range(2): try: self._automap(e) except: self._success = False raise time.sleep(random.random()) finally: e.dispose() def test_concurrent_automaps_w_configure(self): self._success = True threads = [threading.Thread(target=self._chaos) for i in range(30)] for t in threads: t.start() for t in threads: t.join() assert self._success, "One or more threads failed"
ConcurrentAutomapTest
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py
{ "start": 178921, "end": 194036 }
class ____(TestTaskInstanceEndpoint): ENDPOINT_URL = "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context" NEW_STATE = "failed" DAG_ID = "example_python_operator" TASK_ID = "print_the_context" RUN_ID = "TEST_DAG_RUN_ID" DAG_DISPLAY_NAME = "example_python_operator" @mock.patch("airflow.serialization.serialized_objects.SerializedDAG.set_task_instance_state") def test_should_call_mocked_api(self, mock_set_ti_state, test_client, session): self.create_task_instances(session) mock_set_ti_state.return_value = session.scalars( select(TaskInstance).where( TaskInstance.dag_id == self.DAG_ID, TaskInstance.task_id == self.TASK_ID, TaskInstance.run_id == self.RUN_ID, TaskInstance.map_index == -1, ) ).all() response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 200 assert response.json() == { "task_instances": [ { "dag_id": self.DAG_ID, "dag_display_name": self.DAG_DISPLAY_NAME, "dag_version": mock.ANY, "dag_run_id": self.RUN_ID, "logical_date": "2020-01-01T00:00:00Z", "task_id": self.TASK_ID, "duration": 10000.0, "end_date": "2020-01-03T00:00:00Z", "executor": None, "executor_config": "{}", "hostname": "", "id": mock.ANY, "map_index": -1, "max_tries": 0, "note": "placeholder-note", "operator": "PythonOperator", "operator_name": "PythonOperator", "pid": 100, "pool": "default_pool", "pool_slots": 1, "priority_weight": 9, "queue": "default_queue", "queued_when": None, "scheduled_when": None, "start_date": "2020-01-02T00:00:00Z", "state": "running", "task_display_name": self.TASK_ID, "try_number": 0, "unixname": getuser(), "rendered_fields": {}, "rendered_map_index": None, "run_after": "2020-01-01T00:00:00Z", "trigger": None, "triggerer_job": None, } ], "total_entries": 1, } mock_set_ti_state.assert_called_once_with( commit=False, downstream=False, upstream=False, future=False, map_indexes=None, past=False, run_id=self.RUN_ID, session=mock.ANY, state=self.NEW_STATE, task_id=self.TASK_ID, ) @pytest.mark.parametrize( "payload", [ { "new_state": "success", }, { "note": "something", }, { "new_state": "success", "note": "something", }, ], ) def test_should_not_update(self, test_client, session, payload): self.create_task_instances(session) task_before = test_client.get(self.ENDPOINT_URL).json() response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json=payload, ) assert response.status_code == 200 assert [ti["task_id"] for ti in response.json()["task_instances"]] == ["print_the_context"] task_after = test_client.get(self.ENDPOINT_URL).json() assert task_before == task_after _check_task_instance_note(session, task_after["id"], {"content": "placeholder-note", "user_id": None}) def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={}, ) assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={}, ) assert response.status_code == 403 def test_should_not_update_mapped_task_instance(self, test_client, session): map_index = 1 tis = self.create_task_instances(session) ti = TaskInstance( task=tis[0].task, run_id=tis[0].run_id, map_index=map_index, dag_version_id=tis[0].dag_version_id ) ti.rendered_task_instance_fields = RTIF(ti, render_templates=False) session.add(ti) session.commit() task_before = test_client.get(f"{self.ENDPOINT_URL}/{map_index}").json() response = test_client.patch( f"{self.ENDPOINT_URL}/{map_index}/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 200 assert [ti["task_id"] for ti in response.json()["task_instances"]] == ["print_the_context"] task_after = test_client.get(f"{self.ENDPOINT_URL}/{map_index}").json() assert task_before == task_after _check_task_instance_note(session, task_after["id"], None) def test_should_not_update_mapped_task_instance_summary(self, test_client, session): map_indexes = [1, 2, 3] tis = self.create_task_instances(session) for map_index in map_indexes: ti = TaskInstance( task=tis[0].task, run_id=tis[0].run_id, map_index=map_index, state="running", dag_version_id=tis[0].dag_version_id, ) ti.rendered_task_instance_fields = RTIF(ti, render_templates=False) session.add(ti) session.delete(tis[0]) session.commit() response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 200 assert response.json()["total_entries"] == len(map_indexes) for map_index in map_indexes: task_after = test_client.get(f"{self.ENDPOINT_URL}/{map_index}").json() assert task_after["note"] is None assert task_after["state"] == "running" _check_task_instance_note(session, task_after["id"], None) @pytest.mark.parametrize( ("error", "code", "payload"), [ [ [ "The Task Instance with dag_id: `example_python_operator`, run_id: `TEST_DAG_RUN_ID`, task_id: `print_the_context` and map_index: `-1` was not found" ], 404, { "new_state": "failed", }, ] ], ) def test_should_handle_errors(self, error, code, payload, test_client, session): response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run?map_index=-1", json=payload, ) assert response.status_code == code assert response.json()["detail"] == error def test_should_200_for_unknown_fields(self, test_client, session): self.create_task_instances(session) response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 200 def test_should_raise_404_for_non_existent_dag(self, test_client): response = test_client.patch( "/dags/non-existent-dag/dagRuns/TEST_DAG_RUN_ID/taskInstances/print_the_context/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 404 assert response.json() == {"detail": "The Dag with ID: `non-existent-dag` was not found"} def test_should_raise_404_for_non_existent_task_in_dag(self, test_client): response = test_client.patch( "/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInstances/non_existent_task/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 404 assert response.json() == { "detail": "Task 'non_existent_task' not found in DAG 'example_python_operator'" } def test_should_raise_404_not_found_dag(self, test_client): response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 404 def test_should_raise_404_not_found_task(self, test_client): response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={ "new_state": self.NEW_STATE, }, ) assert response.status_code == 404 @pytest.mark.parametrize( ("payload", "expected"), [ ( { "new_state": "failede", }, f"'failede' is not one of ['{State.SUCCESS}', '{State.FAILED}', '{State.SKIPPED}']", ), ( { "new_state": "queued", }, f"'queued' is not one of ['{State.SUCCESS}', '{State.FAILED}', '{State.SKIPPED}']", ), ], ) def test_should_raise_422_for_invalid_task_instance_state(self, payload, expected, test_client, session): self.create_task_instances(session) response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json=payload, ) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "value_error", "loc": ["body", "new_state"], "msg": f"Value error, {expected}", "input": payload["new_state"], "ctx": {"error": {}}, } ] } @pytest.mark.parametrize( ("new_state", "expected_status_code", "expected_json", "set_ti_state_call_count"), [ ( "failed", 200, { "task_instances": [ { "dag_id": "example_python_operator", "dag_display_name": "example_python_operator", "dag_version": mock.ANY, "dag_run_id": "TEST_DAG_RUN_ID", "logical_date": "2020-01-01T00:00:00Z", "task_id": "print_the_context", "duration": 10000.0, "end_date": "2020-01-03T00:00:00Z", "executor": None, "executor_config": "{}", "hostname": "", "id": mock.ANY, "map_index": -1, "max_tries": 0, "note": "placeholder-note", "operator": "PythonOperator", "operator_name": "PythonOperator", "pid": 100, "pool": "default_pool", "pool_slots": 1, "priority_weight": 9, "queue": "default_queue", "queued_when": None, "scheduled_when": None, "start_date": "2020-01-02T00:00:00Z", "state": "running", "task_display_name": "print_the_context", "try_number": 0, "unixname": getuser(), "rendered_fields": {}, "rendered_map_index": None, "run_after": "2020-01-01T00:00:00Z", "trigger": None, "triggerer_job": None, } ], "total_entries": 1, }, 1, ), ( None, 422, { "detail": [ { "type": "value_error", "loc": ["body", "new_state"], "msg": "Value error, 'new_state' should not be empty", "input": None, "ctx": {"error": {}}, } ] }, 0, ), ], ) @mock.patch("airflow.serialization.serialized_objects.SerializedDAG.set_task_instance_state") def test_update_mask_should_call_mocked_api( self, mock_set_ti_state, test_client, session, new_state, expected_status_code, expected_json, set_ti_state_call_count, ): self.create_task_instances(session) mock_set_ti_state.return_value = session.scalars( select(TaskInstance).where( TaskInstance.dag_id == self.DAG_ID, TaskInstance.task_id == self.TASK_ID, TaskInstance.run_id == self.RUN_ID, TaskInstance.map_index == -1, ) ).all() response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", params={"update_mask": "new_state"}, json={ "new_state": new_state, }, ) assert response.status_code == expected_status_code assert response.json() == expected_json assert mock_set_ti_state.call_count == set_ti_state_call_count @mock.patch("airflow.serialization.serialized_objects.SerializedDAG.set_task_instance_state") def test_should_return_empty_list_for_updating_same_task_instance_state( self, mock_set_ti_state, test_client, session ): self.create_task_instances(session) mock_set_ti_state.return_value = None response = test_client.patch( f"{self.ENDPOINT_URL}/dry_run", json={ "new_state": "success", }, ) assert response.status_code == 200 assert response.json() == {"task_instances": [], "total_entries": 0}
TestPatchTaskInstanceDryRun
python
pennersr__django-allauth
allauth/socialaccount/providers/openid/utils.py
{ "start": 1444, "end": 1953 }
class ____: CONTACT_EMAIL = "http://axschema.org/contact/email" PERSON_NAME = "http://axschema.org/namePerson" PERSON_FIRST_NAME = "http://axschema.org/namePerson/first" PERSON_LAST_NAME = "http://axschema.org/namePerson/last" AXAttributes = [ AXAttribute.CONTACT_EMAIL, AXAttribute.PERSON_NAME, AXAttribute.PERSON_FIRST_NAME, AXAttribute.PERSON_LAST_NAME, OldAXAttribute.PERSON_NAME, OldAXAttribute.PERSON_FIRST_NAME, OldAXAttribute.PERSON_LAST_NAME, ]
AXAttribute
python
getsentry__sentry
tests/sentry/db/models/test_base.py
{ "start": 1098, "end": 2308 }
class ____(TestCase): def all_subclasses(self, cls): return set(cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in self.all_subclasses(c)] ) def test(self) -> None: assert self.all_subclasses(DefaultFieldsModelExisting) == { BaseImportChunk, ControlImportChunk, ControlImportChunkReplica, GroupSearchView, Integration, NotificationSettingBase, NotificationSettingOption, NotificationSettingProvider, ProjectTemplate, ProjectTransactionThreshold, ProjectTransactionThresholdOverride, RegionImportChunk, Relocation, RelocationFile, RelocationValidation, RelocationValidationAttempt, RepositoryProjectPathConfig, SentryAppInstallationForProvider, UptimeSubscription, }, ( "Don't use `DefaultFieldsModelExisting` for new models - Use `DefaultFieldsModel` " "instead. If you're retrofitting an existing model, add it to the list in this test." )
PreventDefaultFieldsModelExistingUseTest
python
encode__django-rest-framework
rest_framework/fields.py
{ "start": 55883, "end": 57661 }
class ____(Field): default_error_messages = { 'required': _('No file was submitted.'), 'invalid': _('The submitted data was not a file. Check the encoding type on the form.'), 'no_name': _('No filename could be determined.'), 'empty': _('The submitted file is empty.'), 'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'), } def __init__(self, **kwargs): self.max_length = kwargs.pop('max_length', None) self.allow_empty_file = kwargs.pop('allow_empty_file', False) if 'use_url' in kwargs: self.use_url = kwargs.pop('use_url') super().__init__(**kwargs) def to_internal_value(self, data): try: # `UploadedFile` objects should have name and size attributes. file_name = data.name file_size = data.size except AttributeError: self.fail('invalid') if not file_name: self.fail('no_name') if not self.allow_empty_file and not file_size: self.fail('empty') if self.max_length and len(file_name) > self.max_length: self.fail('max_length', max_length=self.max_length, length=len(file_name)) return data def to_representation(self, value): if not value: return None use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL) if use_url: try: url = value.url except AttributeError: return None request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) return url return value.name
FileField
python
astropy__astropy
astropy/io/fits/hdu/compressed/_codecs.py
{ "start": 10423, "end": 13838 }
class ____(Codec): """ The FITS HCompress compression and decompression algorithm. Hcompress is an the image compression package written by Richard L. White for use at the Space Telescope Science Institute. Hcompress was used to compress the STScI Digitized Sky Survey and has also been used to compress the preview images in the Hubble Data Archive. The technique gives very good compression for astronomical images and is relatively fast. The calculations are carried out using integer arithmetic and are entirely reversible. Consequently, the program can be used for either lossy or lossless compression, with no special approach needed for the lossless case. Parameters ---------- scale The integer scale parameter determines the amount of compression. Scale = 0 or 1 leads to lossless compression, i.e. the decompressed image has exactly the same pixel values as the original image. If the scale factor is greater than 1 then the compression is lossy: the decompressed image will not be exactly the same as the original smooth At high compressions factors the decompressed image begins to appear blocky because of the way information is discarded. This blockiness ness is greatly reduced, producing more pleasing images, if the image is smoothed slightly during decompression. References ---------- .. [1] White, R. L. 1992, in Proceedings of the NASA Space and Earth Science Data Compression Workshop, ed. J. C. Tilton, Snowbird, UT; https://archive.org/details/nasa_techdoc_19930016742 """ codec_id = "FITS_HCOMPRESS1" def __init__(self, *, scale: int, smooth: bool, bytepix: int, nx: int, ny: int): self.scale = scale self.smooth = smooth self.bytepix = bytepix # NOTE: we should probably make this less confusing, but nx is shape[0] and ny is shape[1] self.nx = nx self.ny = ny def decode(self, buf): """ Decompress buffer using the HCOMPRESS_1 algorithm. Parameters ---------- buf : bytes or array_like The buffer to decompress. Returns ------- buf : np.ndarray The decompressed buffer. """ cbytes = np.frombuffer(_as_native_endian_array(buf), dtype=np.uint8).tobytes() dbytes = decompress_hcompress_1_c( cbytes, self.nx, self.ny, self.scale, self.smooth, self.bytepix ) # fits_hdecompress* always returns 4 byte integers irrespective of bytepix return np.frombuffer(dbytes, dtype="i4") def encode(self, buf): """ Compress the data in the buffer using the HCOMPRESS_1 algorithm. Parameters ---------- buf : bytes or array_like The buffer to compress. Returns ------- bytes The compressed bytes. """ # We convert the data to native endian because it is passed to the # C compression code which will interpret it as being native endian. dbytes = ( _as_native_endian_array(buf) .astype(f"i{self.bytepix}", copy=False) .tobytes() ) return compress_hcompress_1_c( dbytes, self.nx, self.ny, self.scale, self.bytepix )
HCompress1
python
numpy__numpy
numpy/ma/tests/test_extras.py
{ "start": 17360, "end": 18907 }
class ____: # Tests for mr_, the equivalent of r_ for masked arrays. def test_1d(self): # Tests mr_ on 1D arrays. assert_array_equal(mr_[1, 2, 3, 4, 5, 6], array([1, 2, 3, 4, 5, 6])) b = ones(5) m = [1, 0, 0, 0, 0] d = masked_array(b, mask=m) c = mr_[d, 0, 0, d] assert_(isinstance(c, MaskedArray)) assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1]) assert_array_equal(c.mask, mr_[m, 0, 0, m]) def test_2d(self): # Tests mr_ on 2D arrays. a_1 = np.random.rand(5, 5) a_2 = np.random.rand(5, 5) m_1 = np.round(np.random.rand(5, 5), 0) m_2 = np.round(np.random.rand(5, 5), 0) b_1 = masked_array(a_1, mask=m_1) b_2 = masked_array(a_2, mask=m_2) # append columns d = mr_['1', b_1, b_2] assert_(d.shape == (5, 10)) assert_array_equal(d[:, :5], b_1) assert_array_equal(d[:, 5:], b_2) assert_array_equal(d.mask, np.r_['1', m_1, m_2]) d = mr_[b_1, b_2] assert_(d.shape == (10, 5)) assert_array_equal(d[:5, :], b_1) assert_array_equal(d[5:, :], b_2) assert_array_equal(d.mask, np.r_[m_1, m_2]) def test_masked_constant(self): actual = mr_[np.ma.masked, 1] assert_equal(actual.mask, [True, False]) assert_equal(actual.data[1], 1) actual = mr_[[1, 2], np.ma.masked] assert_equal(actual.mask, [False, False, True]) assert_equal(actual.data[:2], [1, 2])
TestConcatenator
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 35481, "end": 39504 }
class ____(rv_discrete): r"""A uniform discrete random variable. %(before_notes)s Notes ----- The probability mass function for `randint` is: .. math:: f(k) = \frac{1}{\texttt{high} - \texttt{low}} for :math:`k \in \{\texttt{low}, \dots, \texttt{high} - 1\}`. `randint` takes :math:`\texttt{low}` and :math:`\texttt{high}` as shape parameters. %(after_notes)s Examples -------- >>> import numpy as np >>> from scipy.stats import randint >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Calculate the first four moments: >>> low, high = 7, 31 >>> mean, var, skew, kurt = randint.stats(low, high, moments='mvsk') Display the probability mass function (``pmf``): >>> x = np.arange(low - 5, high + 5) >>> ax.plot(x, randint.pmf(x, low, high), 'bo', ms=8, label='randint pmf') >>> ax.vlines(x, 0, randint.pmf(x, low, high), colors='b', lw=5, alpha=0.5) Alternatively, the distribution object can be called (as a function) to fix the shape and location. This returns a "frozen" RV object holding the given parameters fixed. Freeze the distribution and display the frozen ``pmf``: >>> rv = randint(low, high) >>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', ... lw=1, label='frozen pmf') >>> ax.legend(loc='lower center') >>> plt.show() Check the relationship between the cumulative distribution function (``cdf``) and its inverse, the percent point function (``ppf``): >>> q = np.arange(low, high) >>> p = randint.cdf(q, low, high) >>> np.allclose(q, randint.ppf(p, low, high)) True Generate random numbers: >>> r = randint.rvs(low, high, size=1000) """ def _shape_info(self): return [_ShapeInfo("low", True, (-np.inf, np.inf), (False, False)), _ShapeInfo("high", True, (-np.inf, np.inf), (False, False))] def _argcheck(self, low, high): return (high > low) & _isintegral(low) & _isintegral(high) def _get_support(self, low, high): return low, high-1 def _pmf(self, k, low, high): # randint.pmf(k) = 1./(high - low) p = np.ones_like(k) / (np.asarray(high, dtype=np.int64) - low) return np.where((k >= low) & (k < high), p, 0.) def _cdf(self, x, low, high): k = floor(x) return (k - low + 1.) / (high - low) def _ppf(self, q, low, high): vals = ceil(q * (high - low) + low) - 1 vals1 = (vals - 1).clip(low, high) temp = self._cdf(vals1, low, high) return np.where(temp >= q, vals1, vals) def _stats(self, low, high): m2, m1 = np.asarray(high), np.asarray(low) mu = (m2 + m1 - 1.0) / 2 d = m2 - m1 var = (d*d - 1) / 12.0 g1 = 0.0 g2 = -6.0/5.0 * (d*d + 1.0) / (d*d - 1.0) return mu, var, g1, g2 def _rvs(self, low, high, size=None, random_state=None): """An array of *size* random integers >= ``low`` and < ``high``.""" if np.asarray(low).size == 1 and np.asarray(high).size == 1: # no need to vectorize in that case return rng_integers(random_state, low, high, size=size) if size is not None: # NumPy's RandomState.randint() doesn't broadcast its arguments. # Use `broadcast_to()` to extend the shapes of low and high # up to size. Then we can use the numpy.vectorize'd # randint without needing to pass it a `size` argument. low = np.broadcast_to(low, size) high = np.broadcast_to(high, size) randint = np.vectorize(partial(rng_integers, random_state), otypes=[np.dtype(int)]) return randint(low, high) def _entropy(self, low, high): return log(high - low) randint = randint_gen(name='randint', longname='A discrete uniform ' '(random integer)') # FIXME: problems sampling.
randint_gen
python
scipy__scipy
scipy/stats/_page_trend_test.py
{ "start": 16782, "end": 19315 }
class ____: '''Maintains state between `page_trend_test` executions''' def __init__(self): '''Lightweight initialization''' self.all_pmfs = {} def set_k(self, k): '''Calculate lower and upper limits of L for single row''' self.k = k # See [5] top of page 52 self.a, self.b = (k*(k+1)*(k+2))//6, (k*(k+1)*(2*k+1))//6 def sf(self, l, n): '''Survival function of Page's L statistic''' ps = [self.pmf(l, n) for l in range(l, n*self.b + 1)] return np.sum(ps) def p_l_k_1(self): '''Relative frequency of each L value over all possible single rows''' # See [5] Equation (6) ranks = range(1, self.k+1) # generate all possible rows of length k rank_perms = np.array(list(permutations(ranks))) # compute Page's L for all possible rows Ls = (ranks*rank_perms).sum(axis=1) # count occurrences of each L value counts = np.histogram(Ls, np.arange(self.a-0.5, self.b+1.5))[0] # factorial(k) is number of possible permutations return counts/math.factorial(self.k) def pmf(self, l, n): '''Recursive function to evaluate p(l, k, n); see [5] Equation 1''' if n not in self.all_pmfs: self.all_pmfs[n] = {} if self.k not in self.all_pmfs[n]: self.all_pmfs[n][self.k] = {} # Cache results to avoid repeating calculation. Initially this was # written with lru_cache, but this seems faster? Also, we could add # an option to save this for future lookup. if l in self.all_pmfs[n][self.k]: return self.all_pmfs[n][self.k][l] if n == 1: ps = self.p_l_k_1() # [5] Equation 6 ls = range(self.a, self.b+1) # not fast, but we'll only be here once self.all_pmfs[n][self.k] = {l: p for l, p in zip(ls, ps)} return self.all_pmfs[n][self.k][l] p = 0 low = max(l-(n-1)*self.b, self.a) # [5] Equation 2 high = min(l-(n-1)*self.a, self.b) # [5] Equation 1 for t in range(low, high+1): p1 = self.pmf(l-t, n-1) p2 = self.pmf(t, 1) p += p1*p2 self.all_pmfs[n][self.k][l] = p return p # Maintain state for faster repeat calls to page_trend_test w/ method='exact' # _PageL() is calculated once per thread and stored as an attribute on # this thread-local variable inside page_trend_test(). _pagel_state = threading.local()
_PageL
python
tensorflow__tensorflow
tensorflow/lite/python/lite_v2_test.py
{ "start": 193554, "end": 194510 }
class ____(lite_v2_test_util.ModelTest): @test_util.run_v2_only def testReduceDataset(self): @tf.function def model(): dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4]) output = dataset.reduce(np.int32(0), lambda x, y: x + y) return output concrete_func = model.get_concrete_function() converter = lite.TFLiteConverterV2.from_concrete_functions( [concrete_func], model ) converter.target_spec.supported_ops = [ lite.OpsSet.TFLITE_BUILTINS, lite.OpsSet.SELECT_TF_OPS, ] tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check values from converted model. interp = interpreter.Interpreter(model_content=tflite_model) output_details = interp.get_output_details() interp.allocate_tensors() interp.invoke() actual_value = interp.get_tensor(output_details[0]['index']) self.assertEqual(10, actual_value)
DatasetOpsTest
python
davidhalter__parso
parso/grammar.py
{ "start": 8809, "end": 11081 }
class ____(Grammar): _error_normalizer_config = ErrorFinderConfig() _token_namespace = PythonTokenTypes _start_nonterminal = 'file_input' def __init__(self, version_info: PythonVersionInfo, bnf_text: str): super().__init__( bnf_text, tokenizer=self._tokenize_lines, parser=PythonParser, diff_parser=DiffParser ) self.version_info = version_info def _tokenize_lines(self, lines, **kwargs): return tokenize_lines(lines, version_info=self.version_info, **kwargs) def _tokenize(self, code): # Used by Jedi. return tokenize(code, version_info=self.version_info) def load_grammar(*, version: str = None, path: str = None): """ Loads a :py:class:`parso.Grammar`. The default version is the current Python version. :param str version: A python version string, e.g. ``version='3.8'``. :param str path: A path to a grammar file """ # NOTE: this (3, 14) should be updated to the latest version parso supports. # (if this doesn't happen, users will get older syntaxes and spurious warnings) passed_version_info = parse_version_string(version) version_info = min(passed_version_info, PythonVersionInfo(3, 14)) # # NOTE: this is commented out until parso properly supports newer Python grammars. # if passed_version_info != version_info: # warnings.warn('parso does not support %s.%s yet.' % ( # passed_version_info.major, passed_version_info.minor # )) file = path or os.path.join( 'python', 'grammar%s%s.txt' % (version_info.major, version_info.minor) ) global _loaded_grammars path = os.path.join(os.path.dirname(__file__), file) try: return _loaded_grammars[path] except KeyError: try: with open(path) as f: bnf_text = f.read() grammar = PythonGrammar(version_info, bnf_text) return _loaded_grammars.setdefault(path, grammar) except FileNotFoundError: message = "Python version %s.%s is currently not supported." % ( version_info.major, version_info.minor ) raise NotImplementedError(message)
PythonGrammar
python
great-expectations__great_expectations
great_expectations/metrics/batch/batch_column_types.py
{ "start": 347, "end": 464 }
class ____(BatchMetric[BatchColumnTypesResult]): """Table schema""" name = "table.column_types"
BatchColumnTypes
python
ray-project__ray
rllib/env/tests/test_multi_agent_env_runner.py
{ "start": 429, "end": 1224 }
class ____(ConnectorV2): def __init__(self, env, spaces, device): super().__init__(env.observation_space, env.action_space) self.episode_end_counter = 0 self.episodes_encountered_list = list() self.episodes_encountered_set = set() @override(ConnectorV2) def __call__( self, *, rl_module, batch, episodes: list[MultiAgentEpisode], explore, shared_data, metrics, **kwargs, ): if all(e.is_done for e in episodes): self.episode_end_counter += len(episodes) for episode in episodes: self.episodes_encountered_list.append(episode.id_) self.episodes_encountered_set.add(episode.id_) return batch
EpisodeTracker
python
python-jsonschema__jsonschema
jsonschema/tests/test_validators.py
{ "start": 66932, "end": 67115 }
class ____(ValidatorTestMixin, TestCase): Validator = validators.Draft6Validator valid: tuple[dict, dict] = ({}, {}) invalid = {"type": "integer"}, "foo"
TestDraft6Validator
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataplex.py
{ "start": 20006, "end": 20940 }
class ____: @mock.patch(HOOK_STR) def test_execute(self, hook_mock): op = DataplexDeleteZoneOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, lake_id=LAKE_ID, zone_id=ZONE_ID, api_version=API_VERSION, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) op.execute(context=mock.MagicMock()) hook_mock.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, api_version=API_VERSION, impersonation_chain=IMPERSONATION_CHAIN, ) hook_mock.return_value.delete_zone.assert_called_once_with( project_id=PROJECT_ID, region=REGION, lake_id=LAKE_ID, zone_id=ZONE_ID, retry=DEFAULT, timeout=None, metadata=(), )
TestDataplexDeleteZoneOperator
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/deprecated4.py
{ "start": 992, "end": 1277 }
class ____: @overload @deprecated("DescB1 __get__") def __get__(self, obj: None, owner: object) -> str: ... @overload def __get__(self, obj: object, owner: object) -> str: ... def __get__(self, obj: object | None, owner: object) -> str: return ""
DescB1
python
pypa__pip
src/pip/_vendor/rich/pretty.py
{ "start": 14333, "end": 17204 }
class ____: """A node in a repr tree. May be atomic or a container.""" key_repr: str = "" value_repr: str = "" open_brace: str = "" close_brace: str = "" empty: str = "" last: bool = False is_tuple: bool = False is_namedtuple: bool = False children: Optional[List["Node"]] = None key_separator: str = ": " separator: str = ", " def iter_tokens(self) -> Iterable[str]: """Generate tokens for this node.""" if self.key_repr: yield self.key_repr yield self.key_separator if self.value_repr: yield self.value_repr elif self.children is not None: if self.children: yield self.open_brace if self.is_tuple and not self.is_namedtuple and len(self.children) == 1: yield from self.children[0].iter_tokens() yield "," else: for child in self.children: yield from child.iter_tokens() if not child.last: yield self.separator yield self.close_brace else: yield self.empty def check_length(self, start_length: int, max_length: int) -> bool: """Check the length fits within a limit. Args: start_length (int): Starting length of the line (indent, prefix, suffix). max_length (int): Maximum length. Returns: bool: True if the node can be rendered within max length, otherwise False. """ total_length = start_length for token in self.iter_tokens(): total_length += cell_len(token) if total_length > max_length: return False return True def __str__(self) -> str: repr_text = "".join(self.iter_tokens()) return repr_text def render( self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False ) -> str: """Render the node to a pretty repr. Args: max_width (int, optional): Maximum width of the repr. Defaults to 80. indent_size (int, optional): Size of indents. Defaults to 4. expand_all (bool, optional): Expand all levels. Defaults to False. Returns: str: A repr string of the original object. """ lines = [_Line(node=self, is_root=True)] line_no = 0 while line_no < len(lines): line = lines[line_no] if line.expandable and not line.expanded: if expand_all or not line.check_length(max_width): lines[line_no : line_no + 1] = line.expand(indent_size) line_no += 1 repr_str = "\n".join(str(line) for line in lines) return repr_str @dataclass
Node
python
tensorflow__tensorflow
tensorflow/python/summary/plugin_asset_test.py
{ "start": 1055, "end": 1173 }
class ____(_UnnamedPluginAsset): """Simple example asset.""" plugin_name = "_ExamplePluginAsset"
_ExamplePluginAsset
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classVar6.py
{ "start": 317, "end": 451 }
class ____(TypedDict): # This should generate an error. x: ClassVar # This should generate an error. y: ClassVar[int]
TD1
python
joke2k__faker
tests/providers/test_person.py
{ "start": 73003, "end": 76802 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("zh_TW") Faker.seed(0) def test_last_name(self): # There's no gender-specific last name in Chinese. assert not hasattr(ZhTWProvider, "last_names_male") assert not hasattr(ZhTWProvider, "last_names_female") assert not hasattr(ZhTWProvider, "last_romanized_names_male") assert not hasattr(ZhTWProvider, "last_romanized_names_female") # All last names apply for all genders. assert hasattr(ZhTWProvider, "last_names") # General last name. name = self.fake.last_name() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.last_names # Females last name. (no gender-specific) name = self.fake.last_name_female() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.last_names # Male last name. (no gender-specific) name = self.fake.last_name_male() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.last_names # General last romanized name name = self.fake.last_romanized_name() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.last_romanized_names def test_first_name(self): # General first name name = self.fake.first_name() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.first_names # Females first name name = self.fake.first_name_female() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.first_names assert name in ZhTWProvider.first_names_female # Male first name name = self.fake.first_name_male() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.first_names assert name in ZhTWProvider.first_names_male # General first romanized name name = self.fake.first_romanized_name() assert name self.assertIsInstance(name, str) assert name in ZhTWProvider.first_romanized_names def test_name(self): # Full name name = self.fake.name() assert name self.assertIsInstance(name, str) assert name[0] in ZhTWProvider.last_names or name[:2] in ZhTWProvider.last_names assert name[1:] in ZhTWProvider.first_names or name[2:] in ZhTWProvider.first_names # Full romanized name name = self.fake.romanized_name() assert name self.assertIsInstance(name, str) last_romanized_name, first_romanized_name = name.split(" ") # 'WANG SHU-FEN' or 'SHU-FEN, WANG' are both okay. # first_romanized_name, last_romanized_name = name.split(" ") assert first_romanized_name in ZhTWProvider.first_romanized_names assert last_romanized_name in ZhTWProvider.last_romanized_names def test_person(self): name = self.fake.name() assert name assert isinstance(name, str) first_name = self.fake.first_name() assert first_name assert isinstance(first_name, str) last_name = self.fake.last_name() assert last_name assert isinstance(last_name, str) romanized_name = self.fake.romanized_name() assert romanized_name assert isinstance(romanized_name, str) first_romanized_name = self.fake.first_romanized_name() assert first_romanized_name assert isinstance(first_romanized_name, str) last_romanized_name = self.fake.last_romanized_name() assert last_romanized_name assert isinstance(last_romanized_name, str)
TestZhTW
python
numba__numba
numba/tests/test_typeinfer.py
{ "start": 2200, "end": 11848 }
class ____(unittest.TestCase): """ Tests for type unification with a typing context. """ int_unify = { ('uint8', 'uint8'): 'uint8', ('int8', 'int8'): 'int8', ('uint16', 'uint16'): 'uint16', ('int16', 'int16'): 'int16', ('uint32', 'uint32'): 'uint32', ('int32', 'int32'): 'int32', ('uint64', 'uint64'): 'uint64', ('int64', 'int64'): 'int64', ('int8', 'uint8'): 'int16', ('int8', 'uint16'): 'int32', ('int8', 'uint32'): 'int64', ('uint8', 'int32'): 'int32', ('uint8', 'uint64'): 'uint64', ('int16', 'int8'): 'int16', ('int16', 'uint8'): 'int16', ('int16', 'uint16'): 'int32', ('int16', 'uint32'): 'int64', ('int16', 'int64'): 'int64', ('int16', 'uint64'): 'float64', ('uint16', 'uint8'): 'uint16', ('uint16', 'uint32'): 'uint32', ('uint16', 'int32'): 'int32', ('uint16', 'uint64'): 'uint64', ('int32', 'int8'): 'int32', ('int32', 'int16'): 'int32', ('int32', 'uint32'): 'int64', ('int32', 'int64'): 'int64', ('uint32', 'uint8'): 'uint32', ('uint32', 'int64'): 'int64', ('uint32', 'uint64'): 'uint64', ('int64', 'int8'): 'int64', ('int64', 'uint8'): 'int64', ('int64', 'uint16'): 'int64', ('uint64', 'int8'): 'float64', ('uint64', 'int32'): 'float64', ('uint64', 'int64'): 'float64', } def assert_unify(self, aty, bty, expected): ctx = typing.Context() template = "{0}, {1} -> {2} != {3}" for unify_func in ctx.unify_types, ctx.unify_pairs: unified = unify_func(aty, bty) self.assertEqual(unified, expected, msg=template.format(aty, bty, unified, expected)) unified = unify_func(bty, aty) self.assertEqual(unified, expected, msg=template.format(bty, aty, unified, expected)) def assert_unify_failure(self, aty, bty): self.assert_unify(aty, bty, None) def test_integer(self): ctx = typing.Context() for aty, bty in itertools.product(types.integer_domain, types.integer_domain): key = (str(aty), str(bty)) try: expected = self.int_unify[key] except KeyError: expected = self.int_unify[key[::-1]] self.assert_unify(aty, bty, getattr(types, expected)) def test_bool(self): aty = types.boolean for bty in types.integer_domain: self.assert_unify(aty, bty, bty) # Not sure about this one, but it respects transitivity for cty in types.real_domain: self.assert_unify(aty, cty, cty) def unify_number_pair_test(self, n): """ Test all permutations of N-combinations of numeric types and ensure that the order of types in the sequence is irrelevant. """ ctx = typing.Context() for tys in itertools.combinations(types.number_domain, n): res = [ctx.unify_types(*comb) for comb in itertools.permutations(tys)] first_result = res[0] # Sanity check self.assertIsInstance(first_result, types.Number) # All results must be equal for other in res[1:]: self.assertEqual(first_result, other) def test_unify_number_pair(self): self.unify_number_pair_test(2) self.unify_number_pair_test(3) def test_none_to_optional(self): """ Test unification of `none` and multiple number types to optional type """ ctx = typing.Context() for tys in itertools.combinations(types.number_domain, 2): # First unify without none, to provide the control value tys = list(tys) expected = types.Optional(ctx.unify_types(*tys)) results = [ctx.unify_types(*comb) for comb in itertools.permutations(tys + [types.none])] # All results must be equal for res in results: self.assertEqual(res, expected) def test_none(self): aty = types.none bty = types.none self.assert_unify(aty, bty, types.none) def test_optional(self): aty = types.Optional(i32) bty = types.none self.assert_unify(aty, bty, aty) aty = types.Optional(i32) bty = types.Optional(i64) self.assert_unify(aty, bty, bty) aty = types.Optional(i32) bty = i64 self.assert_unify(aty, bty, types.Optional(i64)) # Failure aty = types.Optional(i32) bty = types.Optional(types.slice3_type) self.assert_unify_failure(aty, bty) def test_tuple(self): aty = types.UniTuple(i32, 3) bty = types.UniTuple(i64, 3) self.assert_unify(aty, bty, types.UniTuple(i64, 3)) # (Tuple, UniTuple) -> Tuple aty = types.UniTuple(i32, 2) bty = types.Tuple((i16, i64)) self.assert_unify(aty, bty, types.Tuple((i32, i64))) aty = types.UniTuple(i64, 0) bty = types.Tuple(()) self.assert_unify(aty, bty, bty) # (Tuple, Tuple) -> Tuple aty = types.Tuple((i8, i16, i32)) bty = types.Tuple((i32, i16, i8)) self.assert_unify(aty, bty, types.Tuple((i32, i16, i32))) aty = types.Tuple((i8, i32)) bty = types.Tuple((i32, i8)) self.assert_unify(aty, bty, types.Tuple((i32, i32))) aty = types.Tuple((i8, i16)) bty = types.Tuple((i16, i8)) self.assert_unify(aty, bty, types.Tuple((i16, i16))) # Different number kinds aty = types.UniTuple(f64, 3) bty = types.UniTuple(c64, 3) self.assert_unify(aty, bty, types.UniTuple(c128, 3)) # Tuples of tuples aty = types.UniTuple(types.Tuple((u32, f32)), 2) bty = types.UniTuple(types.Tuple((i16, f32)), 2) self.assert_unify(aty, bty, types.UniTuple(types.Tuple((i64, f32)), 2)) # Failures aty = types.UniTuple(i32, 1) bty = types.UniTuple(types.slice3_type, 1) self.assert_unify_failure(aty, bty) aty = types.UniTuple(i32, 1) bty = types.UniTuple(i32, 2) self.assert_unify_failure(aty, bty) aty = types.Tuple((i8, types.slice3_type)) bty = types.Tuple((i32, i8)) self.assert_unify_failure(aty, bty) def test_optional_tuple(self): # Unify to optional tuple aty = types.none bty = types.UniTuple(i32, 2) self.assert_unify(aty, bty, types.Optional(types.UniTuple(i32, 2))) aty = types.Optional(types.UniTuple(i16, 2)) bty = types.UniTuple(i32, 2) self.assert_unify(aty, bty, types.Optional(types.UniTuple(i32, 2))) # Unify to tuple of optionals aty = types.Tuple((types.none, i32)) bty = types.Tuple((i16, types.none)) self.assert_unify(aty, bty, types.Tuple((types.Optional(i16), types.Optional(i32)))) aty = types.Tuple((types.Optional(i32), i64)) bty = types.Tuple((i16, types.Optional(i8))) self.assert_unify(aty, bty, types.Tuple((types.Optional(i32), types.Optional(i64)))) def test_arrays(self): aty = types.Array(i32, 3, "C") bty = types.Array(i32, 3, "A") self.assert_unify(aty, bty, bty) aty = types.Array(i32, 3, "C") bty = types.Array(i32, 3, "F") self.assert_unify(aty, bty, types.Array(i32, 3, "A")) aty = types.Array(i32, 3, "C") bty = types.Array(i32, 3, "C", readonly=True) self.assert_unify(aty, bty, bty) aty = types.Array(i32, 3, "A") bty = types.Array(i32, 3, "C", readonly=True) self.assert_unify(aty, bty, types.Array(i32, 3, "A", readonly=True)) # Failures aty = types.Array(i32, 2, "C") bty = types.Array(i32, 3, "C") self.assert_unify_failure(aty, bty) aty = types.Array(i32, 2, "C") bty = types.Array(u32, 2, "C") self.assert_unify_failure(aty, bty) def test_list(self): aty = types.List(types.undefined) bty = types.List(i32) self.assert_unify(aty, bty, bty) aty = types.List(i16) bty = types.List(i32) self.assert_unify(aty, bty, bty) aty = types.List(types.Tuple([i32, i16])) bty = types.List(types.Tuple([i16, i64])) cty = types.List(types.Tuple([i32, i64])) self.assert_unify(aty, bty, cty) # Different reflections aty = types.List(i16, reflected=True) bty = types.List(i32) cty = types.List(i32, reflected=True) self.assert_unify(aty, bty, cty) # Incompatible dtypes aty = types.List(i16) bty = types.List(types.Tuple([i16])) self.assert_unify_failure(aty, bty) def test_set(self): # Different reflections aty = types.Set(i16, reflected=True) bty = types.Set(i32) cty = types.Set(i32, reflected=True) self.assert_unify(aty, bty, cty) # Incompatible dtypes aty = types.Set(i16) bty = types.Set(types.Tuple([i16])) self.assert_unify_failure(aty, bty) def test_range(self): aty = types.range_state32_type bty = types.range_state64_type self.assert_unify(aty, bty, bty)
TestUnify
python
ansible__ansible
test/units/modules/test_unarchive.py
{ "start": 626, "end": 729 }
class ____: def __init__(self): self.params = {} self.tmpdir = None
FakeAnsibleModule
python
pypa__setuptools
setuptools/discovery.py
{ "start": 6391, "end": 7732 }
class ____(PEP420PackageFinder): _EXCLUDE = ( "ci", "bin", "debian", "doc", "docs", "documentation", "manpages", "news", "newsfragments", "changelog", "test", "tests", "unit_test", "unit_tests", "example", "examples", "scripts", "tools", "util", "utils", "python", "build", "dist", "venv", "env", "requirements", # ---- Task runners / Build tools ---- "tasks", # invoke "fabfile", # fabric "site_scons", # SCons # ---- Other tools ---- "benchmark", "benchmarks", "exercise", "exercises", "htmlcov", # Coverage.py # ---- Hidden directories/Private packages ---- "[._]*", ) DEFAULT_EXCLUDE = tuple(chain_iter((p, f"{p}.*") for p in _EXCLUDE)) """Reserved package names""" @staticmethod def _looks_like_package(_path: StrPath, package_name: str) -> bool: names = package_name.split('.') # Consider PEP 561 root_pkg_is_valid = names[0].isidentifier() or names[0].endswith("-stubs") return root_pkg_is_valid and all(name.isidentifier() for name in names[1:])
FlatLayoutPackageFinder
python
pytorch__pytorch
test/inductor/test_cooperative_reductions.py
{ "start": 1664, "end": 8804 }
class ____(TestCase): def setUp(self): super().setUp() torch._inductor.metrics.generated_kernel_count = 0 torch._dynamo.reset() def run_and_check(self, fn, args, dtype=None, *, expect_kernel_count=1): # Define fixed tolerances RTOL = 1e-5 ATOL = 1e-6 # calculate reference value in higher precision when input dtype is float16 ref_dtype = dtype if dtype == torch.float16: ref_dtype = torch.float64 # Cast to the determined reference dtype args_ref = [tensor.to(ref_dtype) for tensor in args] # Calculate expected output raw_expected = fn(*args_ref) if isinstance(raw_expected, (tuple, list)): # If it's a tuple or list, apply .to(dtype) to each tensor within it # Also, handle cases where dtype might not be provided (e.g., for bool reductions) if dtype is not None: expected = type(raw_expected)( [ t.to(dtype) if isinstance(t, torch.Tensor) else t for t in raw_expected ] ) else: expected = type(raw_expected)( [ t.to(torch.float64) if isinstance(t, torch.Tensor) else t for t in raw_expected ] ) else: # If it's a single tensor if dtype is not None: expected = raw_expected.to(dtype) else: expected = raw_expected.to(torch.float64) fn_compiled = torch.compile(fn, fullgraph=True) result, (source_code,) = run_and_get_code(fn_compiled, *args) # For comparison, ensure result is also a tuple/list if expected is if isinstance(expected, (tuple, list)): if isinstance(result, torch.Tensor): result = (result,) elif not isinstance(result, type(expected)): result = type(expected)(result) if dtype is not None: result = type(result)( [t.to(dtype) if isinstance(t, torch.Tensor) else t for t in result] ) else: result = type(result)( [ t.to(torch.float64) if isinstance(t, torch.Tensor) else t for t in result ] ) else: if dtype is not None and isinstance(result, torch.Tensor): result = result.to(dtype) elif isinstance(result, torch.Tensor): result = result.to(torch.float64) # Apply assert_close with fixed tolerances for tensor comparisons if isinstance(result, torch.Tensor) and isinstance(expected, torch.Tensor): assert_close(result, expected, rtol=RTOL, atol=ATOL) elif isinstance(result, (tuple, list)) and isinstance(expected, (tuple, list)): # Iterate through elements for comparison for r_item, e_item in zip(result, expected): if isinstance(r_item, torch.Tensor) and isinstance( e_item, torch.Tensor ): assert_close(r_item, e_item, rtol=RTOL, atol=ATOL) else: # Fallback to assertEqual for non-tensor elements (e.g., bool, int) self.assertEqual(r_item, e_item) else: # Fallback to assertEqual for other types not handled by assert_close self.assertEqual(result, expected) if "@triton_heuristics.fixed_config" in source_code: self.assertIn("cooperative_reduction_grid", source_code) else: self.assertIn("@triton_heuristics.cooperative_reduction", source_code) if "async_compile.multi_kernel" not in source_code: self.assertEqual( torch._inductor.metrics.generated_kernel_count, expect_kernel_count ) return source_code @parametrize( "name", [ "sum", "mean", "prod", "amin", "amax", "min", "max", "var_mean", "std", "softmax", ], ) @parametrize("dtype", [torch.float16, torch.float32, torch.float64]) def test_reduction_fns(self, name, dtype): if IS_SM89 and dtype == torch.float64 and name in ["std", "var_mean"]: raise unittest.SkipTest("Timeouts on SM89") def fn(x, y): return reduction_fn(x + y, dim=-1) reduction_fn = getattr(torch, name) args = [torch.randn(1, 1024**2, device=GPU_TYPE, dtype=dtype) for _ in range(2)] self.run_and_check(fn, args, dtype) def test_bool_reduction_fns(self): def fn(x, y): return [ torch.any(x == y), torch.all(x == y), torch.any(x != y), torch.all(x != y), torch.any(x < y), torch.all(x > y), ] args = [torch.randn(1024, device=GPU_TYPE) for _ in range(2)] source_code = self.run_and_check(fn, args) if "async_compile.multi_kernel" in source_code: return before, after = source_code.split("triton_helpers.x_grid_barrier") self.assertEqual(before.count("if rsplit_id == ("), 0) self.assertEqual(after.count("if rsplit_id == ("), 6) @parametrize("bs", [1, 2, 5, 15]) @parametrize("count", [1024**2 + 1, 1024**2 - 1, 1024]) def test_non_power_of_2(self, bs, count): def fn(x): return x.mean(), x.std() + x.min() args = [torch.randn([bs, count], device=GPU_TYPE)] self.run_and_check(fn, args) def test_chained_reductions(self): def fn(x): for _ in range(8): x = x + torch.softmax(x, 1) return x args = [torch.randn(4, 100000, device=GPU_TYPE)] source_code = self.run_and_check(fn, args) if "async_compile.multi_kernel" in source_code: return # With online softmax, the computation of max and sum are done # jointly and they share a single barrier call. # XPU doesn't support online softmax yet. expected_num_barrier = 8 if config.online_softmax and GPU_TYPE != "xpu" else 16 self.assertEqual( source_code.count("triton_helpers.x_grid_barrier"), expected_num_barrier ) self.assertEqual(source_code.count(f"empty_strided_{GPU_TYPE}"), 5) def test_reduce_split(self): def fn(a, b): a1 = torch.linalg.vector_norm(a) b1 = torch.sum(b, dim=0) return a1, b1 inps = [ torch.rand(2048, 512, device=GPU_TYPE), torch.rand(20, 20, device=GPU_TYPE), ] self.run_and_check(fn, inps, expect_kernel_count=2) @config.patch("triton.persistent_reductions", not config.triton.persistent_reductions)
CooperativeReductionTests
python
django__django
django/template/base.py
{ "start": 17121, "end": 25511 }
class ____: def __init__(self, tokens, libraries=None, builtins=None, origin=None): # Reverse the tokens so delete_first_token(), prepend_token(), and # next_token() can operate at the end of the list in constant time. self.tokens = list(reversed(tokens)) self.tags = {} self.filters = {} self.command_stack = [] # Custom template tags may store additional data on the parser that # will be made available on the template instance. Library authors # should use a key to namespace any added data. The 'django' namespace # is reserved for internal use. self.extra_data = {} if libraries is None: libraries = {} if builtins is None: builtins = [] self.libraries = libraries for builtin in builtins: self.add_library(builtin) self.origin = origin def __repr__(self): return "<%s tokens=%r>" % (self.__class__.__qualname__, self.tokens) def parse(self, parse_until=None): """ Iterate through the parser tokens and compiles each one into a node. If parse_until is provided, parsing will stop once one of the specified tokens has been reached. This is formatted as a list of tokens, e.g. ['elif', 'else', 'endif']. If no matching token is reached, raise an exception with the unclosed block tag details. """ if parse_until is None: parse_until = [] nodelist = NodeList() while self.tokens: token = self.next_token() # Use the raw values here for TokenType.* for a tiny performance # boost. token_type = token.token_type.value if token_type == 0: # TokenType.TEXT self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token_type == 1: # TokenType.VAR if not token.contents: raise self.error( token, "Empty variable tag on line %d" % token.lineno ) try: filter_expression = self.compile_filter(token.contents) except TemplateSyntaxError as e: raise self.error(token, e) var_node = VariableNode(filter_expression) self.extend_nodelist(nodelist, var_node, token) elif token_type == 2: # TokenType.BLOCK try: command = token.contents.split()[0] except IndexError: raise self.error(token, "Empty block tag on line %d" % token.lineno) if command in parse_until: # A matching token has been reached. Return control to # the caller. Put the token back on the token list so the # caller knows where it terminated. self.prepend_token(token) return nodelist # Add the token to the command stack. This is used for error # messages if further parsing fails due to an unclosed block # tag. self.command_stack.append((command, token)) # Get the tag callback function from the ones registered with # the parser. try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command, parse_until) # Compile the callback into a node object and add it to # the node list. try: compiled_result = compile_func(self, token) except Exception as e: raise self.error(token, e) self.extend_nodelist(nodelist, compiled_result, token) # Compile success. Remove the token from the command stack. self.command_stack.pop() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TokenType.BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def extend_nodelist(self, nodelist, node, token): # Check that non-text nodes don't appear before an extends tag. if node.must_be_first and nodelist.contains_nontext: if self.origin.template_name: origin = repr(self.origin.template_name) else: origin = "the template" raise self.error( token, "{%% %s %%} must be the first tag in %s." % (token.contents, origin), ) if not isinstance(node, TextNode): nodelist.contains_nontext = True # Set origin and token here since we can't modify the node __init__() # method. node.token = token node.origin = self.origin nodelist.append(node) def error(self, token, e): """ Return an exception annotated with the originating token. Since the parser can be called recursively, check if a token is already set. This ensures the innermost token is highlighted if an exception occurs, e.g. a compile error within the body of an if statement. """ if not isinstance(e, Exception): e = TemplateSyntaxError(e) if not hasattr(e, "token"): e.token = token return e def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s. Did you " "forget to register or load this tag?" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until], "or"), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'. Did you forget to register " "or load this tag?" % (token.lineno, command), ) def unclosed_block_tag(self, parse_until): command, token = self.command_stack.pop() msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % ( token.lineno, command, ", ".join(parse_until), ) raise self.error(token, msg) def next_token(self): return self.tokens.pop() def prepend_token(self, token): self.tokens.append(token) def delete_first_token(self): del self.tokens[-1] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): """ Convenient wrapper for FilterExpression """ return FilterExpression(token, self) def find_filter(self, filter_name): if filter_name in self.filters: return self.filters[filter_name] else: raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name) # This only matches constant *strings* (things in quotes or marked for # translation). Numbers are treated as variables for implementation reasons # (so that they retain their type when passed to filters). constant_string = r""" (?:%(i18n_open)s%(strdq)s%(i18n_close)s| %(i18n_open)s%(strsq)s%(i18n_close)s| %(strdq)s| %(strsq)s) """ % { "strdq": r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string "strsq": r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string "i18n_open": re.escape("_("), "i18n_close": re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+)| (?:\s*%(filter_sep)s\s* (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+) ) )? )""" % { "constant": constant_string, "var_chars": r"\w\.\+-", "filter_sep": re.escape(FILTER_SEPARATOR), "arg_sep": re.escape(FILTER_ARGUMENT_SEPARATOR), } filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE)
Parser
python
django__django
tests/admin_docs/test_utils.py
{ "start": 289, "end": 5629 }
class ____(AdminDocsSimpleTestCase): """ This __doc__ output is required for testing. I copied this example from `admindocs` documentation. (TITLE) Display an individual :model:`myapp.MyModel`. **Context** ``RequestContext`` ``mymodel`` An instance of :model:`myapp.MyModel`. **Template:** :template:`myapp/my_template.html` (DESCRIPTION) some_metadata: some data """ def setUp(self): self.docstring = self.__doc__ def test_parse_docstring(self): title, description, metadata = parse_docstring(self.docstring) docstring_title = ( "This __doc__ output is required for testing. I copied this example from\n" "`admindocs` documentation. (TITLE)" ) docstring_description = ( "Display an individual :model:`myapp.MyModel`.\n\n" "**Context**\n\n``RequestContext``\n\n``mymodel``\n" " An instance of :model:`myapp.MyModel`.\n\n" "**Template:**\n\n:template:`myapp/my_template.html` " "(DESCRIPTION)" ) self.assertEqual(title, docstring_title) self.assertEqual(description, docstring_description) self.assertEqual(metadata, {"some_metadata": "some data"}) def test_title_output(self): title, description, metadata = parse_docstring(self.docstring) title_output = parse_rst(title, "model", "model:admindocs") self.assertIn("TITLE", title_output) title_rendered = ( "<p>This __doc__ output is required for testing. I copied this " 'example from\n<a class="reference external" ' 'href="/admindocs/models/admindocs/">admindocs</a> documentation. ' "(TITLE)</p>\n" ) self.assertHTMLEqual(title_output, title_rendered) def test_description_output(self): title, description, metadata = parse_docstring(self.docstring) description_output = parse_rst(description, "model", "model:admindocs") description_rendered = ( '<p>Display an individual <a class="reference external" ' 'href="/admindocs/models/myapp.mymodel/">myapp.MyModel</a>.</p>\n' '<p><strong>Context</strong></p>\n<p><tt class="docutils literal">' 'RequestContext</tt></p>\n<dl class="docutils">\n<dt><tt class="' 'docutils literal">mymodel</tt></dt>\n<dd>An instance of <a class="' 'reference external" href="/admindocs/models/myapp.mymodel/">' "myapp.MyModel</a>.</dd>\n</dl>\n<p><strong>Template:</strong></p>" '\n<p><a class="reference external" href="/admindocs/templates/' 'myapp/my_template.html/">myapp/my_template.html</a> (DESCRIPTION)' "</p>\n" ) self.assertHTMLEqual(description_output, description_rendered) def test_initial_header_level(self): header = "should be h3...\n\nHeader\n------\n" output = parse_rst(header, "header") self.assertIn("<h3>Header</h3>", output) def test_parse_rst(self): """ parse_rst() should use `cmsreference` as the default role. """ markup = '<p><a class="reference external" href="/admindocs/%s">title</a></p>\n' self.assertEqual(parse_rst("`title`", "model"), markup % "models/title/") self.assertEqual(parse_rst("`title`", "view"), markup % "views/title/") self.assertEqual(parse_rst("`title`", "template"), markup % "templates/title/") self.assertEqual(parse_rst("`title`", "filter"), markup % "filters/#title") self.assertEqual(parse_rst("`title`", "tag"), markup % "tags/#title") def test_parse_rst_with_docstring_no_leading_line_feed(self): title, body, _ = parse_docstring("firstline\n\n second line") with captured_stderr() as stderr: self.assertEqual(parse_rst(title, ""), "<p>firstline</p>\n") self.assertEqual(parse_rst(body, ""), "<p>second line</p>\n") self.assertEqual(stderr.getvalue(), "") def test_parse_rst_view_case_sensitive(self): source = ":view:`myapp.views.Index`" rendered = ( '<p><a class="reference external" ' 'href="/admindocs/views/myapp.views.Index/">myapp.views.Index</a></p>' ) self.assertHTMLEqual(parse_rst(source, "view"), rendered) def test_parse_rst_template_case_sensitive(self): source = ":template:`Index.html`" rendered = ( '<p><a class="reference external" href="/admindocs/templates/Index.html/">' "Index.html</a></p>" ) self.assertHTMLEqual(parse_rst(source, "template"), rendered) def test_publish_parts(self): """ Django shouldn't break the default role for interpreted text when ``publish_parts`` is used directly, by setting it to ``cmsreference`` (#6681). """ import docutils self.assertNotEqual( docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, "cmsreference" ) source = "reST, `interpreted text`, default role." markup = "<p>reST, <cite>interpreted text</cite>, default role.</p>\n" parts = docutils.core.publish_parts(source=source, writer="html4css1") self.assertEqual(parts["fragment"], markup)
TestUtils
python
python-openxml__python-docx
src/docx/enum/dml.py
{ "start": 779, "end": 3346 }
class ____(BaseXmlEnum): """Indicates the Office theme color, one of those shown in the color gallery on the formatting ribbon. Alias: ``MSO_THEME_COLOR`` Example:: from docx.enum.dml import MSO_THEME_COLOR font.color.theme_color = MSO_THEME_COLOR.ACCENT_1 MS API name: `MsoThemeColorIndex` http://msdn.microsoft.com/en-us/library/office/ff860782(v=office.15).aspx """ NOT_THEME_COLOR = (0, "UNMAPPED", "Indicates the color is not a theme color.") """Indicates the color is not a theme color.""" ACCENT_1 = (5, "accent1", "Specifies the Accent 1 theme color.") """Specifies the Accent 1 theme color.""" ACCENT_2 = (6, "accent2", "Specifies the Accent 2 theme color.") """Specifies the Accent 2 theme color.""" ACCENT_3 = (7, "accent3", "Specifies the Accent 3 theme color.") """Specifies the Accent 3 theme color.""" ACCENT_4 = (8, "accent4", "Specifies the Accent 4 theme color.") """Specifies the Accent 4 theme color.""" ACCENT_5 = (9, "accent5", "Specifies the Accent 5 theme color.") """Specifies the Accent 5 theme color.""" ACCENT_6 = (10, "accent6", "Specifies the Accent 6 theme color.") """Specifies the Accent 6 theme color.""" BACKGROUND_1 = (14, "background1", "Specifies the Background 1 theme color.") """Specifies the Background 1 theme color.""" BACKGROUND_2 = (16, "background2", "Specifies the Background 2 theme color.") """Specifies the Background 2 theme color.""" DARK_1 = (1, "dark1", "Specifies the Dark 1 theme color.") """Specifies the Dark 1 theme color.""" DARK_2 = (3, "dark2", "Specifies the Dark 2 theme color.") """Specifies the Dark 2 theme color.""" FOLLOWED_HYPERLINK = ( 12, "followedHyperlink", "Specifies the theme color for a clicked hyperlink.", ) """Specifies the theme color for a clicked hyperlink.""" HYPERLINK = (11, "hyperlink", "Specifies the theme color for a hyperlink.") """Specifies the theme color for a hyperlink.""" LIGHT_1 = (2, "light1", "Specifies the Light 1 theme color.") """Specifies the Light 1 theme color.""" LIGHT_2 = (4, "light2", "Specifies the Light 2 theme color.") """Specifies the Light 2 theme color.""" TEXT_1 = (13, "text1", "Specifies the Text 1 theme color.") """Specifies the Text 1 theme color.""" TEXT_2 = (15, "text2", "Specifies the Text 2 theme color.") """Specifies the Text 2 theme color.""" MSO_THEME_COLOR = MSO_THEME_COLOR_INDEX
MSO_THEME_COLOR_INDEX
python
falconry__falcon
tests/test_typing.py
{ "start": 2483, "end": 6513 }
class ____: def process_request(self, req: FancyRequest, resp: FancyResponse) -> None: _process_auth(req, resp) # NOTE(vytas): Unlike req.context, resp.context.comment is type checked, # try misspelling it or using with an incompatible type. resp.context.comment = 'fancy req/resp' async def process_request_async( self, req: FancyAsyncRequest, resp: FancyAsyncResponse ) -> None: _process_auth(req, resp) resp.context.comment = 'fancy req/resp' def _sink_impl(req: falcon.Request, resp: falcon.Response) -> None: userid: str | None = str(req.context.userid) if req.context.userid else None resp.media = {'role': req.context.role, 'userid': userid} if req.path == '/not-found': raise falcon.HTTPNotFound() def sink_fancy_req(req: FancyRequest, resp: falcon.Response, **kwargs: Any) -> None: _sink_impl(req, resp) def sink_fancy_both(req: FancyRequest, resp: FancyResponse, **kwargs: Any) -> None: _sink_impl(req, resp) resp.context.comment += ' (sink)' resp.media.update(comment=resp.context.comment) async def sink_fancy_async_req( req: FancyAsyncRequest, resp: falcon.asgi.Response | None, **kwargs: Any ) -> None: if resp is not None: _sink_impl(req, resp) async def sink_fancy_async_both( req: FancyAsyncRequest, resp: FancyAsyncResponse | None, **kwargs: Any ) -> None: if resp is not None: _sink_impl(req, resp) resp.context.comment += ' (sink)' resp.media.update(comment=resp.context.comment) # NOTE(vytas): We don't use fixtures here because that is hard to marry to strict # type checking, Mypy complains that "Untyped decorator makes function untyped". def test_app_fancy_req() -> None: app = falcon.App(request_type=FancyRequest) app.add_middleware(AuthMiddlewareFancyRequest()) app.add_sink(sink_fancy_req) app.set_error_serializer(fancy_error_serializer) _exercise_app(app) def test_app_fancy_both() -> None: app = falcon.App(request_type=FancyRequest, response_type=FancyResponse) app.add_middleware(AuthMiddlewareFancyBoth()) app.add_sink(sink_fancy_both) app.set_error_serializer(fancy_error_serializer) _exercise_app(app) def test_app_fancy_async_req() -> None: app = falcon.asgi.App(request_type=FancyAsyncRequest) app.add_middleware(AuthMiddlewareFancyRequest()) app.add_sink(sink_fancy_async_req) app.set_error_serializer(fancy_asgi_error_serializer) _exercise_app(app) def test_app_fancy_async_both() -> None: app = falcon.asgi.App( request_type=FancyAsyncRequest, response_type=FancyAsyncResponse ) app.add_middleware(AuthMiddlewareFancyBoth()) app.add_sink(sink_fancy_async_both) app.set_error_serializer(fancy_asgi_error_serializer) _exercise_app(app) def _exercise_app(app: falcon.App[Any, Any]) -> None: client = falcon.testing.TestClient(app) result1 = client.get() assert result1.status_code == 200 assert result1.json in ( { 'role': 'anonymous', 'userid': None, }, { 'comment': 'fancy req/resp (sink)', 'role': 'anonymous', 'userid': None, }, ) result2 = client.get(headers={'Authorization': 'ApiKey 123'}) assert result2.status_code == 401 result3 = client.get(headers={'Authorization': 'Basic am9objoxMjM0'}) assert result3.status_code == 200 assert result3.json in ( { 'role': 'user', 'userid': '51e4b478-3825-4e46-9fd7-be7b61d616dc', }, { 'comment': 'fancy req/resp (sink)', 'role': 'user', 'userid': '51e4b478-3825-4e46-9fd7-be7b61d616dc', }, ) result4 = client.get('/not-found') assert result4.status_code == 404 assert result4.json == { 'asgi': isinstance(client.app, falcon.asgi.App), 'fancy': True, 'title': '404 Not Found', }
AuthMiddlewareFancyBoth
python
huggingface__transformers
src/transformers/models/aya_vision/modeling_aya_vision.py
{ "start": 4610, "end": 6200 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. image_hidden_states (`torch.FloatTensor`, *optional*): A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state. """ loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None past_key_values: Optional[Cache] = None hidden_states: Optional[tuple[torch.FloatTensor]] = None attentions: Optional[tuple[torch.FloatTensor]] = None image_hidden_states: Optional[torch.FloatTensor] = None @dataclass @auto_docstring( custom_intro=""" Base class for AyaVision outputs, with hidden states and attentions. """ )
AyaVisionCausalLMOutputWithPast
python
google__jax
jax/_src/interpreters/pxla.py
{ "start": 78121, "end": 87183 }
class ____: def __init__(self, shardings: tuple[GSPMDSharding | UnspecifiedValue, ...], avals: tuple[core.AbstractValue]): gspmd_shardings = [ s if (isinstance(s, (UnspecifiedValue, AUTO)) or (isinstance(s, NamedSharding) and isinstance(s.mesh, AbstractMesh))) else to_gspmd_sharding(s, a.ndim) # pytype: disable=attribute-error for s, a in zip(shardings, avals)] self._gspmd_shardings = gspmd_shardings self.shardings = shardings self.avals = avals def __hash__(self): return hash(tuple( (s._hlo_sharding_hash, s.memory_kind) if isinstance(s, GSPMDSharding) else s for s in self._gspmd_shardings)) def __eq__(self, other): if not isinstance(other, SemanticallyEqualShardings): return False return all( (op_shardings.are_hlo_shardings_equal(s._hlo_sharding, o._hlo_sharding) and s.memory_kind == o.memory_kind) if (isinstance(s, GSPMDSharding) and isinstance(o, GSPMDSharding)) else s == o for s, o in zip(self._gspmd_shardings, other._gspmd_shardings) ) def _raise_warnings_or_errors_for_jit_of_pmap( nreps: int, backend: xc.Client, name: str, jaxpr: core.Jaxpr) -> None: if nreps > 1: warnings.warn( f"The function {name} includes a pmap. Using " "jit-of-pmap can lead to inefficient data movement, as the outer jit " "does not preserve sharded data representations and instead collects " "input and output arrays onto a single device. " "Consider removing the outer jit unless you know what you're doing. " "See https://github.com/jax-ml/jax/issues/2926. Or " "use jax.shard_map instead of pmap under jit compilation.") if nreps > xb.device_count(backend): raise ValueError( f"compiling computation `{name}` that requires {nreps} replicas, but " f"only {xb.device_count(backend)} XLA devices are available.") if xb.process_count(backend) > 1 and ( nreps > 1 or dispatch.jaxpr_has_primitive(jaxpr, "xla_pmap") ): raise NotImplementedError( "jit of multi-host pmap not implemented (and jit-of-pmap can cause " "extra data movement anyway, so maybe you don't want it after all).") @weakref_lru_cache def _cached_lowering_to_hlo(closed_jaxpr: core.ClosedJaxpr, module_name, backend, num_const_args: int, in_avals, semantic_in_shardings, semantic_out_shardings, in_layouts, out_layouts, num_devices, device_assignment, donated_invars, all_default_mem_kind, inout_aliases: None | tuple[None | int, ...], propagated_out_mem_kinds: tuple[None | str, ...], platforms: tuple[str, ...], lowering_parameters: mlir.LoweringParameters, abstract_mesh: AbstractMesh | None): # in_avals, in_shardings, in_layouts include the jaxpr_const_args(jaxpr) out_avals = closed_jaxpr.out_avals jaxpr = closed_jaxpr.jaxpr in_shardings = semantic_in_shardings.shardings out_shardings = semantic_out_shardings.shardings log_priority = logging.WARNING if config.log_compiles.value else logging.DEBUG if logger.isEnabledFor(log_priority): logger.log(log_priority, "Compiling %s with global shapes and types %s. " "Argument mapping: %s.", module_name, in_avals, in_shardings) # Look at the number of replcas present in the jaxpr. In # lower_sharding_computation, nreps > 1 during `jit(pmap)` cases. This is # handled here so as to deprecate the lower_xla_callable codepath when # `jax.Array` is turned on by default. # TODO(yashkatariya): Remove this when `jit(pmap)` is removed. nreps = _jaxpr_replicas(jaxpr) _raise_warnings_or_errors_for_jit_of_pmap(nreps, backend, module_name, jaxpr) in_mlir_shardings: list[JSharding | AUTO | None] | None out_mlir_shardings: list[JSharding | AUTO | None] | None axis_ctx: mlir.AxisContext if nreps == 1: in_mlir_shardings = map(_to_logical_sharding, in_avals, in_shardings) out_mlir_shardings = map(_to_logical_sharding, out_avals, out_shardings) replicated_args = [False] * len(in_avals) axis_ctx = sharding_impls.ShardingContext(num_devices, device_assignment, abstract_mesh) num_partitions = num_devices else: # This path is triggered for `jit(pmap)` cases. replicated_args = None in_mlir_shardings = None out_mlir_shardings = None axis_env = sharding_impls.AxisEnv(nreps, (), ()) axis_ctx = sharding_impls.ReplicaAxisContext(axis_env) num_partitions = 1 if num_devices > 1: unsupported_effects = effects.ordered_effects.filter_in(closed_jaxpr.effects) unsupported_effects = effects.shardable_ordered_effects.filter_not_in( unsupported_effects) if len(unsupported_effects) > 0: raise ValueError( "The following ordered effects are not supported for " f"more than 1 device: {unsupported_effects}") ordered_effects = list(effects.ordered_effects.filter_in(closed_jaxpr.effects)) arg_names = ("",) * num_const_args + jaxpr._debug_info.safe_arg_names(len(in_avals) - num_const_args) with dispatch.log_elapsed_time( "Finished jaxpr to MLIR module conversion {fun_name} in {elapsed_time:.9f} sec", fun_name=module_name, event=dispatch.JAXPR_TO_MLIR_MODULE_EVENT): lowering_result = mlir.lower_jaxpr_to_module( module_name, closed_jaxpr, num_const_args=num_const_args, ordered_effects=ordered_effects, backend=backend, platforms=platforms, axis_context=axis_ctx, in_avals=in_avals, donated_args=donated_invars, replicated_args=replicated_args, arg_shardings=in_mlir_shardings, result_shardings=out_mlir_shardings, in_layouts=in_layouts, out_layouts=out_layouts, arg_names=arg_names, result_names=jaxpr._debug_info.safe_result_paths(len(out_avals)), num_replicas=nreps, num_partitions=num_partitions, all_default_mem_kind=all_default_mem_kind, input_output_aliases=inout_aliases, propagated_out_mem_kinds=propagated_out_mem_kinds, lowering_parameters=lowering_parameters) tuple_args = dispatch.should_tuple_args(len(in_avals), backend.platform) unordered_effects = list( effects.ordered_effects.filter_not_in(closed_jaxpr.effects)) return (lowering_result.module, lowering_result.keepalive, lowering_result.host_callbacks, unordered_effects, ordered_effects, nreps, tuple_args, lowering_result.shape_poly_state) @util.cache(max_size=2048, trace_context_in_key=False) def _create_device_list_cached(device_assignment: tuple[xc.Device, ...] ) -> xc.DeviceList: return xc.DeviceList(device_assignment) def _create_device_list( device_assignment: tuple[xc.Device, ...] | xc.DeviceList | None ) -> xc.DeviceList | None: if device_assignment is None or isinstance(device_assignment, xc.DeviceList): return device_assignment # type: ignore return _create_device_list_cached(device_assignment) @weakref_lru_cache def jaxpr_transfer_mem_kinds(jaxpr: core.Jaxpr): out = [] # type: ignore for eqn in jaxpr.eqns: if eqn.primitive is dispatch.device_put_p: out.extend(d for d in eqn.params['devices'] if isinstance(d, core.MemorySpace)) for subjaxpr in core.subjaxprs(jaxpr): out.extend(jaxpr_transfer_mem_kinds(subjaxpr)) return out def are_all_shardings_default_mem_kind(shardings): for i in shardings: if isinstance(i, (UnspecifiedValue, AUTO)): continue mem_kind = (core.mem_space_to_kind(i) if isinstance(i, core.MemorySpace) else i.memory_kind) if mem_kind is None: continue if mem_kind != 'device': return False return True @weakref_lru_cache def get_out_layouts_via_propagation(closed_jaxpr: core.ClosedJaxpr ) -> tuple[None | Layout]: env = {} # type: ignore jaxpr = closed_jaxpr.jaxpr def read(var): if type(var) is core.Literal: return None return env[var] def write(var, val): env[var] = val safe_map(write, jaxpr.invars, [None] * len(jaxpr.invars)) safe_map(write, jaxpr.constvars, [None] * len(jaxpr.constvars)) for eqn in jaxpr.eqns: # TODO(yashkatariya): Replace this with a registration system when there are # more primitives for layout propagation. if eqn.primitive is pjit.sharding_constraint_p: out_eqn_layouts = [eqn.params['layout']] else: out_eqn_layouts = [None] * len(eqn.outvars) safe_map(write, eqn.outvars, out_eqn_layouts) return tuple(safe_map(read, jaxpr.outvars)) MaybeLayout = Sequence[Union[Layout, AutoLayout, None]]
SemanticallyEqualShardings
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 84221, "end": 86237 }
class ____(multi_rv_frozen): __class_getitem__ = None def __init__(self, alpha, seed=None): self.alpha = _dirichlet_check_parameters(alpha) self._dist = dirichlet_gen(seed) def logpdf(self, x): return self._dist.logpdf(x, self.alpha) def pdf(self, x): return self._dist.pdf(x, self.alpha) def mean(self): return self._dist.mean(self.alpha) def var(self): return self._dist.var(self.alpha) def cov(self): return self._dist.cov(self.alpha) def entropy(self): return self._dist.entropy(self.alpha) def rvs(self, size=1, random_state=None): return self._dist.rvs(self.alpha, size, random_state) # Set frozen generator docstrings from corresponding docstrings in # multivariate_normal_gen and fill in default strings in class docstrings for name in ['logpdf', 'pdf', 'rvs', 'mean', 'var', 'cov', 'entropy']: method = dirichlet_gen.__dict__[name] method_frozen = dirichlet_frozen.__dict__[name] method_frozen.__doc__ = doccer.docformat( method.__doc__, dirichlet_docdict_noparams) method.__doc__ = doccer.docformat(method.__doc__, dirichlet_docdict_params) _wishart_doc_default_callparams = """\ df : int Degrees of freedom, must be greater than or equal to dimension of the scale matrix scale : array_like Symmetric positive definite scale matrix of the distribution """ _wishart_doc_callparams_note = "" _wishart_doc_frozen_callparams = "" _wishart_doc_frozen_callparams_note = """\ See class definition for a detailed description of parameters.""" wishart_docdict_params = { '_doc_default_callparams': _wishart_doc_default_callparams, '_doc_callparams_note': _wishart_doc_callparams_note, '_doc_random_state': _doc_random_state } wishart_docdict_noparams = { '_doc_default_callparams': _wishart_doc_frozen_callparams, '_doc_callparams_note': _wishart_doc_frozen_callparams_note, '_doc_random_state': _doc_random_state }
dirichlet_frozen
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 119498, "end": 128716 }
class ____(rv_continuous): r"""A generalized hyperbolic continuous random variable. %(before_notes)s See Also -------- t, norminvgauss, geninvgauss, laplace, cauchy Notes ----- The probability density function for `genhyperbolic` is: .. math:: f(x, p, a, b) = \frac{(a^2 - b^2)^{p/2}} {\sqrt{2\pi}a^{p-1/2} K_p\Big(\sqrt{a^2 - b^2}\Big)} e^{bx} \times \frac{K_{p - 1/2} (a \sqrt{1 + x^2})} {(\sqrt{1 + x^2})^{1/2 - p}} for :math:`x, p \in ( - \infty; \infty)`, :math:`|b| < a` if :math:`p \ge 0`, :math:`|b| \le a` if :math:`p < 0`. :math:`K_{p}(.)` denotes the modified Bessel function of the second kind and order :math:`p` (`scipy.special.kv`) `genhyperbolic` takes ``p`` as a tail parameter, ``a`` as a shape parameter, ``b`` as a skewness parameter. %(after_notes)s The original parameterization of the Generalized Hyperbolic Distribution is found in [1]_ as follows .. math:: f(x, \lambda, \alpha, \beta, \delta, \mu) = \frac{(\gamma/\delta)^\lambda}{\sqrt{2\pi}K_\lambda(\delta \gamma)} e^{\beta (x - \mu)} \times \frac{K_{\lambda - 1/2} (\alpha \sqrt{\delta^2 + (x - \mu)^2})} {(\sqrt{\delta^2 + (x - \mu)^2} / \alpha)^{1/2 - \lambda}} for :math:`x \in ( - \infty; \infty)`, :math:`\gamma := \sqrt{\alpha^2 - \beta^2}`, :math:`\lambda, \mu \in ( - \infty; \infty)`, :math:`\delta \ge 0, |\beta| < \alpha` if :math:`\lambda \ge 0`, :math:`\delta > 0, |\beta| \le \alpha` if :math:`\lambda < 0`. The location-scale-based parameterization implemented in SciPy is based on [2]_, where :math:`a = \alpha\delta`, :math:`b = \beta\delta`, :math:`p = \lambda`, :math:`scale=\delta` and :math:`loc=\mu` Moments are implemented based on [3]_ and [4]_. For the distributions that are a special case such as Student's t, it is not recommended to rely on the implementation of genhyperbolic. To avoid potential numerical problems and for performance reasons, the methods of the specific distributions should be used. References ---------- .. [1] O. Barndorff-Nielsen, "Hyperbolic Distributions and Distributions on Hyperbolae", Scandinavian Journal of Statistics, Vol. 5(3), pp. 151-157, 1978. https://www.jstor.org/stable/4615705 .. [2] Eberlein E., Prause K. (2002) The Generalized Hyperbolic Model: Financial Derivatives and Risk Measures. In: Geman H., Madan D., Pliska S.R., Vorst T. (eds) Mathematical Finance - Bachelier Congress 2000. Springer Finance. Springer, Berlin, Heidelberg. :doi:`10.1007/978-3-662-12429-1_12` .. [3] Scott, David J, Würtz, Diethelm, Dong, Christine and Tran, Thanh Tam, (2009), Moments of the generalized hyperbolic distribution, MPRA Paper, University Library of Munich, Germany, https://EconPapers.repec.org/RePEc:pra:mprapa:19081. .. [4] E. Eberlein and E. A. von Hammerstein. Generalized hyperbolic and inverse Gaussian distributions: Limiting cases and approximation of processes. FDM Preprint 80, April 2003. University of Freiburg. https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content %(example)s """ def _argcheck(self, p, a, b): return (np.logical_and(np.abs(b) < a, p >= 0) | np.logical_and(np.abs(b) <= a, p < 0)) def _shape_info(self): ip = _ShapeInfo("p", False, (-np.inf, np.inf), (False, False)) ia = _ShapeInfo("a", False, (0, np.inf), (True, False)) ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, False)) return [ip, ia, ib] def _fitstart(self, data): # Arbitrary, but the default p = a = b = 1 is not valid; the # distribution requires |b| < a if p >= 0. return super()._fitstart(data, args=(1, 1, 0.5)) def _logpdf(self, x, p, a, b): # kve instead of kv works better for large values of p # and smaller values of sqrt(a^2 - b^2) @np.vectorize def _logpdf_single(x, p, a, b): return _stats.genhyperbolic_logpdf(x, p, a, b) return _logpdf_single(x, p, a, b) def _pdf(self, x, p, a, b): # kve instead of kv works better for large values of p # and smaller values of sqrt(a^2 - b^2) @np.vectorize def _pdf_single(x, p, a, b): return _stats.genhyperbolic_pdf(x, p, a, b) return _pdf_single(x, p, a, b) # np.vectorize isn't currently designed to be used as a decorator, # so use a lambda instead. This allows us to decorate the function # with `np.vectorize` and still provide the `otypes` parameter. @lambda func: np.vectorize(func, otypes=[np.float64]) @staticmethod def _integrate_pdf(x0, x1, p, a, b): """ Integrate the pdf of the genhyberbolic distribution from x0 to x1. This is a private function used by _cdf() and _sf() only; either x0 will be -inf or x1 will be inf. """ user_data = np.array([p, a, b], float).ctypes.data_as(ctypes.c_void_p) llc = LowLevelCallable.from_cython(_stats, '_genhyperbolic_pdf', user_data) d = np.sqrt((a + b)*(a - b)) mean = b/d * sc.kv(p + 1, d) / sc.kv(p, d) epsrel = 1e-10 epsabs = 0 if x0 < mean < x1: # If the interval includes the mean, integrate over the two # intervals [x0, mean] and [mean, x1] and add. If we try to do # the integral in one call of quad and the non-infinite endpoint # is far in the tail, quad might return an incorrect result # because it does not "see" the peak of the PDF. intgrl = (integrate.quad(llc, x0, mean, epsrel=epsrel, epsabs=epsabs)[0] + integrate.quad(llc, mean, x1, epsrel=epsrel, epsabs=epsabs)[0]) else: intgrl = integrate.quad(llc, x0, x1, epsrel=epsrel, epsabs=epsabs)[0] if np.isnan(intgrl): msg = ("Infinite values encountered in scipy.special.kve. " "Values replaced by NaN to avoid incorrect results.") warnings.warn(msg, RuntimeWarning, stacklevel=3) return max(0.0, min(1.0, intgrl)) def _cdf(self, x, p, a, b): return self._integrate_pdf(-np.inf, x, p, a, b) def _sf(self, x, p, a, b): return self._integrate_pdf(x, np.inf, p, a, b) def _rvs(self, p, a, b, size=None, random_state=None): # note: X = b * V + sqrt(V) * X has a # generalized hyperbolic distribution # if X is standard normal and V is # geninvgauss(p = p, b = t2, loc = loc, scale = t3) t1 = np.float_power(a, 2) - np.float_power(b, 2) # b in the GIG t2 = np.float_power(t1, 0.5) # scale in the GIG t3 = np.float_power(t1, - 0.5) gig = geninvgauss.rvs( p=p, b=t2, scale=t3, size=size, random_state=random_state ) normst = norm.rvs(size=size, random_state=random_state) return b * gig + np.sqrt(gig) * normst def _stats(self, p, a, b): # https://mpra.ub.uni-muenchen.de/19081/1/MPRA_paper_19081.pdf # https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content # standardized moments p, a, b = np.broadcast_arrays(p, a, b) t1 = np.float_power(a, 2) - np.float_power(b, 2) t1 = np.float_power(t1, 0.5) t2 = np.float_power(1, 2) * np.float_power(t1, - 1) integers = np.linspace(0, 4, 5) # make integers perpendicular to existing dimensions integers = integers.reshape(integers.shape + (1,) * p.ndim) b0, b1, b2, b3, b4 = sc.kv(p + integers, t1) r1, r2, r3, r4 = (b / b0 for b in (b1, b2, b3, b4)) m = b * t2 * r1 v = ( t2 * r1 + np.float_power(b, 2) * np.float_power(t2, 2) * (r2 - np.float_power(r1, 2)) ) m3e = ( np.float_power(b, 3) * np.float_power(t2, 3) * (r3 - 3 * b2 * b1 * np.float_power(b0, -2) + 2 * np.float_power(r1, 3)) + 3 * b * np.float_power(t2, 2) * (r2 - np.float_power(r1, 2)) ) s = m3e * np.float_power(v, - 3 / 2) m4e = ( np.float_power(b, 4) * np.float_power(t2, 4) * (r4 - 4 * b3 * b1 * np.float_power(b0, - 2) + 6 * b2 * np.float_power(b1, 2) * np.float_power(b0, - 3) - 3 * np.float_power(r1, 4)) + np.float_power(b, 2) * np.float_power(t2, 3) * (6 * r3 - 12 * b2 * b1 * np.float_power(b0, - 2) + 6 * np.float_power(r1, 3)) + 3 * np.float_power(t2, 2) * r2 ) k = m4e * np.float_power(v, -2) - 3 return m, v, s, k genhyperbolic = genhyperbolic_gen(name='genhyperbolic')
genhyperbolic_gen
python
pennersr__django-allauth
tests/apps/socialaccount/providers/hubic/tests.py
{ "start": 238, "end": 938 }
class ____(OAuth2TestsMixin, TestCase): provider_id = HubicProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "email": "user@example.com", "firstname": "Test", "activated": true, "creationDate": "2014-04-17T17:04:01+02:00", "language": "en", "status": "ok", "offer": "25g", "lastname": "User" } """, ) def get_expected_to_str(self): return "user@example.com" def get_login_response_json(self, with_refresh_token=True): return '{\ "access_token": "testac",\ "expires_in": "3600",\ "refresh_token": "testrf",\ "token_type": "Bearer"\ }'
HubicTests
python
pyca__cryptography
src/cryptography/hazmat/primitives/_modes.py
{ "start": 1513, "end": 3075 }
class ____(Mode, metaclass=abc.ABCMeta): @property @abc.abstractmethod def tag(self) -> bytes | None: """ The value of the tag supplied to the constructor of this mode. """ def _check_aes_key_length(self: Mode, algorithm: CipherAlgorithm) -> None: if algorithm.key_size > 256 and algorithm.name == "AES": raise ValueError( "Only 128, 192, and 256 bit keys are allowed for this AES mode" ) def _check_iv_length( self: ModeWithInitializationVector, algorithm: BlockCipherAlgorithm ) -> None: iv_len = len(self.initialization_vector) if iv_len * 8 != algorithm.block_size: raise ValueError(f"Invalid IV size ({iv_len}) for {self.name}.") def _check_nonce_length( nonce: utils.Buffer, name: str, algorithm: CipherAlgorithm ) -> None: if not isinstance(algorithm, BlockCipherAlgorithm): raise UnsupportedAlgorithm( f"{name} requires a block cipher algorithm", _Reasons.UNSUPPORTED_CIPHER, ) if len(nonce) * 8 != algorithm.block_size: raise ValueError(f"Invalid nonce size ({len(nonce)}) for {name}.") def _check_iv_and_key_length( self: ModeWithInitializationVector, algorithm: CipherAlgorithm ) -> None: if not isinstance(algorithm, BlockCipherAlgorithm): raise UnsupportedAlgorithm( f"{self} requires a block cipher algorithm", _Reasons.UNSUPPORTED_CIPHER, ) _check_aes_key_length(self, algorithm) _check_iv_length(self, algorithm)
ModeWithAuthenticationTag
python
sqlalchemy__sqlalchemy
test/orm/test_versioning.py
{ "start": 33457, "end": 34850 }
class ____(fixtures.MappedTest): __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "base", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("version_id", Integer, nullable=True), Column("data", String(50)), ) Table( "sub", metadata, Column("id", Integer, ForeignKey("base.id"), primary_key=True), Column("sub_data", String(50)), ) @classmethod def setup_classes(cls): class Base(cls.Basic): pass class Sub(Base): pass def test_update_child_table_only(self): Base, sub, base, Sub = ( self.classes.Base, self.tables.sub, self.tables.base, self.classes.Sub, ) self.mapper_registry.map_imperatively( Base, base, version_id_col=base.c.version_id ) self.mapper_registry.map_imperatively(Sub, sub, inherits=Base) s = fixture_session() s1 = Sub(data="b", sub_data="s") s.add(s1) s.commit() s1.sub_data = "s2" with conditional_sane_rowcount_warnings(update=True): s.commit() eq_(s1.version_id, 2)
PlainInheritanceTest
python
ray-project__ray
python/ray/util/client/client_pickler.py
{ "start": 4842, "end": 6012 }
class ____(pickle.Unpickler): def persistent_load(self, pid): assert isinstance(pid, PickleStub) if pid.type == "Object": return ClientObjectRef(pid.ref_id) elif pid.type == "Actor": return ClientActorHandle(ClientActorRef(pid.ref_id)) else: raise NotImplementedError("Being passed back an unknown stub") def dumps_from_client(obj: Any, client_id: str, protocol=None) -> bytes: with io.BytesIO() as file: cp = ClientPickler(client_id, file, protocol=protocol) cp.dump(obj) return file.getvalue() def loads_from_server( data: bytes, *, fix_imports=True, encoding="ASCII", errors="strict" ) -> Any: if isinstance(data, str): raise TypeError("Can't load pickle from unicode string") file = io.BytesIO(data) return ServerUnpickler( file, fix_imports=fix_imports, encoding=encoding, errors=errors ).load() def convert_to_arg(val: Any, client_id: str) -> ray_client_pb2.Arg: out = ray_client_pb2.Arg() out.local = ray_client_pb2.Arg.Locality.INTERNED out.data = dumps_from_client(val, client_id) return out
ServerUnpickler
python
davidhalter__parso
test/normalizer_issue_files/python.py
{ "start": 193, "end": 1222 }
class ____: cls_var: ClassVar[str] def m(self): xs: List[int] = [] # True and False are keywords in Python 3 and therefore need a space. #: E275:13 E275:14 norman = True+False #: E302+3:0 def a(): pass async def b(): pass # Okay async def add(a: int = 0, b: int = 0) -> int: return a + b # Previously E251 four times #: E221:5 async def add(a: int = 0, b: int = 0) -> int: return a + b # Previously just E272+1:5 E272+4:5 #: E302+3 E221:5 E221+3:5 async def x(): pass async def x(y: int = 1): pass #: E704:16 async def f(x): return 2 a[b1, :] == a[b1, ...] # Annotated Function Definitions # Okay def munge(input: AnyStr, sep: AnyStr = None, limit=1000, extra: Union[str, dict] = None) -> AnyStr: pass #: E225:24 E225:26 def x(b: tuple = (1, 2))->int: return a + b #: E252:11 E252:12 E231:8 def b(a:int=1): pass if alpha[:-i]: *a, b = (1, 2, 3) # Named only arguments def foo(*, asdf): pass def foo2(bar, *, asdf=2): pass
Class
python
sympy__sympy
sympy/combinatorics/galois.py
{ "start": 3136, "end": 17867 }
class ____(Enum): """ Names for the transitive subgroups of S6. """ C6 = "C6" S3 = "S3" D6 = "D6" A4 = "A4" G18 = "G18" A4xC2 = "A4 x C2" S4m = "S4-" S4p = "S4+" G36m = "G36-" G36p = "G36+" S4xC2 = "S4 x C2" PSL2F5 = "PSL2(F5)" G72 = "G72" PGL2F5 = "PGL2(F5)" A6 = "A6" S6 = "S6" def get_perm_group(self): if self == S6TransitiveSubgroups.C6: return CyclicGroup(6) elif self == S6TransitiveSubgroups.S3: return S3_in_S6() elif self == S6TransitiveSubgroups.D6: return DihedralGroup(6) elif self == S6TransitiveSubgroups.A4: return A4_in_S6() elif self == S6TransitiveSubgroups.G18: return G18() elif self == S6TransitiveSubgroups.A4xC2: return A4xC2() elif self == S6TransitiveSubgroups.S4m: return S4m() elif self == S6TransitiveSubgroups.S4p: return S4p() elif self == S6TransitiveSubgroups.G36m: return G36m() elif self == S6TransitiveSubgroups.G36p: return G36p() elif self == S6TransitiveSubgroups.S4xC2: return S4xC2() elif self == S6TransitiveSubgroups.PSL2F5: return PSL2F5() elif self == S6TransitiveSubgroups.G72: return G72() elif self == S6TransitiveSubgroups.PGL2F5: return PGL2F5() elif self == S6TransitiveSubgroups.A6: return AlternatingGroup(6) elif self == S6TransitiveSubgroups.S6: return SymmetricGroup(6) def four_group(): """ Return a representation of the Klein four-group as a transitive subgroup of S4. """ return PermutationGroup( Permutation(0, 1)(2, 3), Permutation(0, 2)(1, 3) ) def M20(): """ Return a representation of the metacyclic group M20, a transitive subgroup of S5 that is one of the possible Galois groups for polys of degree 5. Notes ===== See [1], Page 323. """ G = PermutationGroup(Permutation(0, 1, 2, 3, 4), Permutation(1, 2, 4, 3)) G._degree = 5 G._order = 20 G._is_transitive = True G._is_sym = False G._is_alt = False G._is_cyclic = False G._is_dihedral = False return G def S3_in_S6(): """ Return a representation of S3 as a transitive subgroup of S6. Notes ===== The representation is found by viewing the group as the symmetries of a triangular prism. """ G = PermutationGroup(Permutation(0, 1, 2)(3, 4, 5), Permutation(0, 3)(2, 4)(1, 5)) set_symmetric_group_properties(G, 3, 6) return G def A4_in_S6(): """ Return a representation of A4 as a transitive subgroup of S6. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ G = PermutationGroup(Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4)) set_alternating_group_properties(G, 4, 6) return G def S4m(): """ Return a representation of the S4- transitive subgroup of S6. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ G = PermutationGroup(Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3)) set_symmetric_group_properties(G, 4, 6) return G def S4p(): """ Return a representation of the S4+ transitive subgroup of S6. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ G = PermutationGroup(Permutation(0, 2, 4, 1)(3, 5), Permutation(0, 3)(4, 5)) set_symmetric_group_properties(G, 4, 6) return G def A4xC2(): """ Return a representation of the (A4 x C2) transitive subgroup of S6. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ return PermutationGroup( Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4), Permutation(5)(2, 4)) def S4xC2(): """ Return a representation of the (S4 x C2) transitive subgroup of S6. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ return PermutationGroup( Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3), Permutation(1, 4)(3, 5)) def G18(): """ Return a representation of the group G18, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with C2. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(3, 4, 5), Permutation(0, 4)(1, 5)(2, 3)) def G36m(): """ Return a representation of the group G36-, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with C2^2. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(3, 4, 5), Permutation(1, 2)(3, 5), Permutation(0, 4)(1, 5)(2, 3)) def G36p(): """ Return a representation of the group G36+, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with C4. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(3, 4, 5), Permutation(0, 5, 2, 3)(1, 4)) def G72(): """ Return a representation of the group G72, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with D4. Notes ===== See [1], Page 325. """ return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(0, 4, 1, 3)(2, 5), Permutation(0, 3)(1, 4)(2, 5)) def PSL2F5(): r""" Return a representation of the group $PSL_2(\mathbb{F}_5)$, as a transitive subgroup of S6, isomorphic to $A_5$. Notes ===== This was computed using :py:func:`~.find_transitive_subgroups_of_S6`. """ G = PermutationGroup( Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 4, 3, 1, 5)) set_alternating_group_properties(G, 5, 6) return G def PGL2F5(): r""" Return a representation of the group $PGL_2(\mathbb{F}_5)$, as a transitive subgroup of S6, isomorphic to $S_5$. Notes ===== See [1], Page 325. """ G = PermutationGroup( Permutation(0, 1, 2, 3, 4), Permutation(0, 5)(1, 2)(3, 4)) set_symmetric_group_properties(G, 5, 6) return G def find_transitive_subgroups_of_S6(*targets, print_report=False): r""" Search for certain transitive subgroups of $S_6$. The symmetric group $S_6$ has 16 different transitive subgroups, up to conjugacy. Some are more easily constructed than others. For example, the dihedral group $D_6$ is immediately found, but it is not at all obvious how to realize $S_4$ or $S_5$ *transitively* within $S_6$. In some cases there are well-known constructions that can be used. For example, $S_5$ is isomorphic to $PGL_2(\mathbb{F}_5)$, which acts in a natural way on the projective line $P^1(\mathbb{F}_5)$, a set of order 6. In absence of such special constructions however, we can simply search for generators. For example, transitive instances of $A_4$ and $S_4$ can be found within $S_6$ in this way. Once we are engaged in such searches, it may then be easier (if less elegant) to find even those groups like $S_5$ that do have special constructions, by mere search. This function locates generators for transitive instances in $S_6$ of the following subgroups: * $A_4$ * $S_4^-$ ($S_4$ not contained within $A_6$) * $S_4^+$ ($S_4$ contained within $A_6$) * $A_4 \times C_2$ * $S_4 \times C_2$ * $G_{18} = C_3^2 \rtimes C_2$ * $G_{36}^- = C_3^2 \rtimes C_2^2$ * $G_{36}^+ = C_3^2 \rtimes C_4$ * $G_{72} = C_3^2 \rtimes D_4$ * $A_5$ * $S_5$ Note: Each of these groups also has a dedicated function in this module that returns the group immediately, using generators that were found by this search procedure. The search procedure serves as a record of how these generators were found. Also, due to randomness in the generation of the elements of permutation groups, it can be called again, in order to (probably) get different generators for the same groups. Parameters ========== targets : list of :py:class:`~.S6TransitiveSubgroups` values The groups you want to find. print_report : bool (default False) If True, print to stdout the generators found for each group. Returns ======= dict mapping each name in *targets* to the :py:class:`~.PermutationGroup` that was found References ========== .. [2] https://en.wikipedia.org/wiki/Projective_linear_group#Exceptional_isomorphisms .. [3] https://en.wikipedia.org/wiki/Automorphisms_of_the_symmetric_and_alternating_groups#PGL%282,5%29 """ def elts_by_order(G): """Sort the elements of a group by their order. """ elts = defaultdict(list) for g in G.elements: elts[g.order()].append(g) return elts def order_profile(G, name=None): """Determine how many elements a group has, of each order. """ elts = elts_by_order(G) profile = {o:len(e) for o, e in elts.items()} if name: print(f'{name}: ' + ' '.join(f'{len(profile[r])}@{r}' for r in sorted(profile.keys()))) return profile S6 = SymmetricGroup(6) A6 = AlternatingGroup(6) S6_by_order = elts_by_order(S6) def search(existing_gens, needed_gen_orders, order, alt=None, profile=None, anti_profile=None): """ Find a transitive subgroup of S6. Parameters ========== existing_gens : list of Permutation Optionally empty list of generators that must be in the group. needed_gen_orders : list of positive int Nonempty list of the orders of the additional generators that are to be found. order: int The order of the group being sought. alt: bool, None If True, require the group to be contained in A6. If False, require the group not to be contained in A6. profile : dict If given, the group's order profile must equal this. anti_profile : dict If given, the group's order profile must *not* equal this. """ for gens in itertools.product(*[S6_by_order[n] for n in needed_gen_orders]): if len(set(gens)) < len(gens): continue G = PermutationGroup(existing_gens + list(gens)) if G.order() == order and G.is_transitive(): if alt is not None and G.is_subgroup(A6) != alt: continue if profile and order_profile(G) != profile: continue if anti_profile and order_profile(G) == anti_profile: continue return G def match_known_group(G, alt=None): needed = [g.order() for g in G.generators] return search([], needed, G.order(), alt=alt, profile=order_profile(G)) found = {} def finish_up(name, G): found[name] = G if print_report: print("=" * 40) print(f"{name}:") print(G.generators) if S6TransitiveSubgroups.A4 in targets or S6TransitiveSubgroups.A4xC2 in targets: A4_in_S6 = match_known_group(AlternatingGroup(4)) finish_up(S6TransitiveSubgroups.A4, A4_in_S6) if S6TransitiveSubgroups.S4m in targets or S6TransitiveSubgroups.S4xC2 in targets: S4m_in_S6 = match_known_group(SymmetricGroup(4), alt=False) finish_up(S6TransitiveSubgroups.S4m, S4m_in_S6) if S6TransitiveSubgroups.S4p in targets: S4p_in_S6 = match_known_group(SymmetricGroup(4), alt=True) finish_up(S6TransitiveSubgroups.S4p, S4p_in_S6) if S6TransitiveSubgroups.A4xC2 in targets: A4xC2_in_S6 = search(A4_in_S6.generators, [2], 24, anti_profile=order_profile(SymmetricGroup(4))) finish_up(S6TransitiveSubgroups.A4xC2, A4xC2_in_S6) if S6TransitiveSubgroups.S4xC2 in targets: S4xC2_in_S6 = search(S4m_in_S6.generators, [2], 48) finish_up(S6TransitiveSubgroups.S4xC2, S4xC2_in_S6) # For the normal factor N = C3^2 in any of the G_n subgroups, we take one # obvious instance of C3^2 in S6: N_gens = [Permutation(5)(0, 1, 2), Permutation(5)(3, 4, 5)] if S6TransitiveSubgroups.G18 in targets: G18_in_S6 = search(N_gens, [2], 18) finish_up(S6TransitiveSubgroups.G18, G18_in_S6) if S6TransitiveSubgroups.G36m in targets: G36m_in_S6 = search(N_gens, [2, 2], 36, alt=False) finish_up(S6TransitiveSubgroups.G36m, G36m_in_S6) if S6TransitiveSubgroups.G36p in targets: G36p_in_S6 = search(N_gens, [4], 36, alt=True) finish_up(S6TransitiveSubgroups.G36p, G36p_in_S6) if S6TransitiveSubgroups.G72 in targets: G72_in_S6 = search(N_gens, [4, 2], 72) finish_up(S6TransitiveSubgroups.G72, G72_in_S6) # The PSL2(F5) and PGL2(F5) subgroups are isomorphic to A5 and S5, resp. if S6TransitiveSubgroups.PSL2F5 in targets: PSL2F5_in_S6 = match_known_group(AlternatingGroup(5)) finish_up(S6TransitiveSubgroups.PSL2F5, PSL2F5_in_S6) if S6TransitiveSubgroups.PGL2F5 in targets: PGL2F5_in_S6 = match_known_group(SymmetricGroup(5)) finish_up(S6TransitiveSubgroups.PGL2F5, PGL2F5_in_S6) # There is little need to "search" for any of the groups C6, S3, D6, A6, # or S6, since they all have obvious realizations within S6. However, we # support them here just in case a random representation is desired. if S6TransitiveSubgroups.C6 in targets: C6 = match_known_group(CyclicGroup(6)) finish_up(S6TransitiveSubgroups.C6, C6) if S6TransitiveSubgroups.S3 in targets: S3 = match_known_group(SymmetricGroup(3)) finish_up(S6TransitiveSubgroups.S3, S3) if S6TransitiveSubgroups.D6 in targets: D6 = match_known_group(DihedralGroup(6)) finish_up(S6TransitiveSubgroups.D6, D6) if S6TransitiveSubgroups.A6 in targets: A6 = match_known_group(A6) finish_up(S6TransitiveSubgroups.A6, A6) if S6TransitiveSubgroups.S6 in targets: S6 = match_known_group(S6) finish_up(S6TransitiveSubgroups.S6, S6) return found
S6TransitiveSubgroups
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-motherduck/destination_motherduck/processors/duckdb.py
{ "start": 1070, "end": 3942 }
class ____(SqlConfig): """Configuration for DuckDB.""" db_path: Path | str = Field() """Normally db_path is a Path object. The database name will be inferred from the file name. For example, given a `db_path` of `/path/to/my/duckdb-file`, the database name is `my_db`. """ schema_name: str = Field(default="main") """The name of the schema to write to. Defaults to "main".""" @overrides def get_sql_alchemy_url(self) -> SecretString: """Return the SQLAlchemy URL to use.""" # Suppress warnings from DuckDB about reflection on indices. # https://github.com/Mause/duckdb_engine/issues/905 warnings.filterwarnings( "ignore", message="duckdb-engine doesn't yet support reflection on indices", category=DuckDBEngineWarning, ) parsed_db_path = urlparse(self.db_path) if parsed_db_path.scheme == MOTHERDUCK_SCHEME: path = f"{MOTHERDUCK_SCHEME}:{parsed_db_path.path}" else: path = parsed_db_path.path return SecretString(f"duckdb:///{path!s}") def get_duckdb_config(self) -> Dict[str, Any]: """Get config dictionary to pass to duckdb""" return dict(parse_qsl(urlparse(self.db_path).query)) @overrides def get_database_name(self) -> str: """Return the name of the database.""" if self.db_path == ":memory:": return "memory" # Split the path on the appropriate separator ("/" or "\") split_on: Literal["/", "\\"] = "\\" if "\\" in str(self.db_path) else "/" # Return the file name without the extension return str(self.db_path).split(sep=split_on)[-1].split(".")[0] def _is_file_based_db(self) -> bool: """Return whether the database is file-based.""" if isinstance(self.db_path, Path): return True db_path_str = str(self.db_path) return ( ("/" in db_path_str or "\\" in db_path_str) and db_path_str != ":memory:" and f"{MOTHERDUCK_SCHEME}:" not in db_path_str and "motherduck:" not in db_path_str ) @overrides def get_sql_engine(self) -> Engine: """ Return a new SQL engine to use. This method is overridden to: - ensure that the database parent directory is created if it doesn't exist. - pass the DuckDB query parameters (such as motherduck_token) via the config """ if self._is_file_based_db(): Path(self.db_path).parent.mkdir(parents=True, exist_ok=True) return create_engine( url=self.get_sql_alchemy_url(), echo=DEBUG_MODE, execution_options={ "schema_translate_map": {None: self.schema_name}, }, future=True, )
DuckDBConfig
python
getsentry__sentry
tests/sentry/models/test_debugfile.py
{ "start": 898, "end": 7393 }
class ____(TestCase): def test_delete_dif(self) -> None: dif = self.create_dif_file( debug_id="dfb8e43a-f242-3d73-a453-aeb6a777ef75-feedface", features=["debug", "unwind"] ) dif_id = dif.id dif.delete() assert not ProjectDebugFile.objects.filter(id=dif_id).exists() assert not File.objects.filter(id=dif.file.id).exists() def test_find_dif_by_debug_id(self) -> None: debug_id1 = "dfb8e43a-f242-3d73-a453-aeb6a777ef75" debug_id2 = "19bd7a09-3e31-4911-a5cd-8e829b845407" debug_id3 = "7d402821-fae6-4ebc-bbb2-152f8e3b3352" self.create_dif_file(debug_id=debug_id1) dif1 = self.create_dif_file(debug_id=debug_id1) dif2 = self.create_dif_file(debug_id=debug_id2) difs = ProjectDebugFile.objects.find_by_debug_ids( project=self.project, debug_ids=[debug_id1, debug_id2, debug_id3] ) assert difs[debug_id1].id == dif1.id assert difs[debug_id2].id == dif2.id assert debug_id3 not in difs def test_find_dif_by_feature(self) -> None: debug_id1 = "dfb8e43a-f242-3d73-a453-aeb6a777ef75" debug_id2 = "19bd7a09-3e31-4911-a5cd-8e829b845407" debug_id3 = "7d402821-fae6-4ebc-bbb2-152f8e3b3352" self.create_dif_file(debug_id=debug_id1, features=["debug"]) dif1 = self.create_dif_file(debug_id=debug_id1, features=["debug"]) self.create_dif_file(debug_id=debug_id1, features=["unwind"]) dif2 = self.create_dif_file(debug_id=debug_id2) difs = ProjectDebugFile.objects.find_by_debug_ids( project=self.project, debug_ids=[debug_id1, debug_id2, debug_id3], features=["debug"] ) assert difs[debug_id1].id == dif1.id assert difs[debug_id2].id == dif2.id assert debug_id3 not in difs def test_find_dif_by_features(self) -> None: debug_id1 = "dfb8e43a-f242-3d73-a453-aeb6a777ef75" debug_id2 = "19bd7a09-3e31-4911-a5cd-8e829b845407" debug_id3 = "7d402821-fae6-4ebc-bbb2-152f8e3b3352" dif1 = self.create_dif_file(debug_id=debug_id1, features=["debug", "unwind"]) self.create_dif_file(debug_id=debug_id1, features=["debug"]) self.create_dif_file(debug_id=debug_id1, features=["unwind"]) dif2 = self.create_dif_file(debug_id=debug_id2) difs = ProjectDebugFile.objects.find_by_debug_ids( project=self.project, debug_ids=[debug_id1, debug_id2, debug_id3], features=["debug", "unwind"], ) assert difs[debug_id1].id == dif1.id assert difs[debug_id2].id == dif2.id assert debug_id3 not in difs def test_find_legacy_dif_by_features(self) -> None: debug_id1 = "dfb8e43a-f242-3d73-a453-aeb6a777ef75" self.create_dif_file(debug_id=debug_id1) dif1 = self.create_dif_file(debug_id=debug_id1) # XXX: If no file has features, in a group, the newest one is chosen, # regardless of the required feature set. difs = ProjectDebugFile.objects.find_by_debug_ids( project=self.project, debug_ids=[debug_id1], features=["debug"] ) assert difs[debug_id1].id == dif1.id def test_find_dif_miss_by_features(self) -> None: debug_id = "dfb8e43a-f242-3d73-a453-aeb6a777ef75" self.create_dif_file(debug_id=debug_id, features=[]) difs = ProjectDebugFile.objects.find_by_debug_ids( project=self.project, debug_ids=[debug_id], features=["debug"] ) assert debug_id not in difs def test_find_missing(self) -> None: dif = self.create_dif_file(debug_id="dfb8e43a-f242-3d73-a453-aeb6a777ef75-feedface") ret = ProjectDebugFile.objects.find_missing([dif.checksum, "a" * 40], self.project) assert ret == ["a" * 40] def test_file_extension_dartsymbolmap(self) -> None: """Test that dartsymbolmap files return .json file extension.""" # Create a file with dartsymbolmap content type file = File.objects.create( name="dartsymbolmap", type="project.dif", headers={"Content-Type": "application/x-dartsymbolmap+json"}, ) # Create a ProjectDebugFile dif = ProjectDebugFile.objects.create( file=file, checksum="test-checksum", object_name="dartsymbolmap", cpu_name="any", project_id=self.project.id, debug_id="b8e43a-f242-3d73-a453-aeb6a777ef75", data={"features": ["mapping"]}, ) # Verify that file_extension returns .json assert dif.file_extension == ".json" def test_file_extension_macho_dbg(self) -> None: """Test that macho files return empty file extension.""" file = File.objects.create( name="foo", type="project.dif", headers={"Content-Type": "application/x-mach-binary"}, ) dif = ProjectDebugFile.objects.create( file=file, checksum="test-checksum", object_name="foo", cpu_name="x86_64", project_id=self.project.id, debug_id="b8e43a-f242-3d73-a453-aeb6a777ef75", data={"type": "dbg"}, ) assert dif.file_extension == ".debug" def test_file_extension_macho_exe(self) -> None: file = File.objects.create( name="foo", type="project.dif", headers={"Content-Type": "application/x-mach-binary"}, ) dif = ProjectDebugFile.objects.create( file=file, checksum="test-checksum", object_name="foo", cpu_name="x86_64", project_id=self.project.id, debug_id="b8e43a-f242-3d73-a453-aeb6a777ef75", data={"type": "exe"}, ) assert dif.file_extension == "" def test_file_extension_macho_lib(self) -> None: file = File.objects.create( name="foo", type="project.dif", headers={"Content-Type": "application/x-mach-binary"}, ) dif = ProjectDebugFile.objects.create( file=file, checksum="test-checksum", object_name="foo", cpu_name="x86_64", project_id=self.project.id, debug_id="b8e43a-f242-3d73-a453-aeb6a777ef75", data={"type": "lib"}, ) assert dif.file_extension == ""
DebugFileTest
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 2360, "end": 2840 }
class ____(AutoEnum): """Enumeration of state types.""" SCHEDULED = AutoEnum.auto() PENDING = AutoEnum.auto() RUNNING = AutoEnum.auto() COMPLETED = AutoEnum.auto() FAILED = AutoEnum.auto() CANCELLED = AutoEnum.auto() CRASHED = AutoEnum.auto() PAUSED = AutoEnum.auto() CANCELLING = AutoEnum.auto() TERMINAL_STATES: set[StateType] = { StateType.COMPLETED, StateType.CANCELLED, StateType.FAILED, StateType.CRASHED, }
StateType
python
pola-rs__polars
py-polars/src/polars/expr/expr.py
{ "start": 3794, "end": 379253 }
class ____: """Expressions that can be used in various contexts.""" # NOTE: This `= None` is needed to generate the docs with sphinx_accessor. _pyexpr: PyExpr = None # type: ignore[assignment] _accessors: ClassVar[set[str]] = { "arr", "bin", "cat", "dt", "ext", "list", "meta", "name", "str", "struct", } @classmethod def _from_pyexpr(cls, pyexpr: PyExpr) -> Expr: expr = cls.__new__(cls) expr._pyexpr = pyexpr return expr def _repr_html_(self) -> str: return self._pyexpr.to_str() def __repr__(self) -> str: if len(expr_str := self._pyexpr.to_str()) > 30: expr_str = f"{expr_str[:30]}…" return f"<{self.__class__.__name__} [{expr_str!r}] at 0x{id(self):X}>" def __str__(self) -> str: return self._pyexpr.to_str() def __bool__(self) -> NoReturn: msg = ( "the truth value of an Expr 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 `pl.col('a') and pl.col('b')`, use `pl.col('a') & pl.col('b')`\n" "- instead of `pl.col('a') in [y, z]`, use `pl.col('a').is_in([y, z])`\n" "- instead of `max(pl.col('a'), pl.col('b'))`, use `pl.max_horizontal(pl.col('a'), pl.col('b'))`\n" ) raise TypeError(msg) def __abs__(self) -> Expr: return self.abs() # operators def __add__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr + other_pyexpr) def __radd__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(other_pyexpr + self._pyexpr) def __and__(self, other: IntoExprColumn | int | bool) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr.and_(other_pyexpr)) def __rand__(self, other: IntoExprColumn | int | bool) -> Expr: other_expr = parse_into_expression(other) return wrap_expr(other_expr.and_(self._pyexpr)) def __eq__(self, other: IntoExpr) -> Expr: # type: ignore[override] warn_null_comparison(other) other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.eq(other_pyexpr)) def __floordiv__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr // other_pyexpr) def __rfloordiv__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(other_pyexpr // self._pyexpr) def __ge__(self, other: IntoExpr) -> Expr: warn_null_comparison(other) other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.gt_eq(other_pyexpr)) def __gt__(self, other: IntoExpr) -> Expr: warn_null_comparison(other) other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.gt(other_pyexpr)) def __invert__(self) -> Expr: return self.not_() def __le__(self, other: IntoExpr) -> Expr: warn_null_comparison(other) other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.lt_eq(other_pyexpr)) def __lt__(self, other: IntoExpr) -> Expr: warn_null_comparison(other) other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.lt(other_pyexpr)) def __mod__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr % other_pyexpr) def __rmod__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(other_pyexpr % self._pyexpr) def __mul__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr * other_pyexpr) def __rmul__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(other_pyexpr * self._pyexpr) def __ne__(self, other: IntoExpr) -> Expr: # type: ignore[override] warn_null_comparison(other) other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.neq(other_pyexpr)) def __neg__(self) -> Expr: return wrap_expr(-self._pyexpr) def __or__(self, other: IntoExprColumn | int | bool) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr.or_(other_pyexpr)) def __ror__(self, other: IntoExprColumn | int | bool) -> Expr: other_expr = parse_into_expression(other) return wrap_expr(other_expr.or_(self._pyexpr)) def __pos__(self) -> Expr: return self def __pow__(self, exponent: IntoExprColumn | int | float) -> Expr: exponent_pyexpr = parse_into_expression(exponent) return wrap_expr(self._pyexpr.pow(exponent_pyexpr)) def __rpow__(self, base: IntoExprColumn | int | float) -> Expr: base_pyexpr = parse_into_expression(base) return wrap_expr(base_pyexpr) ** self def __sub__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr - other_pyexpr) def __rsub__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(other_pyexpr - self._pyexpr) def __truediv__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr / other_pyexpr) def __rtruediv__(self, other: IntoExpr) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(other_pyexpr / self._pyexpr) def __xor__(self, other: IntoExprColumn | int | bool) -> Expr: other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr.xor_(other_pyexpr)) def __rxor__(self, other: IntoExprColumn | int | bool) -> Expr: other_expr = parse_into_expression(other) return wrap_expr(other_expr.xor_(self._pyexpr)) def __getstate__(self) -> bytes: return self._pyexpr.__getstate__() def __setstate__(self, state: bytes) -> None: self._pyexpr = F.lit(0)._pyexpr # Initialize with a dummy self._pyexpr.__setstate__(state) def __array_ufunc__( self, ufunc: Callable[..., Any], method: str, *inputs: Any, **kwargs: Any ) -> Expr: """Numpy universal functions.""" if method != "__call__": msg = f"Only call is implemented not {method}" raise NotImplementedError(msg) # Numpy/Scipy ufuncs have signature None but numba signatures always exists. is_custom_ufunc = getattr(ufunc, "signature") is not None # noqa: B009 if is_custom_ufunc is True: msg = ( "Native numpy ufuncs are dispatched using `map_batches(ufunc, is_elementwise=True)` which " "is safe for native Numpy and Scipy ufuncs but custom ufuncs in a group_by " "context won't be properly grouped. Custom ufuncs are dispatched with is_elementwise=False. " f"If {ufunc.__name__} needs elementwise then please use map_batches directly." ) warnings.warn( msg, CustomUFuncWarning, stacklevel=find_stacklevel(), ) if len(inputs) == 1 and len(kwargs) == 0: # if there is only 1 input then it must be an Expr for this func to # have been called. If there are no kwargs then call map_batches # directly on the ufunc if not isinstance(inputs[0], Expr): msg = "Input must be expression." raise OutOfBoundsError(msg) return inputs[0].map_batches(ufunc, is_elementwise=not is_custom_ufunc) num_expr = sum(isinstance(inp, Expr) for inp in inputs) exprs = [ (inp, True, i) if isinstance(inp, Expr) else (inp, False, i) for i, inp in enumerate(inputs) ] if num_expr == 1: root_expr = next(expr[0] for expr in exprs if expr[1]) else: # We rename all but the first expression in case someone did e.g. # np.divide(pl.col("a"), pl.col("a")); we'll be creating a struct # below, and structs can't have duplicate names. first_renameable_expr = True actual_exprs = [] for inp, is_actual_expr, index in exprs: if is_actual_expr: if first_renameable_expr: first_renameable_expr = False else: inp = inp.alias(f"argument_{index}") actual_exprs.append(inp) root_expr = F.struct(actual_exprs) def function(s: Series) -> Series: # pragma: no cover args: list[Any] = [] for i, expr in enumerate(exprs): if expr[1] and num_expr > 1: args.append(s.struct[i]) elif expr[1]: args.append(s) else: args.append(expr[0]) return ufunc(*args, **kwargs) return root_expr.map_batches(function, is_elementwise=not is_custom_ufunc) @classmethod def deserialize( cls, source: str | Path | IOBase | bytes, *, format: SerializationFormat = "binary", ) -> Expr: """ Read a serialized expression from a file. Parameters ---------- source Path to a file or a file-like object (by file-like object, we refer to objects that have a `read()` method, such as a file handler (e.g. via builtin `open` function) or `BytesIO`). format The format with which the Expr was serialized. Options: - `"binary"`: Deserialize from binary format (bytes). This is the default. - `"json"`: Deserialize from JSON format (string). Warnings -------- This function uses :mod:`pickle` if the logical plan contains Python UDFs, and as such inherits the security implications. Deserializing can execute arbitrary code, so it should only be attempted on trusted data. See Also -------- Expr.meta.serialize Notes ----- Serialization is not stable across Polars versions: a LazyFrame serialized in one Polars version may not be deserializable in another Polars version. Examples -------- >>> import io >>> expr = pl.col("foo").sum().over("bar") >>> bytes = expr.meta.serialize() >>> pl.Expr.deserialize(io.BytesIO(bytes)) <Expr ['col("foo").sum().over([col("ba…'] at ...> """ if isinstance(source, StringIO): source = BytesIO(source.getvalue().encode()) elif isinstance(source, (str, Path)): source = normalize_filepath(source) elif isinstance(source, bytes): source = BytesIO(source) if format == "binary": deserializer = PyExpr.deserialize_binary elif format == "json": deserializer = PyExpr.deserialize_json else: msg = f"`format` must be one of {{'binary', 'json'}}, got {format!r}" raise ValueError(msg) return cls._from_pyexpr(deserializer(source)) def to_physical(self) -> Expr: """ Cast to physical representation of the logical dtype. - :func:`polars.datatypes.Date` -> :func:`polars.datatypes.Int32` - :func:`polars.datatypes.Datetime` -> :func:`polars.datatypes.Int64` - :func:`polars.datatypes.Time` -> :func:`polars.datatypes.Int64` - :func:`polars.datatypes.Duration` -> :func:`polars.datatypes.Int64` - :func:`polars.datatypes.Categorical` -> :func:`polars.datatypes.UInt32` - `List(inner)` -> `List(physical of inner)` - `Array(inner)` -> `Struct(physical of inner)` - `Struct(fields)` -> `Array(physical of fields)` Other data types will be left unchanged. Warnings -------- The physical representations are an implementation detail and not guaranteed to be stable. Examples -------- Replicating the pandas `pd.factorize <https://pandas.pydata.org/docs/reference/api/pandas.factorize.html>`_ function. >>> pl.DataFrame({"vals": ["a", "x", None, "a"]}).with_columns( ... pl.col("vals").cast(pl.Categorical), ... pl.col("vals") ... .cast(pl.Categorical) ... .to_physical() ... .alias("vals_physical"), ... ) shape: (4, 2) ┌──────┬───────────────┐ │ vals ┆ vals_physical │ │ --- ┆ --- │ │ cat ┆ u32 │ ╞══════╪═══════════════╡ │ a ┆ 0 │ │ x ┆ 1 │ │ null ┆ null │ │ a ┆ 0 │ └──────┴───────────────┘ """ return wrap_expr(self._pyexpr.to_physical()) def any(self, *, ignore_nulls: bool = True) -> Expr: """ Return whether any of the values in the column are `True`. Only works on columns of data type :class:`Boolean`. Parameters ---------- ignore_nulls * If set to `True` (default), null values are ignored. If there are no non-null values, the output is `False`. * If set to `False`, `Kleene logic`_ is used to deal with nulls: if the column contains any null values and no `True` values, the output is null. .. _Kleene logic: https://en.wikipedia.org/wiki/Three-valued_logic Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [True, False], ... "b": [False, False], ... "c": [None, False], ... } ... ) >>> df.select(pl.col("*").any()) shape: (1, 3) ┌──────┬───────┬───────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ bool ┆ bool ┆ bool │ ╞══════╪═══════╪═══════╡ │ true ┆ false ┆ false │ └──────┴───────┴───────┘ Enable Kleene logic by setting `ignore_nulls=False`. >>> df.select(pl.col("*").any(ignore_nulls=False)) shape: (1, 3) ┌──────┬───────┬──────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ bool ┆ bool ┆ bool │ ╞══════╪═══════╪══════╡ │ true ┆ false ┆ null │ └──────┴───────┴──────┘ """ return wrap_expr(self._pyexpr.any(ignore_nulls)) def all(self, *, ignore_nulls: bool = True) -> Expr: """ Return whether all values in the column are `True`. Only works on columns of data type :class:`Boolean`. .. note:: This method is not to be confused with the function :func:`polars.all`, which can be used to select all columns. Parameters ---------- ignore_nulls * If set to `True` (default), null values are ignored. If there are no non-null values, the output is `True`. * If set to `False`, `Kleene logic`_ is used to deal with nulls: if the column contains any null values and no `False` values, the output is null. .. _Kleene logic: https://en.wikipedia.org/wiki/Three-valued_logic Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [True, True], ... "b": [False, True], ... "c": [None, True], ... } ... ) >>> df.select(pl.col("*").all()) shape: (1, 3) ┌──────┬───────┬──────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ bool ┆ bool ┆ bool │ ╞══════╪═══════╪══════╡ │ true ┆ false ┆ true │ └──────┴───────┴──────┘ Enable Kleene logic by setting `ignore_nulls=False`. >>> df.select(pl.col("*").all(ignore_nulls=False)) shape: (1, 3) ┌──────┬───────┬──────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ bool ┆ bool ┆ bool │ ╞══════╪═══════╪══════╡ │ true ┆ false ┆ null │ └──────┴───────┴──────┘ """ return wrap_expr(self._pyexpr.all(ignore_nulls)) def arg_true(self) -> Expr: """ Return indices where expression evaluates `True`. .. warning:: Modifies number of rows returned, so will fail in combination with other expressions. Use as only expression in `select` / `with_columns`. See Also -------- Series.arg_true : Return indices where Series is True polars.arg_where Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2, 1]}) >>> df.select((pl.col("a") == 1).arg_true()) shape: (3, 1) ┌─────┐ │ a │ │ --- │ │ u32 │ ╞═════╡ │ 0 │ │ 1 │ │ 3 │ └─────┘ """ return wrap_expr(py_arg_where(self._pyexpr)) def sqrt(self) -> Expr: """ Compute the square root of the elements. Examples -------- >>> df = pl.DataFrame({"values": [1.0, 2.0, 4.0]}) >>> df.select(pl.col("values").sqrt()) shape: (3, 1) ┌──────────┐ │ values │ │ --- │ │ f64 │ ╞══════════╡ │ 1.0 │ │ 1.414214 │ │ 2.0 │ └──────────┘ """ return wrap_expr(self._pyexpr.sqrt()) def cbrt(self) -> Expr: """ Compute the cube root of the elements. Examples -------- >>> df = pl.DataFrame({"values": [1.0, 2.0, 4.0]}) >>> df.select(pl.col("values").cbrt()) shape: (3, 1) ┌──────────┐ │ values │ │ --- │ │ f64 │ ╞══════════╡ │ 1.0 │ │ 1.259921 │ │ 1.587401 │ └──────────┘ """ return wrap_expr(self._pyexpr.cbrt()) def log10(self) -> Expr: """ Compute the base 10 logarithm of the input array, element-wise. Examples -------- >>> df = pl.DataFrame({"values": [1.0, 2.0, 4.0]}) >>> df.select(pl.col("values").log10()) shape: (3, 1) ┌─────────┐ │ values │ │ --- │ │ f64 │ ╞═════════╡ │ 0.0 │ │ 0.30103 │ │ 0.60206 │ └─────────┘ """ return self.log(10.0) def exp(self) -> Expr: """ Compute the exponential, element-wise. Examples -------- >>> df = pl.DataFrame({"values": [1.0, 2.0, 4.0]}) >>> df.select(pl.col("values").exp()) shape: (3, 1) ┌──────────┐ │ values │ │ --- │ │ f64 │ ╞══════════╡ │ 2.718282 │ │ 7.389056 │ │ 54.59815 │ └──────────┘ """ return wrap_expr(self._pyexpr.exp()) def alias(self, name: str) -> Expr: """ Rename the expression. Parameters ---------- name The new name. See Also -------- name.map name.prefix name.suffix Examples -------- Rename an expression to avoid overwriting an existing column. >>> df = pl.DataFrame( ... { ... "a": [1, 2, 3], ... "b": ["x", "y", "z"], ... } ... ) >>> df.with_columns( ... pl.col("a") + 10, ... pl.col("b").str.to_uppercase().alias("c"), ... ) shape: (3, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ str │ ╞═════╪═════╪═════╡ │ 11 ┆ x ┆ X │ │ 12 ┆ y ┆ Y │ │ 13 ┆ z ┆ Z │ └─────┴─────┴─────┘ Overwrite the default name of literal columns to prevent errors due to duplicate column names. >>> df.with_columns( ... pl.lit(True).alias("c"), ... pl.lit(4.0).alias("d"), ... ) shape: (3, 4) ┌─────┬─────┬──────┬─────┐ │ a ┆ b ┆ c ┆ d │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ bool ┆ f64 │ ╞═════╪═════╪══════╪═════╡ │ 1 ┆ x ┆ true ┆ 4.0 │ │ 2 ┆ y ┆ true ┆ 4.0 │ │ 3 ┆ z ┆ true ┆ 4.0 │ └─────┴─────┴──────┴─────┘ """ return wrap_expr(self._pyexpr.alias(name)) def exclude( self, columns: str | PolarsDataType | Collection[str] | Collection[PolarsDataType], *more_columns: str | PolarsDataType, ) -> Expr: """ Exclude columns from a multi-column expression. Only works after a wildcard or regex column selection, and you cannot provide both string column names *and* dtypes (you may prefer to use selectors instead). Parameters ---------- columns The name or datatype of the column(s) to exclude. Accepts regular expression input. Regular expressions should start with `^` and end with `$`. *more_columns Additional names or datatypes of columns to exclude, specified as positional arguments. Examples -------- >>> df = pl.DataFrame( ... { ... "aa": [1, 2, 3], ... "ba": ["a", "b", None], ... "cc": [None, 2.5, 1.5], ... } ... ) >>> df shape: (3, 3) ┌─────┬──────┬──────┐ │ aa ┆ ba ┆ cc │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ f64 │ ╞═════╪══════╪══════╡ │ 1 ┆ a ┆ null │ │ 2 ┆ b ┆ 2.5 │ │ 3 ┆ null ┆ 1.5 │ └─────┴──────┴──────┘ Exclude by column name(s): >>> df.select(pl.all().exclude("ba")) shape: (3, 2) ┌─────┬──────┐ │ aa ┆ cc │ │ --- ┆ --- │ │ i64 ┆ f64 │ ╞═════╪══════╡ │ 1 ┆ null │ │ 2 ┆ 2.5 │ │ 3 ┆ 1.5 │ └─────┴──────┘ Exclude by regex, e.g. removing all columns whose names end with the letter "a": >>> df.select(pl.all().exclude("^.*a$")) shape: (3, 1) ┌──────┐ │ cc │ │ --- │ │ f64 │ ╞══════╡ │ null │ │ 2.5 │ │ 1.5 │ └──────┘ Exclude by dtype(s), e.g. removing all columns of type Int64 or Float64: >>> df.select(pl.all().exclude([pl.Int64, pl.Float64])) shape: (3, 1) ┌──────┐ │ ba │ │ --- │ │ str │ ╞══════╡ │ a │ │ b │ │ null │ └──────┘ """ return self.meta.as_selector().exclude(columns, *more_columns).as_expr() def pipe( self, function: Callable[Concatenate[Expr, P], T], *args: P.args, **kwargs: P.kwargs, ) -> T: r''' Offers a structured way to apply a sequence of user-defined functions (UDFs). Parameters ---------- function Callable; will receive the expression as the first parameter, followed by any given args/kwargs. *args Arguments to pass to the UDF. **kwargs Keyword arguments to pass to the UDF. Examples -------- >>> def extract_number(expr: pl.Expr) -> pl.Expr: ... """Extract the digits from a string.""" ... return expr.str.extract(r"\d+", 0).cast(pl.Int64) >>> >>> def scale_negative_even(expr: pl.Expr, *, n: int = 1) -> pl.Expr: ... """Set even numbers negative, and scale by a user-supplied value.""" ... expr = pl.when(expr % 2 == 0).then(-expr).otherwise(expr) ... return expr * n >>> >>> df = pl.DataFrame({"val": ["a: 1", "b: 2", "c: 3", "d: 4"]}) >>> df.with_columns( ... udfs=( ... pl.col("val").pipe(extract_number).pipe(scale_negative_even, n=5) ... ), ... ) shape: (4, 2) ┌──────┬──────┐ │ val ┆ udfs │ │ --- ┆ --- │ │ str ┆ i64 │ ╞══════╪══════╡ │ a: 1 ┆ 5 │ │ b: 2 ┆ -10 │ │ c: 3 ┆ 15 │ │ d: 4 ┆ -20 │ └──────┴──────┘ ''' return function(self, *args, **kwargs) def not_(self) -> Expr: """ Method equivalent of bitwise "not" operator `~expr`. This has the effect of negating logical boolean expressions, but operates bitwise on integers. Examples -------- >>> df = pl.DataFrame( ... { ... "label": ["aa", "bb", "cc", "dd", "ee"], ... "valid": [True, False, None, False, True], ... "int_code": [1, 0, 2, None, -1], ... } ... ) Apply "not" to boolean expression (negates the value) and integer expression (operates bitwise): >>> df.with_columns( ... not_valid=pl.col("valid").not_(), ... not_int_code=pl.col("int_code").not_(), ... ) shape: (5, 5) ┌───────┬───────┬──────────┬───────────┬──────────────┐ │ label ┆ valid ┆ int_code ┆ not_valid ┆ not_int_code │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ bool ┆ i64 ┆ bool ┆ i64 │ ╞═══════╪═══════╪══════════╪═══════════╪══════════════╡ │ aa ┆ true ┆ 1 ┆ false ┆ -2 │ │ bb ┆ false ┆ 0 ┆ true ┆ -1 │ │ cc ┆ null ┆ 2 ┆ null ┆ -3 │ │ dd ┆ false ┆ null ┆ true ┆ null │ │ ee ┆ true ┆ -1 ┆ false ┆ 0 │ └───────┴───────┴──────────┴───────────┴──────────────┘ """ return wrap_expr(self._pyexpr.not_()) def is_null(self) -> Expr: """ Returns a boolean Series indicating which values are null. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, None, 1, 5], ... "b": [1.0, 2.0, float("nan"), 1.0, 5.0], ... } ... ) >>> df.with_columns(pl.all().is_null().name.suffix("_isnull")) # nan != null shape: (5, 4) ┌──────┬─────┬──────────┬──────────┐ │ a ┆ b ┆ a_isnull ┆ b_isnull │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ bool ┆ bool │ ╞══════╪═════╪══════════╪══════════╡ │ 1 ┆ 1.0 ┆ false ┆ false │ │ 2 ┆ 2.0 ┆ false ┆ false │ │ null ┆ NaN ┆ true ┆ false │ │ 1 ┆ 1.0 ┆ false ┆ false │ │ 5 ┆ 5.0 ┆ false ┆ false │ └──────┴─────┴──────────┴──────────┘ """ return wrap_expr(self._pyexpr.is_null()) def is_not_null(self) -> Expr: """ Returns a boolean Series indicating which values are not null. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, None, 1, 5], ... "b": [1.0, 2.0, float("nan"), 1.0, 5.0], ... } ... ) >>> df.with_columns( ... pl.all().is_not_null().name.suffix("_not_null") # nan != null ... ) shape: (5, 4) ┌──────┬─────┬────────────┬────────────┐ │ a ┆ b ┆ a_not_null ┆ b_not_null │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ bool ┆ bool │ ╞══════╪═════╪════════════╪════════════╡ │ 1 ┆ 1.0 ┆ true ┆ true │ │ 2 ┆ 2.0 ┆ true ┆ true │ │ null ┆ NaN ┆ false ┆ true │ │ 1 ┆ 1.0 ┆ true ┆ true │ │ 5 ┆ 5.0 ┆ true ┆ true │ └──────┴─────┴────────────┴────────────┘ """ return wrap_expr(self._pyexpr.is_not_null()) def is_finite(self) -> Expr: """ Returns a boolean Series indicating which values are finite. Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame( ... { ... "A": [1.0, 2], ... "B": [3.0, float("inf")], ... } ... ) >>> df.select(pl.all().is_finite()) shape: (2, 2) ┌──────┬───────┐ │ A ┆ B │ │ --- ┆ --- │ │ bool ┆ bool │ ╞══════╪═══════╡ │ true ┆ true │ │ true ┆ false │ └──────┴───────┘ """ return wrap_expr(self._pyexpr.is_finite()) def is_infinite(self) -> Expr: """ Returns a boolean Series indicating which values are infinite. Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame( ... { ... "A": [1.0, 2], ... "B": [3.0, float("inf")], ... } ... ) >>> df.select(pl.all().is_infinite()) shape: (2, 2) ┌───────┬───────┐ │ A ┆ B │ │ --- ┆ --- │ │ bool ┆ bool │ ╞═══════╪═══════╡ │ false ┆ false │ │ false ┆ true │ └───────┴───────┘ """ return wrap_expr(self._pyexpr.is_infinite()) def is_nan(self) -> Expr: """ Returns a boolean Series indicating which values are NaN. Notes ----- Floating point `NaN` (Not A Number) should not be confused with missing data represented as `Null/None`. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, None, 1, 5], ... "b": [1.0, 2.0, float("nan"), 1.0, 5.0], ... } ... ) >>> df.with_columns(pl.col(pl.Float64).is_nan().name.suffix("_isnan")) shape: (5, 3) ┌──────┬─────┬─────────┐ │ a ┆ b ┆ b_isnan │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ bool │ ╞══════╪═════╪═════════╡ │ 1 ┆ 1.0 ┆ false │ │ 2 ┆ 2.0 ┆ false │ │ null ┆ NaN ┆ true │ │ 1 ┆ 1.0 ┆ false │ │ 5 ┆ 5.0 ┆ false │ └──────┴─────┴─────────┘ """ return wrap_expr(self._pyexpr.is_nan()) def is_not_nan(self) -> Expr: """ Returns a boolean Series indicating which values are not NaN. Notes ----- Floating point `NaN` (Not A Number) should not be confused with missing data represented as `Null/None`. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, None, 1, 5], ... "b": [1.0, 2.0, float("nan"), 1.0, 5.0], ... } ... ) >>> df.with_columns(pl.col(pl.Float64).is_not_nan().name.suffix("_is_not_nan")) shape: (5, 3) ┌──────┬─────┬──────────────┐ │ a ┆ b ┆ b_is_not_nan │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ bool │ ╞══════╪═════╪══════════════╡ │ 1 ┆ 1.0 ┆ true │ │ 2 ┆ 2.0 ┆ true │ │ null ┆ NaN ┆ false │ │ 1 ┆ 1.0 ┆ true │ │ 5 ┆ 5.0 ┆ true │ └──────┴─────┴──────────────┘ """ return wrap_expr(self._pyexpr.is_not_nan()) def agg_groups(self) -> Expr: """ Get the group indexes of the group by operation. .. deprecated:: 1.35 use `df.with_row_index().group_by(...).agg(pl.col('index'))` instead. This method will be removed in Polars 2.0. Should be used in aggregation context only. Examples -------- >>> import warnings >>> warnings.filterwarnings("ignore", category=DeprecationWarning) >>> df = pl.DataFrame( ... { ... "group": [ ... "one", ... "one", ... "one", ... "two", ... "two", ... "two", ... ], ... "value": [94, 95, 96, 97, 97, 99], ... } ... ) >>> df.group_by("group", maintain_order=True).agg(pl.col("value").agg_groups()) shape: (2, 2) ┌───────┬───────────┐ │ group ┆ value │ │ --- ┆ --- │ │ str ┆ list[u32] │ ╞═══════╪═══════════╡ │ one ┆ [0, 1, 2] │ │ two ┆ [3, 4, 5] │ └───────┴───────────┘ New recommended approach: >>> ( ... df.with_row_index() ... .group_by("group", maintain_order=True) ... .agg(pl.col("index")) ... ) shape: (2, 2) ┌───────┬───────────┐ │ group ┆ index │ │ --- ┆ --- │ │ str ┆ list[u32] │ ╞═══════╪═══════════╡ │ one ┆ [0, 1, 2] │ │ two ┆ [3, 4, 5] │ └───────┴───────────┘ """ warnings.warn( "agg_groups() is deprecated and will be removed in Polars 2.0. " "Use df.with_row_index().group_by(...).agg(pl.col('index')) instead.", DeprecationWarning, stacklevel=2, ) return wrap_expr(self._pyexpr.agg_groups()) def count(self) -> Expr: """ Return the number of non-null elements in the column. Returns ------- Expr Expression of data type :class:`UInt32`. See Also -------- len Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3], "b": [None, 4, 4]}) >>> df.select(pl.all().count()) shape: (1, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ u32 ┆ u32 │ ╞═════╪═════╡ │ 3 ┆ 2 │ └─────┴─────┘ """ return wrap_expr(self._pyexpr.count()) def len(self) -> Expr: """ Return the number of elements in the column. Null values count towards the total. Returns ------- Expr Expression of data type :class:`UInt32`. See Also -------- count Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3], "b": [None, 4, 4]}) >>> df.select(pl.all().len()) shape: (1, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ u32 ┆ u32 │ ╞═════╪═════╡ │ 3 ┆ 3 │ └─────┴─────┘ """ return wrap_expr(self._pyexpr.len()) def slice(self, offset: int | Expr, length: int | Expr | None = None) -> Expr: """ Get a slice of this expression. Parameters ---------- offset Start index. Negative indexing is supported. length Length of the slice. If set to `None`, all rows starting at the offset will be selected. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [8, 9, 10, 11], ... "b": [None, 4, 4, 4], ... } ... ) >>> df.select(pl.all().slice(1, 2)) shape: (2, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 9 ┆ 4 │ │ 10 ┆ 4 │ └─────┴─────┘ """ if not isinstance(offset, Expr): offset = F.lit(offset) if not isinstance(length, Expr): length = F.lit(length) return wrap_expr(self._pyexpr.slice(offset._pyexpr, length._pyexpr)) def append(self, other: IntoExpr, *, upcast: bool = True) -> Expr: """ Append expressions. This is done by adding the chunks of `other` to this `Series`. Parameters ---------- other Expression to append. upcast Cast both `Series` to the same supertype. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [8, 9, 10], ... "b": [None, 4, 4], ... } ... ) >>> df.select(pl.all().head(1).append(pl.all().tail(1))) shape: (2, 2) ┌─────┬──────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════╡ │ 8 ┆ null │ │ 10 ┆ 4 │ └─────┴──────┘ """ other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr.append(other_pyexpr, upcast)) def rechunk(self) -> Expr: """ Create a single chunk of memory for this Series. Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2]}) Create a Series with 3 nulls, append column `a`, then rechunk. >>> df.select(pl.repeat(None, 3).append(pl.col("a")).rechunk()) shape: (6, 1) ┌────────┐ │ repeat │ │ --- │ │ i64 │ ╞════════╡ │ null │ │ null │ │ null │ │ 1 │ │ 1 │ │ 2 │ └────────┘ """ return wrap_expr(self._pyexpr.rechunk()) def drop_nulls(self) -> Expr: """ Drop all null values. The original order of the remaining elements is preserved. See Also -------- drop_nans Notes ----- A null value is not the same as a NaN value. To drop NaN values, use :func:`drop_nans`. Examples -------- >>> df = pl.DataFrame({"a": [1.0, None, 3.0, float("nan")]}) >>> df.select(pl.col("a").drop_nulls()) shape: (3, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ │ 3.0 │ │ NaN │ └─────┘ """ return wrap_expr(self._pyexpr.drop_nulls()) def drop_nans(self) -> Expr: """ Drop all floating point NaN values. The original order of the remaining elements is preserved. See Also -------- drop_nulls Notes ----- A NaN value is not the same as a null value. To drop null values, use :func:`drop_nulls`. Examples -------- >>> df = pl.DataFrame({"a": [1.0, None, 3.0, float("nan")]}) >>> df.select(pl.col("a").drop_nans()) shape: (3, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ 1.0 │ │ null │ │ 3.0 │ └──────┘ """ return wrap_expr(self._pyexpr.drop_nans()) def cum_sum(self, *, reverse: bool = False) -> Expr: """ Get an array with the cumulative sum computed at every element. Parameters ---------- reverse Reverse the operation. Notes ----- Dtypes in {Int8, UInt8, Int16, UInt16} are cast to Int64 before summing to prevent overflow issues. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3, 4]}) >>> df.with_columns( ... pl.col("a").cum_sum().alias("cum_sum"), ... pl.col("a").cum_sum(reverse=True).alias("cum_sum_reverse"), ... ) shape: (4, 3) ┌─────┬─────────┬─────────────────┐ │ a ┆ cum_sum ┆ cum_sum_reverse │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════════╪═════════════════╡ │ 1 ┆ 1 ┆ 10 │ │ 2 ┆ 3 ┆ 9 │ │ 3 ┆ 6 ┆ 7 │ │ 4 ┆ 10 ┆ 4 │ └─────┴─────────┴─────────────────┘ Null values are excluded, but can also be filled by calling `fill_null(strategy="forward")`. >>> df = pl.DataFrame({"values": [None, 10, None, 8, 9, None, 16, None]}) >>> df.with_columns( ... pl.col("values").cum_sum().alias("value_cum_sum"), ... pl.col("values") ... .cum_sum() ... .fill_null(strategy="forward") ... .alias("value_cum_sum_all_filled"), ... ) shape: (8, 3) ┌────────┬───────────────┬──────────────────────────┐ │ values ┆ value_cum_sum ┆ value_cum_sum_all_filled │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞════════╪═══════════════╪══════════════════════════╡ │ null ┆ null ┆ null │ │ 10 ┆ 10 ┆ 10 │ │ null ┆ null ┆ 10 │ │ 8 ┆ 18 ┆ 18 │ │ 9 ┆ 27 ┆ 27 │ │ null ┆ null ┆ 27 │ │ 16 ┆ 43 ┆ 43 │ │ null ┆ null ┆ 43 │ └────────┴───────────────┴──────────────────────────┘ """ return wrap_expr(self._pyexpr.cum_sum(reverse)) def cum_prod(self, *, reverse: bool = False) -> Expr: """ Get an array with the cumulative product computed at every element. Parameters ---------- reverse Reverse the operation. Notes ----- Dtypes in {Int8, UInt8, Int16, UInt16} are cast to Int64 before summing to prevent overflow issues. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3, 4]}) >>> df.with_columns( ... pl.col("a").cum_prod().alias("cum_prod"), ... pl.col("a").cum_prod(reverse=True).alias("cum_prod_reverse"), ... ) shape: (4, 3) ┌─────┬──────────┬──────────────────┐ │ a ┆ cum_prod ┆ cum_prod_reverse │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪══════════╪══════════════════╡ │ 1 ┆ 1 ┆ 24 │ │ 2 ┆ 2 ┆ 24 │ │ 3 ┆ 6 ┆ 12 │ │ 4 ┆ 24 ┆ 4 │ └─────┴──────────┴──────────────────┘ """ return wrap_expr(self._pyexpr.cum_prod(reverse)) def cum_min(self, *, reverse: bool = False) -> Expr: """ Get an array with the cumulative min computed at every element. Parameters ---------- reverse Reverse the operation. Examples -------- >>> df = pl.DataFrame({"a": [3, 1, 2]}) >>> df.with_columns( ... pl.col("a").cum_min().alias("cum_min"), ... pl.col("a").cum_min(reverse=True).alias("cum_min_reverse"), ... ) shape: (3, 3) ┌─────┬─────────┬─────────────────┐ │ a ┆ cum_min ┆ cum_min_reverse │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════════╪═════════════════╡ │ 3 ┆ 3 ┆ 1 │ │ 1 ┆ 1 ┆ 1 │ │ 2 ┆ 1 ┆ 2 │ └─────┴─────────┴─────────────────┘ """ return wrap_expr(self._pyexpr.cum_min(reverse)) def cum_max(self, *, reverse: bool = False) -> Expr: """ Get an array with the cumulative max computed at every element. Parameters ---------- reverse Reverse the operation. Examples -------- >>> df = pl.DataFrame({"a": [1, 3, 2]}) >>> df.with_columns( ... pl.col("a").cum_max().alias("cum_max"), ... pl.col("a").cum_max(reverse=True).alias("cum_max_reverse"), ... ) shape: (3, 3) ┌─────┬─────────┬─────────────────┐ │ a ┆ cum_max ┆ cum_max_reverse │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════════╪═════════════════╡ │ 1 ┆ 1 ┆ 3 │ │ 3 ┆ 3 ┆ 3 │ │ 2 ┆ 3 ┆ 2 │ └─────┴─────────┴─────────────────┘ Null values are excluded, but can also be filled by calling `fill_null(strategy="forward")`. >>> df = pl.DataFrame({"values": [None, 10, None, 8, 9, None, 16, None]}) >>> df.with_columns( ... pl.col("values").cum_max().alias("cum_max"), ... pl.col("values") ... .cum_max() ... .fill_null(strategy="forward") ... .alias("cum_max_all_filled"), ... ) shape: (8, 3) ┌────────┬─────────┬────────────────────┐ │ values ┆ cum_max ┆ cum_max_all_filled │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞════════╪═════════╪════════════════════╡ │ null ┆ null ┆ null │ │ 10 ┆ 10 ┆ 10 │ │ null ┆ null ┆ 10 │ │ 8 ┆ 10 ┆ 10 │ │ 9 ┆ 10 ┆ 10 │ │ null ┆ null ┆ 10 │ │ 16 ┆ 16 ┆ 16 │ │ null ┆ null ┆ 16 │ └────────┴─────────┴────────────────────┘ """ return wrap_expr(self._pyexpr.cum_max(reverse)) def cum_count(self, *, reverse: bool = False) -> Expr: """ Return the cumulative count of the non-null values in the column. Parameters ---------- reverse Reverse the operation. Examples -------- >>> df = pl.DataFrame({"a": ["x", "k", None, "d"]}) >>> df.with_columns( ... pl.col("a").cum_count().alias("cum_count"), ... pl.col("a").cum_count(reverse=True).alias("cum_count_reverse"), ... ) shape: (4, 3) ┌──────┬───────────┬───────────────────┐ │ a ┆ cum_count ┆ cum_count_reverse │ │ --- ┆ --- ┆ --- │ │ str ┆ u32 ┆ u32 │ ╞══════╪═══════════╪═══════════════════╡ │ x ┆ 1 ┆ 3 │ │ k ┆ 2 ┆ 2 │ │ null ┆ 2 ┆ 1 │ │ d ┆ 3 ┆ 1 │ └──────┴───────────┴───────────────────┘ """ return wrap_expr(self._pyexpr.cum_count(reverse)) def floor(self) -> Expr: """ Rounds down to the nearest integer value. Only works on floating point Series. Examples -------- >>> df = pl.DataFrame({"a": [0.3, 0.5, 1.0, 1.1]}) >>> df.select(pl.col("a").floor()) shape: (4, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 0.0 │ │ 0.0 │ │ 1.0 │ │ 1.0 │ └─────┘ """ return wrap_expr(self._pyexpr.floor()) def ceil(self) -> Expr: """ Rounds up to the nearest integer value. Only works on floating point Series. Examples -------- >>> df = pl.DataFrame({"a": [0.3, 0.5, 1.0, 1.1]}) >>> df.select(pl.col("a").ceil()) shape: (4, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ │ 1.0 │ │ 1.0 │ │ 2.0 │ └─────┘ """ return wrap_expr(self._pyexpr.ceil()) def round(self, decimals: int = 0, mode: RoundMode = "half_to_even") -> Expr: """ Round underlying floating point data by `decimals` digits. The default rounding mode is "half to even" (also known as "bankers' rounding"). Parameters ---------- decimals Number of decimals to round by. mode : {'half_to_even', 'half_away_from_zero'} RoundMode. * *half_to_even* round to the nearest even number * *half_away_from_zero* round to the nearest number away from zero Examples -------- >>> df = pl.DataFrame({"a": [0.33, 0.52, 1.02, 1.17]}) >>> df.select(pl.col("a").round(1)) shape: (4, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 0.3 │ │ 0.5 │ │ 1.0 │ │ 1.2 │ └─────┘ >>> df = pl.DataFrame( ... { ... "f64": [-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5], ... "d": ["-3.5", "-2.5", "-1.5", "-0.5", "0.5", "1.5", "2.5", "3.5"], ... }, ... schema_overrides={"d": pl.Decimal(scale=1)}, ... ) >>> df.with_columns( ... pl.all().round(mode="half_away_from_zero").name.suffix("_away"), ... pl.all().round(mode="half_to_even").name.suffix("_to_even"), ... ) shape: (8, 6) ┌──────┬───────────────┬──────────┬───────────────┬─────────────┬───────────────┐ │ f64 ┆ d ┆ f64_away ┆ d_away ┆ f64_to_even ┆ d_to_even │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ f64 ┆ decimal[38,1] ┆ f64 ┆ decimal[38,1] ┆ f64 ┆ decimal[38,1] │ ╞══════╪═══════════════╪══════════╪═══════════════╪═════════════╪═══════════════╡ │ -3.5 ┆ -3.5 ┆ -4.0 ┆ -4.0 ┆ -4.0 ┆ -4.0 │ │ -2.5 ┆ -2.5 ┆ -3.0 ┆ -3.0 ┆ -2.0 ┆ -2.0 │ │ -1.5 ┆ -1.5 ┆ -2.0 ┆ -2.0 ┆ -2.0 ┆ -2.0 │ │ -0.5 ┆ -0.5 ┆ -1.0 ┆ -1.0 ┆ -0.0 ┆ 0.0 │ │ 0.5 ┆ 0.5 ┆ 1.0 ┆ 1.0 ┆ 0.0 ┆ 0.0 │ │ 1.5 ┆ 1.5 ┆ 2.0 ┆ 2.0 ┆ 2.0 ┆ 2.0 │ │ 2.5 ┆ 2.5 ┆ 3.0 ┆ 3.0 ┆ 2.0 ┆ 2.0 │ │ 3.5 ┆ 3.5 ┆ 4.0 ┆ 4.0 ┆ 4.0 ┆ 4.0 │ └──────┴───────────────┴──────────┴───────────────┴─────────────┴───────────────┘ """ # noqa: W505 return wrap_expr(self._pyexpr.round(decimals, mode)) def round_sig_figs(self, digits: int) -> Expr: """ Round to a number of significant figures. Parameters ---------- digits Number of significant figures to round to. Examples -------- >>> df = pl.DataFrame({"a": [0.01234, 3.333, 1234.0]}) >>> df.with_columns(pl.col("a").round_sig_figs(2).alias("round_sig_figs")) shape: (3, 2) ┌─────────┬────────────────┐ │ a ┆ round_sig_figs │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════════╪════════════════╡ │ 0.01234 ┆ 0.012 │ │ 3.333 ┆ 3.3 │ │ 1234.0 ┆ 1200.0 │ └─────────┴────────────────┘ """ return wrap_expr(self._pyexpr.round_sig_figs(digits)) def dot(self, other: Expr | str) -> Expr: """ Compute the dot/inner product between two Expressions. Parameters ---------- other Expression to compute dot product with. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 3, 5], ... "b": [2, 4, 6], ... } ... ) >>> df.select(pl.col("a").dot(pl.col("b"))) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 44 │ └─────┘ """ other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr.dot(other_pyexpr)) def mode(self, *, maintain_order: bool = False) -> Expr: """ Compute the most occurring value(s). Can return multiple Values. Parameters ---------- maintain_order Maintain order of data. This requires more work. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 1, 2, 3], ... "b": [1, 1, 2, 2], ... } ... ) >>> df.select(pl.all().mode().first()) # doctest: +IGNORE_RESULT shape: (2, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 1 │ └─────┴─────┘ """ return wrap_expr(self._pyexpr.mode(maintain_order=maintain_order)) def cast( self, dtype: PolarsDataType | pl.DataTypeExpr | type[Any], *, strict: bool = True, wrap_numerical: bool = False, ) -> Expr: r""" Cast between data types. Parameters ---------- dtype DataType to cast to. strict Raise if cast is invalid on rows after predicates are pushed down. If `False`, invalid casts will produce null values. wrap_numerical If True numeric casts wrap overflowing values instead of marking the cast as invalid. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, 3], ... "b": ["4", "5", "6"], ... } ... ) >>> df.with_columns( ... pl.col("a").cast(pl.Float64), ... pl.col("b").cast(pl.Int32), ... ) shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ i32 │ ╞═════╪═════╡ │ 1.0 ┆ 4 │ │ 2.0 ┆ 5 │ │ 3.0 ┆ 6 │ └─────┴─────┘ """ dtype = parse_into_datatype_expr(dtype) return wrap_expr( self._pyexpr.cast(dtype._pydatatype_expr, strict, wrap_numerical) ) def sort(self, *, descending: bool = False, nulls_last: bool = False) -> Expr: """ Sort this column. When used in a projection/selection context, the whole column is sorted. When used in a group by context, the groups are sorted. Parameters ---------- descending Sort in descending order. nulls_last Place null values last. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, None, 3, 2], ... } ... ) >>> df.select(pl.col("a").sort()) shape: (4, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ null │ │ 1 │ │ 2 │ │ 3 │ └──────┘ >>> df.select(pl.col("a").sort(descending=True)) shape: (4, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ null │ │ 3 │ │ 2 │ │ 1 │ └──────┘ >>> df.select(pl.col("a").sort(nulls_last=True)) shape: (4, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ 2 │ │ 3 │ │ null │ └──────┘ When sorting in a group by context, the groups are sorted. >>> df = pl.DataFrame( ... { ... "group": ["one", "one", "one", "two", "two", "two"], ... "value": [1, 98, 2, 3, 99, 4], ... } ... ) >>> df.group_by("group").agg(pl.col("value").sort()) # doctest: +IGNORE_RESULT shape: (2, 2) ┌───────┬────────────┐ │ group ┆ value │ │ --- ┆ --- │ │ str ┆ list[i64] │ ╞═══════╪════════════╡ │ two ┆ [3, 4, 99] │ │ one ┆ [1, 2, 98] │ └───────┴────────────┘ """ return wrap_expr(self._pyexpr.sort_with(descending, nulls_last)) def top_k(self, k: int | IntoExprColumn = 5) -> Expr: r""" Return the `k` largest elements. Non-null elements are always preferred over null elements. The output is not guaranteed to be in any particular order, call :func:`sort` after this function if you wish the output to be sorted. This has time complexity: .. math:: O(n) Parameters ---------- k Number of elements to return. See Also -------- top_k_by bottom_k bottom_k_by Examples -------- Get the 5 largest values in series. >>> df = pl.DataFrame({"value": [1, 98, 2, 3, 99, 4]}) >>> df.select( ... pl.col("value").top_k().alias("top_k"), ... pl.col("value").bottom_k().alias("bottom_k"), ... ) shape: (5, 2) ┌───────┬──────────┐ │ top_k ┆ bottom_k │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════╪══════════╡ │ 4 ┆ 1 │ │ 98 ┆ 98 │ │ 2 ┆ 2 │ │ 3 ┆ 3 │ │ 99 ┆ 4 │ └───────┴──────────┘ """ k_pyexpr = parse_into_expression(k) return wrap_expr(self._pyexpr.top_k(k_pyexpr)) @deprecate_renamed_parameter("descending", "reverse", version="1.0.0") def top_k_by( self, by: IntoExpr | Iterable[IntoExpr], k: int | IntoExprColumn = 5, *, reverse: bool | Sequence[bool] = False, ) -> Expr: r""" Return the elements corresponding to the `k` largest elements of the `by` column(s). 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, call :func:`sort` after this function if you wish the output to be sorted. This has time complexity: .. math:: O(n \log{n}) .. versionchanged:: 1.0.0 The `descending` parameter was renamed to `reverse`. Parameters ---------- by Column(s) used to determine the largest elements. Accepts expression input. Strings are parsed as column names. k Number of elements to return. 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. See Also -------- top_k bottom_k bottom_k_by Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, 3, 4, 5, 6], ... "b": [6, 5, 4, 3, 2, 1], ... "c": ["Apple", "Orange", "Apple", "Apple", "Banana", "Banana"], ... } ... ) >>> df shape: (6, 3) ┌─────┬─────┬────────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞═════╪═════╪════════╡ │ 1 ┆ 6 ┆ Apple │ │ 2 ┆ 5 ┆ Orange │ │ 3 ┆ 4 ┆ Apple │ │ 4 ┆ 3 ┆ Apple │ │ 5 ┆ 2 ┆ Banana │ │ 6 ┆ 1 ┆ Banana │ └─────┴─────┴────────┘ Get the top 2 rows by column `a` or `b`. >>> df.select( ... pl.all().top_k_by("a", 2).name.suffix("_top_by_a"), ... pl.all().top_k_by("b", 2).name.suffix("_top_by_b"), ... ) shape: (2, 6) ┌────────────┬────────────┬────────────┬────────────┬────────────┬────────────┐ │ a_top_by_a ┆ b_top_by_a ┆ c_top_by_a ┆ a_top_by_b ┆ b_top_by_b ┆ c_top_by_b │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str ┆ i64 ┆ i64 ┆ str │ ╞════════════╪════════════╪════════════╪════════════╪════════════╪════════════╡ │ 6 ┆ 1 ┆ Banana ┆ 1 ┆ 6 ┆ Apple │ │ 5 ┆ 2 ┆ Banana ┆ 2 ┆ 5 ┆ Orange │ └────────────┴────────────┴────────────┴────────────┴────────────┴────────────┘ Get the top 2 rows by multiple columns with given order. >>> df.select( ... pl.all() ... .top_k_by(["c", "a"], 2, reverse=[False, True]) ... .name.suffix("_by_ca"), ... pl.all() ... .top_k_by(["c", "b"], 2, reverse=[False, True]) ... .name.suffix("_by_cb"), ... ) shape: (2, 6) ┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ │ a_by_ca ┆ b_by_ca ┆ c_by_ca ┆ a_by_cb ┆ b_by_cb ┆ c_by_cb │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str ┆ i64 ┆ i64 ┆ str │ ╞═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡ │ 2 ┆ 5 ┆ Orange ┆ 2 ┆ 5 ┆ Orange │ │ 5 ┆ 2 ┆ Banana ┆ 6 ┆ 1 ┆ Banana │ └─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ Get the top 2 rows by column `a` in each group. >>> ( ... df.group_by("c", maintain_order=True) ... .agg(pl.all().top_k_by("a", 2)) ... .explode(pl.all().exclude("c")) ... ) shape: (5, 3) ┌────────┬─────┬─────┐ │ c ┆ a ┆ b │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞════════╪═════╪═════╡ │ Apple ┆ 4 ┆ 3 │ │ Apple ┆ 3 ┆ 4 │ │ Orange ┆ 2 ┆ 5 │ │ Banana ┆ 6 ┆ 1 │ │ Banana ┆ 5 ┆ 2 │ └────────┴─────┴─────┘ """ # noqa: W505 k_pyexpr = parse_into_expression(k) by_pyexprs = parse_into_list_of_expressions(by) reverse = extend_bool(reverse, len(by_pyexprs), "reverse", "by") return wrap_expr(self._pyexpr.top_k_by(by_pyexprs, k=k_pyexpr, reverse=reverse)) def bottom_k(self, k: int | IntoExprColumn = 5) -> Expr: r""" Return the `k` smallest elements. Non-null elements are always preferred over null elements. The output is not guaranteed to be in any particular order, call :func:`sort` after this function if you wish the output to be sorted. This has time complexity: .. math:: O(n) Parameters ---------- k Number of elements to return. See Also -------- top_k top_k_by bottom_k_by Examples -------- >>> df = pl.DataFrame( ... { ... "value": [1, 98, 2, 3, 99, 4], ... } ... ) >>> df.select( ... pl.col("value").top_k().alias("top_k"), ... pl.col("value").bottom_k().alias("bottom_k"), ... ) shape: (5, 2) ┌───────┬──────────┐ │ top_k ┆ bottom_k │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════╪══════════╡ │ 4 ┆ 1 │ │ 98 ┆ 98 │ │ 2 ┆ 2 │ │ 3 ┆ 3 │ │ 99 ┆ 4 │ └───────┴──────────┘ """ k_pyexpr = parse_into_expression(k) return wrap_expr(self._pyexpr.bottom_k(k_pyexpr)) @deprecate_renamed_parameter("descending", "reverse", version="1.0.0") def bottom_k_by( self, by: IntoExpr | Iterable[IntoExpr], k: int | IntoExprColumn = 5, *, reverse: bool | Sequence[bool] = False, ) -> Expr: r""" Return the elements corresponding to the `k` smallest elements of the `by` column(s). 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, call :func:`sort` after this function if you wish the output to be sorted. This has time complexity: .. math:: O(n \log{n}) .. versionchanged:: 1.0.0 The `descending` parameter was renamed `reverse`. Parameters ---------- by Column(s) used to determine the smallest elements. Accepts expression input. Strings are parsed as column names. k Number of elements to return. reverse Consider the `k` largest elements of the `by` column(s) (instead of the `k` smallest). This can be specified per column by passing a sequence of booleans. See Also -------- top_k top_k_by bottom_k Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, 3, 4, 5, 6], ... "b": [6, 5, 4, 3, 2, 1], ... "c": ["Apple", "Orange", "Apple", "Apple", "Banana", "Banana"], ... } ... ) >>> df shape: (6, 3) ┌─────┬─────┬────────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str │ ╞═════╪═════╪════════╡ │ 1 ┆ 6 ┆ Apple │ │ 2 ┆ 5 ┆ Orange │ │ 3 ┆ 4 ┆ Apple │ │ 4 ┆ 3 ┆ Apple │ │ 5 ┆ 2 ┆ Banana │ │ 6 ┆ 1 ┆ Banana │ └─────┴─────┴────────┘ Get the bottom 2 rows by column `a` or `b`. >>> df.select( ... pl.all().bottom_k_by("a", 2).name.suffix("_btm_by_a"), ... pl.all().bottom_k_by("b", 2).name.suffix("_btm_by_b"), ... ) shape: (2, 6) ┌────────────┬────────────┬────────────┬────────────┬────────────┬────────────┐ │ a_btm_by_a ┆ b_btm_by_a ┆ c_btm_by_a ┆ a_btm_by_b ┆ b_btm_by_b ┆ c_btm_by_b │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str ┆ i64 ┆ i64 ┆ str │ ╞════════════╪════════════╪════════════╪════════════╪════════════╪════════════╡ │ 1 ┆ 6 ┆ Apple ┆ 6 ┆ 1 ┆ Banana │ │ 2 ┆ 5 ┆ Orange ┆ 5 ┆ 2 ┆ Banana │ └────────────┴────────────┴────────────┴────────────┴────────────┴────────────┘ Get the bottom 2 rows by multiple columns with given order. >>> df.select( ... pl.all() ... .bottom_k_by(["c", "a"], 2, reverse=[False, True]) ... .name.suffix("_by_ca"), ... pl.all() ... .bottom_k_by(["c", "b"], 2, reverse=[False, True]) ... .name.suffix("_by_cb"), ... ) shape: (2, 6) ┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐ │ a_by_ca ┆ b_by_ca ┆ c_by_ca ┆ a_by_cb ┆ b_by_cb ┆ c_by_cb │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ str ┆ i64 ┆ i64 ┆ str │ ╞═════════╪═════════╪═════════╪═════════╪═════════╪═════════╡ │ 4 ┆ 3 ┆ Apple ┆ 1 ┆ 6 ┆ Apple │ │ 3 ┆ 4 ┆ Apple ┆ 3 ┆ 4 ┆ Apple │ └─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘ Get the bottom 2 rows by column `a` in each group. >>> ( ... df.group_by("c", maintain_order=True) ... .agg(pl.all().bottom_k_by("a", 2)) ... .explode(pl.all().exclude("c")) ... ) shape: (5, 3) ┌────────┬─────┬─────┐ │ c ┆ a ┆ b │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞════════╪═════╪═════╡ │ Apple ┆ 1 ┆ 6 │ │ Apple ┆ 3 ┆ 4 │ │ Orange ┆ 2 ┆ 5 │ │ Banana ┆ 5 ┆ 2 │ │ Banana ┆ 6 ┆ 1 │ └────────┴─────┴─────┘ """ # noqa: W505 k_pyexpr = parse_into_expression(k) by_pyexpr = parse_into_list_of_expressions(by) reverse = extend_bool(reverse, len(by_pyexpr), "reverse", "by") return wrap_expr( self._pyexpr.bottom_k_by(by_pyexpr, k=k_pyexpr, reverse=reverse) ) def arg_sort(self, *, descending: bool = False, nulls_last: bool = False) -> Expr: """ Get the index values that would sort this column. Parameters ---------- descending Sort in descending (descending) order. nulls_last Place null values last instead of first. Returns ------- Expr Expression of data type :class:`UInt32`. See Also -------- Expr.gather: Take values by index. Expr.rank : Get the rank of each row. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [20, 10, 30], ... "b": [1, 2, 3], ... } ... ) >>> df.select(pl.col("a").arg_sort()) shape: (3, 1) ┌─────┐ │ a │ │ --- │ │ u32 │ ╞═════╡ │ 1 │ │ 0 │ │ 2 │ └─────┘ Use gather to apply the arg sort to other columns. >>> df.select(pl.col("b").gather(pl.col("a").arg_sort())) shape: (3, 1) ┌─────┐ │ b │ │ --- │ │ i64 │ ╞═════╡ │ 2 │ │ 1 │ │ 3 │ └─────┘ """ return wrap_expr(self._pyexpr.arg_sort(descending, nulls_last)) def arg_max(self) -> Expr: """ Get the index of the maximal value. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [20, 10, 30], ... } ... ) >>> df.select(pl.col("a").arg_max()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ u32 │ ╞═════╡ │ 2 │ └─────┘ """ return wrap_expr(self._pyexpr.arg_max()) def arg_min(self) -> Expr: """ Get the index of the minimal value. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [20, 10, 30], ... } ... ) >>> df.select(pl.col("a").arg_min()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ u32 │ ╞═════╡ │ 1 │ └─────┘ """ return wrap_expr(self._pyexpr.arg_min()) def index_of(self, element: IntoExpr) -> Expr: """ Get the index of the first occurrence of a value, or ``None`` if it's not found. Parameters ---------- element Value to find. Examples -------- >>> df = pl.DataFrame({"a": [1, None, 17]}) >>> df.select( ... [ ... pl.col("a").index_of(17).alias("seventeen"), ... pl.col("a").index_of(None).alias("null"), ... pl.col("a").index_of(55).alias("fiftyfive"), ... ] ... ) shape: (1, 3) ┌───────────┬──────┬───────────┐ │ seventeen ┆ null ┆ fiftyfive │ │ --- ┆ --- ┆ --- │ │ u32 ┆ u32 ┆ u32 │ ╞═══════════╪══════╪═══════════╡ │ 2 ┆ 1 ┆ null │ └───────────┴──────┴───────────┘ """ dtype = None # Decimals by default are converted with maximum precision, but that # makes lossless casting hard. So for Decimals we manually specify the # minimal required precision. if isinstance(element, Decimal): _, digits, exponent = element.as_tuple() if isinstance(exponent, int): # can also be 'n'/'N'/'F' dtype = PolarsDecimal(len(digits), -exponent) element_pyexpr = parse_into_expression(element, str_as_lit=True, dtype=dtype) return wrap_expr(self._pyexpr.index_of(element_pyexpr)) def search_sorted( self, element: IntoExpr | np.ndarray[Any, Any], side: SearchSortedSide = "any", *, descending: bool = False, ) -> Expr: """ Find indices where elements should be inserted to maintain order. .. math:: a[i-1] < v <= a[i] Parameters ---------- element Expression or scalar value. side : {'any', 'left', 'right'} If 'any', the index of the first suitable location found is given. If 'left', the index of the leftmost suitable location found is given. If 'right', return the rightmost suitable location found is given. descending Boolean indicating whether the values are descending or not (they are required to be sorted either way). Examples -------- >>> df = pl.DataFrame( ... { ... "values": [1, 2, 3, 5], ... } ... ) >>> df.select( ... [ ... pl.col("values").search_sorted(0).alias("zero"), ... pl.col("values").search_sorted(3).alias("three"), ... pl.col("values").search_sorted(6).alias("six"), ... ] ... ) shape: (1, 3) ┌──────┬───────┬─────┐ │ zero ┆ three ┆ six │ │ --- ┆ --- ┆ --- │ │ u32 ┆ u32 ┆ u32 │ ╞══════╪═══════╪═════╡ │ 0 ┆ 2 ┆ 4 │ └──────┴───────┴─────┘ """ element_pyexpr = parse_into_expression( element, str_as_lit=True, list_as_series=True ) return wrap_expr(self._pyexpr.search_sorted(element_pyexpr, side, descending)) def sort_by( self, by: IntoExpr | Iterable[IntoExpr], *more_by: IntoExpr, descending: bool | Sequence[bool] = False, nulls_last: bool | Sequence[bool] = False, multithreaded: bool = True, maintain_order: bool = False, ) -> Expr: """ Sort this column by the ordering of other columns. When used in a projection/selection context, the whole column is sorted. When used in a group by context, the groups are sorted. Parameters ---------- by Column(s) to sort by. Accepts expression input. Strings are parsed as column names. *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. multithreaded Sort using multiple threads. maintain_order Whether the order should be maintained if elements are equal. Examples -------- Pass a single column name to sort by that column. >>> df = pl.DataFrame( ... { ... "group": ["a", "a", "b", "b"], ... "value1": [1, 3, 4, 2], ... "value2": [8, 7, 6, 5], ... } ... ) >>> df.select(pl.col("group").sort_by("value1")) shape: (4, 1) ┌───────┐ │ group │ │ --- │ │ str │ ╞═══════╡ │ a │ │ b │ │ a │ │ b │ └───────┘ Sorting by expressions is also supported. >>> df.select(pl.col("group").sort_by(pl.col("value1") + pl.col("value2"))) shape: (4, 1) ┌───────┐ │ group │ │ --- │ │ str │ ╞═══════╡ │ b │ │ a │ │ a │ │ b │ └───────┘ Sort by multiple columns by passing a list of columns. >>> df.select(pl.col("group").sort_by(["value1", "value2"], descending=True)) shape: (4, 1) ┌───────┐ │ group │ │ --- │ │ str │ ╞═══════╡ │ b │ │ a │ │ b │ │ a │ └───────┘ Or use positional arguments to sort by multiple columns in the same way. >>> df.select(pl.col("group").sort_by("value1", "value2")) shape: (4, 1) ┌───────┐ │ group │ │ --- │ │ str │ ╞═══════╡ │ a │ │ b │ │ a │ │ b │ └───────┘ When sorting in a group by context, the groups are sorted. >>> df.group_by("group").agg( ... pl.col("value1").sort_by("value2") ... ) # doctest: +IGNORE_RESULT shape: (2, 2) ┌───────┬───────────┐ │ group ┆ value1 │ │ --- ┆ --- │ │ str ┆ list[i64] │ ╞═══════╪═══════════╡ │ a ┆ [3, 1] │ │ b ┆ [2, 4] │ └───────┴───────────┘ Take a single row from each group where a column attains its minimal value within that group. >>> df.group_by("group").agg( ... pl.all().sort_by("value2").first() ... ) # doctest: +IGNORE_RESULT shape: (2, 3) ┌───────┬────────┬────────┐ │ group ┆ value1 ┆ value2 | │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 | ╞═══════╪════════╪════════╡ │ a ┆ 3 ┆ 7 | │ b ┆ 2 ┆ 5 | └───────┴────────┴────────┘ """ by_pyexprs = parse_into_list_of_expressions(by, *more_by) descending = extend_bool(descending, len(by_pyexprs), "descending", "by") nulls_last = extend_bool(nulls_last, len(by_pyexprs), "nulls_last", "by") return wrap_expr( self._pyexpr.sort_by( by_pyexprs, descending, nulls_last, multithreaded, maintain_order ) ) def gather( self, indices: int | Sequence[int] | IntoExpr | Series | np.ndarray[Any, Any] ) -> Expr: """ Take values by index. Parameters ---------- indices An expression that leads to a UInt32 dtyped Series. Returns ------- Expr Expression of the same data type. See Also -------- Expr.get : Take a single value Examples -------- >>> df = pl.DataFrame( ... { ... "group": [ ... "one", ... "one", ... "one", ... "two", ... "two", ... "two", ... ], ... "value": [1, 98, 2, 3, 99, 4], ... } ... ) >>> df.group_by("group", maintain_order=True).agg( ... pl.col("value").gather([2, 1]) ... ) shape: (2, 2) ┌───────┬───────────┐ │ group ┆ value │ │ --- ┆ --- │ │ str ┆ list[i64] │ ╞═══════╪═══════════╡ │ one ┆ [2, 98] │ │ two ┆ [4, 99] │ └───────┴───────────┘ """ if (isinstance(indices, Sequence) and not isinstance(indices, str)) or ( _check_for_numpy(indices) and isinstance(indices, np.ndarray) ): indices_lit_pyexpr = F.lit(pl.Series("", indices, dtype=Int64))._pyexpr else: indices_lit_pyexpr = parse_into_expression(indices) return wrap_expr(self._pyexpr.gather(indices_lit_pyexpr)) def get(self, index: int | Expr) -> Expr: """ Return a single value by index. Parameters ---------- index An expression that leads to a UInt32 index. Returns ------- Expr Expression of the same data type. Examples -------- >>> df = pl.DataFrame( ... { ... "group": [ ... "one", ... "one", ... "one", ... "two", ... "two", ... "two", ... ], ... "value": [1, 98, 2, 3, 99, 4], ... } ... ) >>> df.group_by("group", maintain_order=True).agg(pl.col("value").get(1)) shape: (2, 2) ┌───────┬───────┐ │ group ┆ value │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═══════╡ │ one ┆ 98 │ │ two ┆ 99 │ └───────┴───────┘ """ index_lit_pyexpr = parse_into_expression(index) return wrap_expr(self._pyexpr.get(index_lit_pyexpr)) def shift( self, n: int | IntoExprColumn = 1, *, fill_value: IntoExpr | None = None ) -> Expr: """ Shift values by the given number of indices. Parameters ---------- n Number of indices to shift forward. If a negative value is passed, values are shifted in the opposite direction instead. fill_value Fill the resulting null values with this scalar value. Notes ----- This method is similar to the `LAG` operation in SQL when the value for `n` is positive. With a negative value for `n`, it is similar to `LEAD`. See Also -------- fill_null Examples -------- By default, values are shifted forward by one index. >>> df = pl.DataFrame({"a": [1, 2, 3, 4]}) >>> df.with_columns(shift=pl.col("a").shift()) shape: (4, 2) ┌─────┬───────┐ │ a ┆ shift │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════╡ │ 1 ┆ null │ │ 2 ┆ 1 │ │ 3 ┆ 2 │ │ 4 ┆ 3 │ └─────┴───────┘ Pass a negative value to shift in the opposite direction instead. >>> df.with_columns(shift=pl.col("a").shift(-2)) shape: (4, 2) ┌─────┬───────┐ │ a ┆ shift │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════╡ │ 1 ┆ 3 │ │ 2 ┆ 4 │ │ 3 ┆ null │ │ 4 ┆ null │ └─────┴───────┘ Specify `fill_value` to fill the resulting null values. >>> df.with_columns(shift=pl.col("a").shift(-2, fill_value=100)) shape: (4, 2) ┌─────┬───────┐ │ a ┆ shift │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═══════╡ │ 1 ┆ 3 │ │ 2 ┆ 4 │ │ 3 ┆ 100 │ │ 4 ┆ 100 │ └─────┴───────┘ """ if fill_value is not None: fill_value_pyexpr = parse_into_expression(fill_value, str_as_lit=True) else: fill_value_pyexpr = None n_pyexpr = parse_into_expression(n) return wrap_expr(self._pyexpr.shift(n_pyexpr, fill_value_pyexpr)) def fill_null( self, value: Any | Expr | None = None, strategy: FillNullStrategy | None = None, limit: int | None = None, ) -> Expr: """ Fill null values using the specified value or strategy. To interpolate over null values see interpolate. See the examples below to fill nulls with an expression. Parameters ---------- value Value used to fill null values. strategy : {None, 'forward', 'backward', 'min', 'max', 'mean', 'zero', 'one'} Strategy used to fill null values. limit Number of consecutive null values to fill when using the 'forward' or 'backward' strategy. See Also -------- backward_fill fill_nan forward_fill Notes ----- A null value is not the same as a NaN value. To fill NaN values, use :func:`fill_nan`. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, None], ... "b": [4, None, 6], ... } ... ) >>> df.with_columns(pl.col("b").fill_null(strategy="zero")) shape: (3, 2) ┌──────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪═════╡ │ 1 ┆ 4 │ │ 2 ┆ 0 │ │ null ┆ 6 │ └──────┴─────┘ >>> df.with_columns(pl.col("b").fill_null(99)) shape: (3, 2) ┌──────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪═════╡ │ 1 ┆ 4 │ │ 2 ┆ 99 │ │ null ┆ 6 │ └──────┴─────┘ >>> df.with_columns(pl.col("b").fill_null(strategy="forward")) shape: (3, 2) ┌──────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪═════╡ │ 1 ┆ 4 │ │ 2 ┆ 4 │ │ null ┆ 6 │ └──────┴─────┘ >>> df.with_columns(pl.col("b").fill_null(pl.col("b").median())) shape: (3, 2) ┌──────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ f64 │ ╞══════╪═════╡ │ 1 ┆ 4.0 │ │ 2 ┆ 5.0 │ │ null ┆ 6.0 │ └──────┴─────┘ >>> df.with_columns(pl.all().fill_null(pl.all().median())) shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════╡ │ 1.0 ┆ 4.0 │ │ 2.0 ┆ 5.0 │ │ 1.5 ┆ 6.0 │ └─────┴─────┘ """ if value is not None and strategy is not None: msg = "cannot specify both `value` and `strategy`" raise ValueError(msg) elif value is None and strategy is None: msg = "must specify either a fill `value` or `strategy`" raise ValueError(msg) elif strategy not in ("forward", "backward") and limit is not None: msg = "can only specify `limit` when strategy is set to 'backward' or 'forward'" raise ValueError(msg) if value is not None: value_pyexpr = parse_into_expression(value, str_as_lit=True) return wrap_expr(self._pyexpr.fill_null(value_pyexpr)) else: assert strategy is not None return wrap_expr(self._pyexpr.fill_null_with_strategy(strategy, limit)) def fill_nan(self, value: int | float | Expr | None) -> Expr: """ Fill floating point NaN value with a fill value. Parameters ---------- value Value used to fill NaN values. See Also -------- fill_null Notes ----- A NaN value is not the same as a null value. To fill null values, use :func:`fill_null`. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1.0, None, float("nan")], ... "b": [4.0, float("nan"), 6], ... } ... ) >>> df.with_columns(pl.col("b").fill_nan(0)) shape: (3, 2) ┌──────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞══════╪═════╡ │ 1.0 ┆ 4.0 │ │ null ┆ 0.0 │ │ NaN ┆ 6.0 │ └──────┴─────┘ """ fill_value_pyexpr = parse_into_expression(value, str_as_lit=True) return wrap_expr(self._pyexpr.fill_nan(fill_value_pyexpr)) def forward_fill(self, limit: int | None = None) -> Expr: """ Fill missing values with the last non-null value. This is an alias of `.fill_null(strategy="forward")`. Parameters ---------- limit The number of consecutive null values to forward fill. See Also -------- backward_fill fill_null shift """ return self.fill_null(strategy="forward", limit=limit) def backward_fill(self, limit: int | None = None) -> Expr: """ Fill missing values with the next non-null value. This is an alias of `.fill_null(strategy="backward")`. Parameters ---------- limit The number of consecutive null values to backward fill. See Also -------- fill_null forward_fill shift """ return self.fill_null(strategy="backward", limit=limit) def reverse(self) -> Expr: """ Reverse the selection. Examples -------- >>> df = pl.DataFrame( ... { ... "A": [1, 2, 3, 4, 5], ... "fruits": ["banana", "banana", "apple", "apple", "banana"], ... "B": [5, 4, 3, 2, 1], ... "cars": ["beetle", "audi", "beetle", "beetle", "beetle"], ... } ... ) >>> df.select( ... [ ... pl.all(), ... pl.all().reverse().name.suffix("_reverse"), ... ] ... ) shape: (5, 8) ┌─────┬────────┬─────┬────────┬───────────┬────────────────┬───────────┬──────────────┐ │ A ┆ fruits ┆ B ┆ cars ┆ A_reverse ┆ fruits_reverse ┆ B_reverse ┆ cars_reverse │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ i64 ┆ str ┆ i64 ┆ str ┆ i64 ┆ str │ ╞═════╪════════╪═════╪════════╪═══════════╪════════════════╪═══════════╪══════════════╡ │ 1 ┆ banana ┆ 5 ┆ beetle ┆ 5 ┆ banana ┆ 1 ┆ beetle │ │ 2 ┆ banana ┆ 4 ┆ audi ┆ 4 ┆ apple ┆ 2 ┆ beetle │ │ 3 ┆ apple ┆ 3 ┆ beetle ┆ 3 ┆ apple ┆ 3 ┆ beetle │ │ 4 ┆ apple ┆ 2 ┆ beetle ┆ 2 ┆ banana ┆ 4 ┆ audi │ │ 5 ┆ banana ┆ 1 ┆ beetle ┆ 1 ┆ banana ┆ 5 ┆ beetle │ └─────┴────────┴─────┴────────┴───────────┴────────────────┴───────────┴──────────────┘ """ # noqa: W505 return wrap_expr(self._pyexpr.reverse()) def std(self, ddof: int = 1) -> Expr: """ Get standard deviation. Parameters ---------- 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 -------- >>> df = pl.DataFrame({"a": [-1, 0, 1]}) >>> df.select(pl.col("a").std()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ └─────┘ """ return wrap_expr(self._pyexpr.std(ddof)) def var(self, ddof: int = 1) -> Expr: """ Get variance. Parameters ---------- 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 -------- >>> df = pl.DataFrame({"a": [-1, 0, 1]}) >>> df.select(pl.col("a").var()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ └─────┘ """ return wrap_expr(self._pyexpr.var(ddof)) def max(self) -> Expr: """ Get maximum value. Examples -------- >>> df = pl.DataFrame({"a": [-1.0, float("nan"), 1.0]}) >>> df.select(pl.col("a").max()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ └─────┘ """ return wrap_expr(self._pyexpr.max()) def min(self) -> Expr: """ Get minimum value. Examples -------- >>> df = pl.DataFrame({"a": [-1.0, float("nan"), 1.0]}) >>> df.select(pl.col("a").min()) shape: (1, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ -1.0 │ └──────┘ """ return wrap_expr(self._pyexpr.min()) def nan_max(self) -> Expr: """ Get maximum value, but propagate/poison encountered NaN values. This differs from numpy's `nanmax` as numpy defaults to propagating NaN values, whereas polars defaults to ignoring them. Examples -------- >>> df = pl.DataFrame({"a": [0.0, float("nan")]}) >>> df.select(pl.col("a").nan_max()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ NaN │ └─────┘ """ return wrap_expr(self._pyexpr.nan_max()) def nan_min(self) -> Expr: """ Get minimum value, but propagate/poison encountered NaN values. This differs from numpy's `nanmax` as numpy defaults to propagating NaN values, whereas polars defaults to ignoring them. Examples -------- >>> df = pl.DataFrame({"a": [0.0, float("nan")]}) >>> df.select(pl.col("a").nan_min()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ NaN │ └─────┘ """ return wrap_expr(self._pyexpr.nan_min()) def sum(self) -> Expr: """ Get sum value. Notes ----- * Dtypes in {Int8, UInt8, Int16, UInt16} are cast to Int64 before summing to prevent overflow issues. * If there are no non-null values, then the output is `0`. If you would prefer empty sums to return `None`, you can use `pl.when(expr.count()>0).then(expr.sum())` instead of `expr.sum()`. Examples -------- >>> df = pl.DataFrame({"a": [-1, 0, 1]}) >>> df.select(pl.col("a").sum()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 0 │ └─────┘ """ return wrap_expr(self._pyexpr.sum()) def mean(self) -> Expr: """ Get mean value. Examples -------- >>> df = pl.DataFrame({"a": [-1, 0, 1]}) >>> df.select(pl.col("a").mean()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 0.0 │ └─────┘ """ return wrap_expr(self._pyexpr.mean()) def median(self) -> Expr: """ Get median value using linear interpolation. Examples -------- >>> df = pl.DataFrame({"a": [-1, 0, 1]}) >>> df.select(pl.col("a").median()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 0.0 │ └─────┘ """ return wrap_expr(self._pyexpr.median()) def product(self) -> Expr: """ Compute the product of an expression. Notes ----- If there are no non-null values, then the output is `1`. If you would prefer empty products to return `None`, you can use `pl.when(expr.count()>0).then(expr.product())` instead of `expr.product()`. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").product()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 6 │ └─────┘ """ return wrap_expr(self._pyexpr.product()) def n_unique(self) -> Expr: """ Count unique values. Notes ----- `null` is considered to be a unique value for the purposes of this operation. Examples -------- >>> df = pl.DataFrame({"x": [1, 1, 2, 2, 3], "y": [1, 1, 1, None, None]}) >>> df.select( ... x_unique=pl.col("x").n_unique(), ... y_unique=pl.col("y").n_unique(), ... ) shape: (1, 2) ┌──────────┬──────────┐ │ x_unique ┆ y_unique │ │ --- ┆ --- │ │ u32 ┆ u32 │ ╞══════════╪══════════╡ │ 3 ┆ 2 │ └──────────┴──────────┘ """ return wrap_expr(self._pyexpr.n_unique()) def approx_n_unique(self) -> Expr: """ Approximate count of unique values. This is done using the HyperLogLog++ algorithm for cardinality estimation. Examples -------- >>> df = pl.DataFrame({"n": [1, 1, 2]}) >>> df.select(pl.col("n").approx_n_unique()) shape: (1, 1) ┌─────┐ │ n │ │ --- │ │ u32 │ ╞═════╡ │ 2 │ └─────┘ >>> df = pl.DataFrame({"n": range(1000)}) >>> df.select( ... exact=pl.col("n").n_unique(), ... approx=pl.col("n").approx_n_unique(), ... ) # doctest: +SKIP shape: (1, 2) ┌───────┬────────┐ │ exact ┆ approx │ │ --- ┆ --- │ │ u32 ┆ u32 │ ╞═══════╪════════╡ │ 1000 ┆ 1005 │ └───────┴────────┘ """ return wrap_expr(self._pyexpr.approx_n_unique()) def null_count(self) -> Expr: """ Count null values. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [None, 1, None], ... "b": [10, None, 300], ... "c": [350, 650, 850], ... } ... ) >>> df.select(pl.all().null_count()) shape: (1, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ u32 ┆ u32 ┆ u32 │ ╞═════╪═════╪═════╡ │ 2 ┆ 1 ┆ 0 │ └─────┴─────┴─────┘ """ return wrap_expr(self._pyexpr.null_count()) def has_nulls(self) -> Expr: """ Check whether the expression contains one or more null values. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [None, 1, None], ... "b": [10, None, 300], ... "c": [350, 650, 850], ... } ... ) >>> df.select(pl.all().has_nulls()) shape: (1, 3) ┌──────┬──────┬───────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ bool ┆ bool ┆ bool │ ╞══════╪══════╪═══════╡ │ true ┆ true ┆ false │ └──────┴──────┴───────┘ """ return self.null_count() > 0 def arg_unique(self) -> Expr: """ Get index of first unique value. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [8, 9, 10], ... "b": [None, 4, 4], ... } ... ) >>> df.select(pl.col("a").arg_unique()) shape: (3, 1) ┌─────┐ │ a │ │ --- │ │ u32 │ ╞═════╡ │ 0 │ │ 1 │ │ 2 │ └─────┘ >>> df.select(pl.col("b").arg_unique()) shape: (2, 1) ┌─────┐ │ b │ │ --- │ │ u32 │ ╞═════╡ │ 0 │ │ 1 │ └─────┘ """ return wrap_expr(self._pyexpr.arg_unique()) def unique(self, *, maintain_order: bool = False) -> Expr: """ Get unique values of this expression. Parameters ---------- maintain_order Maintain order of data. This requires more work. Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2]}) >>> df.select(pl.col("a").unique()) # doctest: +IGNORE_RESULT shape: (2, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 2 │ │ 1 │ └─────┘ >>> df.select(pl.col("a").unique(maintain_order=True)) shape: (2, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ └─────┘ """ if maintain_order: return wrap_expr(self._pyexpr.unique_stable()) return wrap_expr(self._pyexpr.unique()) def first(self, *, ignore_nulls: bool = False) -> Expr: """ Get the first value. Parameters ---------- ignore_nulls Ignore null values (default `False`). If set to `True`, the first non-null value is returned, otherwise `None` is returned if no non-null value exists. Examples -------- >>> df = pl.DataFrame({"a": [None, 1, 2]}) >>> df.select(pl.col("a").first()) shape: (1, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ null │ └──────┘ >>> df.select(pl.col("a").first(ignore_nulls=True)) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ └─────┘ """ return wrap_expr(self._pyexpr.first(ignore_nulls=ignore_nulls)) def last(self, *, ignore_nulls: bool = False) -> Expr: """ Get the last value. Parameters ---------- ignore_nulls Ignore null values (default `False`). If set to `True`, the last non-null value is returned, otherwise `None` is returned if no non-null value exists. Examples -------- >>> df = pl.DataFrame({"a": [1, 3, 2]}) >>> df.select(pl.col("a").last()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 2 │ └─────┘ """ return wrap_expr(self._pyexpr.last(ignore_nulls=ignore_nulls)) @unstable() def item(self, *, allow_empty: bool = False) -> Expr: """ Get the single value. This raises an error if there is not exactly one value. Parameters ---------- allow_empty Allow having no values to return `null`. See Also -------- :meth:`Expr.get` : Get a single value by index. Examples -------- >>> df = pl.DataFrame({"a": [1]}) >>> df.select(pl.col("a").item()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ └─────┘ >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").item()) Traceback (most recent call last): ... polars.exceptions.ComputeError: aggregation 'item' expected a single value, got 3 values >>> df.head(0).select(pl.col("a").item(allow_empty=True)) shape: (1, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ null │ └──────┘ """ # noqa: W505 return wrap_expr(self._pyexpr.item(allow_empty=allow_empty)) def over( self, partition_by: IntoExpr | Iterable[IntoExpr] | None = None, *more_exprs: IntoExpr, order_by: IntoExpr | Iterable[IntoExpr] | None = None, descending: bool = False, nulls_last: bool = False, mapping_strategy: WindowMappingStrategy = "group_to_rows", ) -> Expr: """ Compute expressions over the given groups. This expression is similar to performing a group by aggregation and joining the result back into the original DataFrame. The outcome is similar to how `window functions <https://www.postgresql.org/docs/current/tutorial-window.html>`_ work in PostgreSQL. Parameters ---------- partition_by Column(s) to group by. Accepts expression input. Strings are parsed as column names. *more_exprs Additional columns to group by, specified as positional arguments. order_by Order the window functions/aggregations with the partitioned groups by the result of the expression passed to `order_by`. descending In case 'order_by' is given, indicate whether to order in ascending or descending order. nulls_last In case 'order_by' is given, indicate whether to order the nulls in last position. mapping_strategy: {'group_to_rows', 'join', 'explode'} - group_to_rows If the aggregation results in multiple values per group, map them back to their row position in the DataFrame. This can only be done if each group yields the same elements before aggregation as after. If the aggregation results in one scalar value per group, this value will be mapped to every row. - join If the aggregation may result in multiple values per group, join the values as 'List<group_dtype>' to each row position. Warning: this can be memory intensive. If the aggregation always results in one scalar value per group, join this value as '<group_dtype>' to each row position. - explode If the aggregation may result in multiple values per group, map each value to a new row, similar to the results of `group_by` + `agg` + `explode`. If the aggregation always results in one scalar value per group, map this value to one row position. Sorting of the given groups is required if the groups are not part of the window operation for the operation, otherwise the result would not make sense. This operation changes the number of rows. Examples -------- Pass the name of a column to compute the expression over that column. >>> df = pl.DataFrame( ... { ... "a": ["a", "a", "b", "b", "b"], ... "b": [1, 2, 3, 5, 3], ... "c": [5, 4, 3, 2, 1], ... } ... ) >>> df.with_columns(c_max=pl.col("c").max().over("a")) shape: (5, 4) ┌─────┬─────┬─────┬───────┐ │ a ┆ b ┆ c ┆ c_max │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═══════╡ │ a ┆ 1 ┆ 5 ┆ 5 │ │ a ┆ 2 ┆ 4 ┆ 5 │ │ b ┆ 3 ┆ 3 ┆ 3 │ │ b ┆ 5 ┆ 2 ┆ 3 │ │ b ┆ 3 ┆ 1 ┆ 3 │ └─────┴─────┴─────┴───────┘ Expression input is also supported. >>> df.with_columns(c_max=pl.col("c").max().over(pl.col("b") // 2)) shape: (5, 4) ┌─────┬─────┬─────┬───────┐ │ a ┆ b ┆ c ┆ c_max │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═══════╡ │ a ┆ 1 ┆ 5 ┆ 5 │ │ a ┆ 2 ┆ 4 ┆ 4 │ │ b ┆ 3 ┆ 3 ┆ 4 │ │ b ┆ 5 ┆ 2 ┆ 2 │ │ b ┆ 3 ┆ 1 ┆ 4 │ └─────┴─────┴─────┴───────┘ Group by multiple columns by passing multiple column names or expressions. >>> df.with_columns(c_min=pl.col("c").min().over("a", pl.col("b") % 2)) shape: (5, 4) ┌─────┬─────┬─────┬───────┐ │ a ┆ b ┆ c ┆ c_min │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═══════╡ │ a ┆ 1 ┆ 5 ┆ 5 │ │ a ┆ 2 ┆ 4 ┆ 4 │ │ b ┆ 3 ┆ 3 ┆ 1 │ │ b ┆ 5 ┆ 2 ┆ 1 │ │ b ┆ 3 ┆ 1 ┆ 1 │ └─────┴─────┴─────┴───────┘ Mapping strategy `join` joins the values by group. >>> df.with_columns( ... c_pairs=pl.col("c").head(2).over("a", mapping_strategy="join") ... ) shape: (5, 4) ┌─────┬─────┬─────┬───────────┐ │ a ┆ b ┆ c ┆ c_pairs │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ list[i64] │ ╞═════╪═════╪═════╪═══════════╡ │ a ┆ 1 ┆ 5 ┆ [5, 4] │ │ a ┆ 2 ┆ 4 ┆ [5, 4] │ │ b ┆ 3 ┆ 3 ┆ [3, 2] │ │ b ┆ 5 ┆ 2 ┆ [3, 2] │ │ b ┆ 3 ┆ 1 ┆ [3, 2] │ └─────┴─────┴─────┴───────────┘ Mapping strategy `explode` maps the values to new rows, changing the shape. >>> df.select( ... c_first_2=pl.col("c").head(2).over("a", mapping_strategy="explode") ... ) shape: (4, 1) ┌───────────┐ │ c_first_2 │ │ --- │ │ i64 │ ╞═══════════╡ │ 5 │ │ 4 │ │ 3 │ │ 2 │ └───────────┘ You can use non-elementwise expressions with `over` too. By default they are evaluated using row-order, but you can specify a different one using `order_by`. >>> from datetime import date >>> df = pl.DataFrame( ... { ... "store_id": ["a", "a", "b", "b"], ... "date": [ ... date(2024, 9, 18), ... date(2024, 9, 17), ... date(2024, 9, 18), ... date(2024, 9, 16), ... ], ... "sales": [7, 9, 8, 10], ... } ... ) >>> df.with_columns( ... cumulative_sales=pl.col("sales") ... .cum_sum() ... .over("store_id", order_by="date") ... ) shape: (4, 4) ┌──────────┬────────────┬───────┬──────────────────┐ │ store_id ┆ date ┆ sales ┆ cumulative_sales │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ date ┆ i64 ┆ i64 │ ╞══════════╪════════════╪═══════╪══════════════════╡ │ a ┆ 2024-09-18 ┆ 7 ┆ 16 │ │ a ┆ 2024-09-17 ┆ 9 ┆ 9 │ │ b ┆ 2024-09-18 ┆ 8 ┆ 18 │ │ b ┆ 2024-09-16 ┆ 10 ┆ 10 │ └──────────┴────────────┴───────┴──────────────────┘ If you don't require that the group order be preserved, then the more performant option is to use `mapping_strategy='explode'` - be careful however to only ever use this in a `select` statement, not a `with_columns` one. >>> window = { ... "partition_by": "store_id", ... "order_by": "date", ... "mapping_strategy": "explode", ... } >>> df.select( ... pl.all().over(**window), ... cumulative_sales=pl.col("sales").cum_sum().over(**window), ... ) shape: (4, 4) ┌──────────┬────────────┬───────┬──────────────────┐ │ store_id ┆ date ┆ sales ┆ cumulative_sales │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ date ┆ i64 ┆ i64 │ ╞══════════╪════════════╪═══════╪══════════════════╡ │ a ┆ 2024-09-17 ┆ 9 ┆ 9 │ │ a ┆ 2024-09-18 ┆ 7 ┆ 16 │ │ b ┆ 2024-09-16 ┆ 10 ┆ 10 │ │ b ┆ 2024-09-18 ┆ 8 ┆ 18 │ └──────────┴────────────┴───────┴──────────────────┘ """ if partition_by is not None: partition_by_pyexprs = parse_into_list_of_expressions( partition_by, *more_exprs ) else: partition_by_pyexprs = None if order_by is not None: order_by_pyexprs = parse_into_list_of_expressions(order_by) else: order_by_pyexprs = None return wrap_expr( self._pyexpr.over( partition_by_pyexprs, order_by=order_by_pyexprs, order_by_descending=descending, order_by_nulls_last=False, # does not work yet mapping_strategy=mapping_strategy, ) ) def rolling( self, index_column: IntoExprColumn, *, period: str | timedelta, offset: str | timedelta | None = None, closed: ClosedInterval = "right", ) -> Expr: """ Create rolling groups based on a temporal or integer column. If you have a time series `<t_0, t_1, ..., t_n>`, then by default the windows created will be * (t_0 - period, t_0] * (t_1 - period, t_1] * ... * (t_n - period, t_n] whereas if you pass a non-default `offset`, then the windows will be * (t_0 + offset, t_0 + offset + period] * (t_1 + offset, t_1 + offset + period] * ... * (t_n + offset, t_n + offset + period] The `period` and `offset` arguments are created either from a timedelta, or by using the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) Or combine them: "3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". Parameters ---------- index_column Column used to group based on the time window. Often of type Date/Datetime. This column must be sorted in ascending order. In case of a rolling group by on indices, dtype needs to be one of {UInt32, UInt64, Int32, Int64}. Note that the first three get temporarily cast to Int64, so if performance matters use an Int64 column. period Length of the window - must be non-negative. offset Offset of the window. Default is `-period`. closed : {'right', 'left', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive). Examples -------- >>> dates = [ ... "2020-01-01 13:45:48", ... "2020-01-01 16:42:13", ... "2020-01-01 16:45:09", ... "2020-01-02 18:12:48", ... "2020-01-03 19:45:32", ... "2020-01-08 23:16:43", ... ] >>> df = pl.DataFrame({"dt": dates, "a": [3, 7, 5, 9, 2, 1]}).with_columns( ... pl.col("dt").str.strptime(pl.Datetime).set_sorted() ... ) >>> df.with_columns( ... sum_a=pl.sum("a").rolling(index_column="dt", period="2d"), ... min_a=pl.min("a").rolling(index_column="dt", period="2d"), ... max_a=pl.max("a").rolling(index_column="dt", period="2d"), ... ) shape: (6, 5) ┌─────────────────────┬─────┬───────┬───────┬───────┐ │ dt ┆ a ┆ sum_a ┆ min_a ┆ max_a │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ datetime[μs] ┆ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════════════════════╪═════╪═══════╪═══════╪═══════╡ │ 2020-01-01 13:45:48 ┆ 3 ┆ 3 ┆ 3 ┆ 3 │ │ 2020-01-01 16:42:13 ┆ 7 ┆ 10 ┆ 3 ┆ 7 │ │ 2020-01-01 16:45:09 ┆ 5 ┆ 15 ┆ 3 ┆ 7 │ │ 2020-01-02 18:12:48 ┆ 9 ┆ 24 ┆ 3 ┆ 9 │ │ 2020-01-03 19:45:32 ┆ 2 ┆ 11 ┆ 2 ┆ 9 │ │ 2020-01-08 23:16:43 ┆ 1 ┆ 1 ┆ 1 ┆ 1 │ └─────────────────────┴─────┴───────┴───────┴───────┘ """ index_column_pyexpr = parse_into_expression(index_column) if offset is None: offset = negate_duration_string(parse_as_duration_string(period)) period = parse_as_duration_string(period) offset = parse_as_duration_string(offset) return wrap_expr( self._pyexpr.rolling(index_column_pyexpr, period, offset, closed) ) def is_unique(self) -> Expr: """ Get mask of unique values. Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2]}) >>> df.select(pl.col("a").is_unique()) shape: (3, 1) ┌───────┐ │ a │ │ --- │ │ bool │ ╞═══════╡ │ false │ │ false │ │ true │ └───────┘ """ return wrap_expr(self._pyexpr.is_unique()) def is_first_distinct(self) -> Expr: """ Return a boolean mask indicating the first occurrence of each distinct value. Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2, 3, 2]}) >>> df.with_columns(pl.col("a").is_first_distinct().alias("first")) shape: (5, 2) ┌─────┬───────┐ │ a ┆ first │ │ --- ┆ --- │ │ i64 ┆ bool │ ╞═════╪═══════╡ │ 1 ┆ true │ │ 1 ┆ false │ │ 2 ┆ true │ │ 3 ┆ true │ │ 2 ┆ false │ └─────┴───────┘ """ return wrap_expr(self._pyexpr.is_first_distinct()) def is_last_distinct(self) -> Expr: """ Return a boolean mask indicating the last occurrence of each distinct value. Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2, 3, 2]}) >>> df.with_columns(pl.col("a").is_last_distinct().alias("last")) shape: (5, 2) ┌─────┬───────┐ │ a ┆ last │ │ --- ┆ --- │ │ i64 ┆ bool │ ╞═════╪═══════╡ │ 1 ┆ false │ │ 1 ┆ true │ │ 2 ┆ false │ │ 3 ┆ true │ │ 2 ┆ true │ └─────┴───────┘ """ return wrap_expr(self._pyexpr.is_last_distinct()) def is_duplicated(self) -> Expr: """ Return a boolean mask indicating duplicated values. Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2]}) >>> df.select(pl.col("a").is_duplicated()) shape: (3, 1) ┌───────┐ │ a │ │ --- │ │ bool │ ╞═══════╡ │ true │ │ true │ │ false │ └───────┘ """ return wrap_expr(self._pyexpr.is_duplicated()) def peak_max(self) -> Expr: """ Get a boolean mask of the local maximum peaks. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3, 4, 5]}) >>> df.select(pl.col("a").peak_max()) shape: (5, 1) ┌───────┐ │ a │ │ --- │ │ bool │ ╞═══════╡ │ false │ │ false │ │ false │ │ false │ │ true │ └───────┘ """ return wrap_expr(self._pyexpr.peak_max()) def peak_min(self) -> Expr: """ Get a boolean mask of the local minimum peaks. Examples -------- >>> df = pl.DataFrame({"a": [4, 1, 3, 2, 5]}) >>> df.select(pl.col("a").peak_min()) shape: (5, 1) ┌───────┐ │ a │ │ --- │ │ bool │ ╞═══════╡ │ false │ │ true │ │ false │ │ true │ │ false │ └───────┘ """ return wrap_expr(self._pyexpr.peak_min()) def quantile( self, quantile: float | Expr, interpolation: QuantileMethod = "nearest", ) -> Expr: """ Get quantile value. Parameters ---------- quantile Quantile between 0.0 and 1.0. interpolation : {'nearest', 'higher', 'lower', 'midpoint', 'linear', 'equiprobable'} Interpolation method. Examples -------- >>> df = pl.DataFrame({"a": [0, 1, 2, 3, 4, 5]}) >>> df.select(pl.col("a").quantile(0.3)) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 2.0 │ └─────┘ >>> df.select(pl.col("a").quantile(0.3, interpolation="higher")) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 2.0 │ └─────┘ >>> df.select(pl.col("a").quantile(0.3, interpolation="lower")) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ └─────┘ >>> df.select(pl.col("a").quantile(0.3, interpolation="midpoint")) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.5 │ └─────┘ >>> df.select(pl.col("a").quantile(0.3, interpolation="linear")) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.5 │ └─────┘ """ # noqa: W505 quantile_pyexpr = parse_into_expression(quantile) return wrap_expr(self._pyexpr.quantile(quantile_pyexpr, interpolation)) @unstable() def cut( self, breaks: Sequence[float], *, labels: Sequence[str] | None = None, left_closed: bool = False, include_breaks: bool = False, ) -> Expr: """ Bin continuous values into discrete categories. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Parameters ---------- breaks List of unique cut points. labels Names of the categories. The number of labels must be equal to the number of cut points plus one. left_closed Set the intervals to be left-closed instead of right-closed. include_breaks Include a column with the right endpoint of the bin each observation falls in. This will change the data type of the output from a :class:`Categorical` to a :class:`Struct`. Returns ------- Expr Expression of data type :class:`Categorical` if `include_breaks` is set to `False` (default), otherwise an expression of data type :class:`Struct`. See Also -------- qcut Examples -------- Divide a column into three categories. >>> df = pl.DataFrame({"foo": [-2, -1, 0, 1, 2]}) >>> df.with_columns( ... pl.col("foo").cut([-1, 1], labels=["a", "b", "c"]).alias("cut") ... ) shape: (5, 2) ┌─────┬─────┐ │ foo ┆ cut │ │ --- ┆ --- │ │ i64 ┆ cat │ ╞═════╪═════╡ │ -2 ┆ a │ │ -1 ┆ a │ │ 0 ┆ b │ │ 1 ┆ b │ │ 2 ┆ c │ └─────┴─────┘ Add both the category and the breakpoint. >>> df.with_columns( ... pl.col("foo").cut([-1, 1], include_breaks=True).alias("cut") ... ).unnest("cut") shape: (5, 3) ┌─────┬────────────┬────────────┐ │ foo ┆ breakpoint ┆ category │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ cat │ ╞═════╪════════════╪════════════╡ │ -2 ┆ -1.0 ┆ (-inf, -1] │ │ -1 ┆ -1.0 ┆ (-inf, -1] │ │ 0 ┆ 1.0 ┆ (-1, 1] │ │ 1 ┆ 1.0 ┆ (-1, 1] │ │ 2 ┆ inf ┆ (1, inf] │ └─────┴────────────┴────────────┘ """ return wrap_expr(self._pyexpr.cut(breaks, labels, left_closed, include_breaks)) @unstable() def qcut( self, quantiles: Sequence[float] | int, *, labels: Sequence[str] | None = None, left_closed: bool = False, allow_duplicates: bool = False, include_breaks: bool = False, ) -> Expr: """ Bin continuous values into discrete categories based on their quantiles. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Parameters ---------- quantiles Either a list of quantile probabilities between 0 and 1 or a positive integer determining the number of bins with uniform probability. labels Names of the categories. The number of labels must be equal to the number of categories. left_closed Set the intervals to be left-closed instead of right-closed. allow_duplicates If set to `True`, duplicates in the resulting quantiles are dropped, rather than raising a `DuplicateError`. This can happen even with unique probabilities, depending on the data. include_breaks Include a column with the right endpoint of the bin each observation falls in. This will change the data type of the output from a :class:`Categorical` to a :class:`Struct`. Returns ------- Expr Expression of data type :class:`Categorical` if `include_breaks` is set to `False` (default), otherwise an expression of data type :class:`Struct`. See Also -------- cut Examples -------- Divide a column into three categories according to pre-defined quantile probabilities. >>> df = pl.DataFrame({"foo": [-2, -1, 0, 1, 2]}) >>> df.with_columns( ... pl.col("foo").qcut([0.25, 0.75], labels=["a", "b", "c"]).alias("qcut") ... ) shape: (5, 2) ┌─────┬──────┐ │ foo ┆ qcut │ │ --- ┆ --- │ │ i64 ┆ cat │ ╞═════╪══════╡ │ -2 ┆ a │ │ -1 ┆ a │ │ 0 ┆ b │ │ 1 ┆ b │ │ 2 ┆ c │ └─────┴──────┘ Divide a column into two categories using uniform quantile probabilities. >>> df.with_columns( ... pl.col("foo") ... .qcut(2, labels=["low", "high"], left_closed=True) ... .alias("qcut") ... ) shape: (5, 2) ┌─────┬──────┐ │ foo ┆ qcut │ │ --- ┆ --- │ │ i64 ┆ cat │ ╞═════╪══════╡ │ -2 ┆ low │ │ -1 ┆ low │ │ 0 ┆ high │ │ 1 ┆ high │ │ 2 ┆ high │ └─────┴──────┘ Add both the category and the breakpoint. >>> df.with_columns( ... pl.col("foo").qcut([0.25, 0.75], include_breaks=True).alias("qcut") ... ).unnest("qcut") shape: (5, 3) ┌─────┬────────────┬────────────┐ │ foo ┆ breakpoint ┆ category │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ cat │ ╞═════╪════════════╪════════════╡ │ -2 ┆ -1.0 ┆ (-inf, -1] │ │ -1 ┆ -1.0 ┆ (-inf, -1] │ │ 0 ┆ 1.0 ┆ (-1, 1] │ │ 1 ┆ 1.0 ┆ (-1, 1] │ │ 2 ┆ inf ┆ (1, inf] │ └─────┴────────────┴────────────┘ """ if isinstance(quantiles, int): pyexpr = self._pyexpr.qcut_uniform( quantiles, labels, left_closed, allow_duplicates, include_breaks ) else: pyexpr = self._pyexpr.qcut( quantiles, labels, left_closed, allow_duplicates, include_breaks ) return wrap_expr(pyexpr) def rle(self) -> Expr: """ Compress the column data using run-length encoding. Run-length encoding (RLE) encodes data by storing each *run* of identical values as a single value and its length. Returns ------- Expr Expression of data type `Struct` with fields `len` of data type `UInt32` and `value` of the original data type. See Also -------- rle_id Examples -------- >>> df = pl.DataFrame({"a": [1, 1, 2, 1, None, 1, 3, 3]}) >>> df.select(pl.col("a").rle()).unnest("a") shape: (6, 2) ┌─────┬───────┐ │ len ┆ value │ │ --- ┆ --- │ │ u32 ┆ i64 │ ╞═════╪═══════╡ │ 2 ┆ 1 │ │ 1 ┆ 2 │ │ 1 ┆ 1 │ │ 1 ┆ null │ │ 1 ┆ 1 │ │ 2 ┆ 3 │ └─────┴───────┘ """ return wrap_expr(self._pyexpr.rle()) def rle_id(self) -> Expr: """ Get a distinct integer ID for each run of identical values. The ID starts at 0 and increases by one each time the value of the column changes. Returns ------- Expr Expression of data type `UInt32`. See Also -------- rle Notes ----- This functionality is especially useful for defining a new group for every time a column's value changes, rather than for every distinct value of that column. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, 1, 1, 1], ... "b": ["x", "x", None, "y", "y"], ... } ... ) >>> df.with_columns( ... rle_id_a=pl.col("a").rle_id(), ... rle_id_ab=pl.struct("a", "b").rle_id(), ... ) shape: (5, 4) ┌─────┬──────┬──────────┬───────────┐ │ a ┆ b ┆ rle_id_a ┆ rle_id_ab │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ u32 ┆ u32 │ ╞═════╪══════╪══════════╪═══════════╡ │ 1 ┆ x ┆ 0 ┆ 0 │ │ 2 ┆ x ┆ 1 ┆ 1 │ │ 1 ┆ null ┆ 2 ┆ 2 │ │ 1 ┆ y ┆ 2 ┆ 3 │ │ 1 ┆ y ┆ 2 ┆ 3 │ └─────┴──────┴──────────┴───────────┘ """ return wrap_expr(self._pyexpr.rle_id()) def filter( self, *predicates: IntoExprColumn | Iterable[IntoExprColumn], **constraints: Any, ) -> Expr: """ Filter the expression based on one or more predicate expressions. The original order of the remaining elements is preserved. Elements where the filter does not evaluate to True are discarded, including nulls. Mostly useful in an aggregation context. If you want to filter on a DataFrame level, use `LazyFrame.filter`. Parameters ---------- 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 `pl.col(name).eq(value)`, and be implicitly joined with the other filter conditions using `&`. Examples -------- >>> df = pl.DataFrame( ... { ... "group_col": ["g1", "g1", "g2"], ... "b": [1, 2, 3], ... } ... ) >>> df.group_by("group_col").agg( ... lt=pl.col("b").filter(pl.col("b") < 2).sum(), ... gte=pl.col("b").filter(pl.col("b") >= 2).sum(), ... ).sort("group_col") shape: (2, 3) ┌───────────┬─────┬─────┐ │ group_col ┆ lt ┆ gte │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞═══════════╪═════╪═════╡ │ g1 ┆ 1 ┆ 2 │ │ g2 ┆ 0 ┆ 3 │ └───────────┴─────┴─────┘ Filter expressions can also take constraints as keyword arguments. >>> df = pl.DataFrame( ... { ... "key": ["a", "a", "a", "a", "b", "b", "b", "b", "b"], ... "n": [1, 2, 2, 3, 1, 3, 3, 2, 3], ... }, ... ) >>> df.group_by("key").agg( ... n_1=pl.col("n").filter(n=1).sum(), ... n_2=pl.col("n").filter(n=2).sum(), ... n_3=pl.col("n").filter(n=3).sum(), ... ).sort(by="key") shape: (2, 4) ┌─────┬─────┬─────┬─────┐ │ key ┆ n_1 ┆ n_2 ┆ n_3 │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╡ │ a ┆ 1 ┆ 4 ┆ 3 │ │ b ┆ 1 ┆ 2 ┆ 9 │ └─────┴─────┴─────┴─────┘ """ predicate = parse_predicates_constraints_into_expression( *predicates, **constraints ) return wrap_expr(self._pyexpr.filter(predicate)) @deprecated("`where` is deprecated; use `filter` instead.") def where(self, predicate: Expr) -> Expr: """ Filter a single column. .. deprecated:: 0.20.4 Use the :func:`filter` method instead. Alias for :func:`filter`. Parameters ---------- predicate Boolean expression. Examples -------- >>> df = pl.DataFrame( ... { ... "group_col": ["g1", "g1", "g2"], ... "b": [1, 2, 3], ... } ... ) >>> df.group_by("group_col").agg( # doctest: +SKIP ... [ ... pl.col("b").where(pl.col("b") < 2).sum().alias("lt"), ... pl.col("b").where(pl.col("b") >= 2).sum().alias("gte"), ... ] ... ).sort("group_col") shape: (2, 3) ┌───────────┬─────┬─────┐ │ group_col ┆ lt ┆ gte │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞═══════════╪═════╪═════╡ │ g1 ┆ 1 ┆ 2 │ │ g2 ┆ 0 ┆ 3 │ └───────────┴─────┴─────┘ """ return self.filter(predicate) def map_batches( self, function: Callable[[Series], Series | Any], return_dtype: PolarsDataType | pl.DataTypeExpr | None = None, *, agg_list: bool = False, is_elementwise: bool = False, returns_scalar: bool = False, ) -> Expr: """ 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), or a scalar that will be converted into a Series. If the result is a scalar and you want it to stay as a scalar, pass in ``returns_scalar=True``. If you want to apply a custom function elementwise over single values, see :func:`map_elements`. A reasonable use case for `map` functions is transforming the values represented by an expression using a third-party library. Parameters ---------- function Lambda/function to apply. return_dtype Datatype of the output Series. It is recommended to set this whenever possible. If this is `None`, it tries to infer the datatype by calling the function with dummy data and looking at the output. agg_list First implode when in a group-by aggregation. .. deprecated:: 1.32.0 Use `expr.implode().map_batches(..)` instead. is_elementwise Set to true if the operations is elementwise for better performance and optimization. An elementwise operations has unit or equal length for all inputs and can be ran sequentially on slices without results being affected. 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. Notes ----- A UDF passed to `map_batches` must be pure, meaning that it cannot modify or depend on state other than its arguments. Polars may call the function with arbitrary input data. See Also -------- map_elements replace Examples -------- >>> df = pl.DataFrame( ... { ... "sine": [0.0, 1.0, 0.0, -1.0], ... "cosine": [1.0, 0.0, -1.0, 0.0], ... } ... ) >>> df.select( ... pl.all().map_batches( ... lambda x: x.to_numpy().argmax(), ... returns_scalar=True, ... ) ... ) shape: (1, 2) ┌──────┬────────┐ │ sine ┆ cosine │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪════════╡ │ 1 ┆ 0 │ └──────┴────────┘ Here's an example of a function that returns a scalar, where we want it to stay as a scalar: >>> df = pl.DataFrame( ... { ... "a": [0, 1, 0, 1], ... "b": [1, 2, 3, 4], ... } ... ) >>> df.group_by("a").agg( ... pl.col("b").map_batches( ... lambda x: x.max(), returns_scalar=True, return_dtype=pl.self_dtype() ... ) ... ) # doctest: +IGNORE_RESULT shape: (2, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 4 │ │ 0 ┆ 3 │ └─────┴─────┘ Call a function that takes multiple arguments by creating a `struct` and referencing its fields inside the function call. >>> df = pl.DataFrame( ... { ... "a": [5, 1, 0, 3], ... "b": [4, 2, 3, 4], ... } ... ) >>> df.with_columns( ... a_times_b=pl.struct("a", "b").map_batches( ... lambda x: np.multiply(x.struct.field("a"), x.struct.field("b")), ... return_dtype=pl.Int64, ... ) ... ) shape: (4, 3) ┌─────┬─────┬───────────┐ │ a ┆ b ┆ a_times_b │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═══════════╡ │ 5 ┆ 4 ┆ 20 │ │ 1 ┆ 2 ┆ 2 │ │ 0 ┆ 3 ┆ 0 │ │ 3 ┆ 4 ┆ 12 │ └─────┴─────┴───────────┘ """ if agg_list: msg = f"""using 'agg_list=True' is deprecated and will be removed in 2.0 Consider using {self}.implode() instead""" raise DeprecationWarning(msg) self = self.implode() def _wrap(sl: Sequence[pl.Series], *args: Any, **kwargs: Any) -> pl.Series: return function(sl[0], *args, **kwargs) return F.map_batches( [self], _wrap, return_dtype, is_elementwise=is_elementwise, returns_scalar=returns_scalar, ) def map_elements( self, function: Callable[[Any], Any], return_dtype: PolarsDataType | pl.DataTypeExpr | None = None, *, skip_nulls: bool = True, pass_name: bool = False, strategy: MapElementsStrategy = "thread_local", returns_scalar: bool = False, ) -> Expr: """ Map a custom/user-defined function (UDF) to each element of a column. .. warning:: This method is much slower than the native expressions API. Only use it if you cannot implement your logic otherwise. Suppose that the function is: `x ↦ sqrt(x)`: - For mapping elements of a series, consider: `pl.col("col_name").sqrt()`. - For mapping inner elements of lists, consider: `pl.col("col_name").list.eval(pl.element().sqrt())`. - For mapping elements of struct fields, consider: `pl.col("col_name").struct.field("field_name").sqrt()`. If you want to replace the original column or field, consider :meth:`.with_columns <polars.DataFrame.with_columns>` and :meth:`.with_fields <polars.Expr.struct.with_fields>`. Parameters ---------- function Lambda/function to map. return_dtype Datatype of the output Series. It is recommended to set this whenever possible. If this is `None`, it tries to infer the datatype by calling the function with dummy data and looking at the output. skip_nulls Don't map the function over values that contain nulls (this is faster). pass_name Pass the Series name to the custom function (this is more expensive). returns_scalar .. deprecated:: 1.32.0 Is ignored and will be removed in 2.0. strategy : {'thread_local', 'threading'} The threading strategy to use. - 'thread_local': run the python function on a single thread. - 'threading': run the python function on separate threads. Use with care as this can slow performance. This might only speed up your code if the amount of work per element is significant and the python function releases the GIL (e.g. via calling a c function) .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Notes ----- * Using `map_elements` is strongly discouraged as you will be effectively running python "for" loops, which will be very slow. Wherever possible you should prefer the native expression API to achieve the best performance. * If your function is expensive and you don't want it to be called more than once for a given input, consider applying an `@lru_cache` decorator to it. If your data is suitable you may achieve *significant* speedups. * Window function application using `over` is considered a GroupBy context here, so `map_elements` can be used to map functions over window groups. * A UDF passed to `map_elements` must be pure, meaning that it cannot modify or depend on state other than its arguments. Polars may call the function with arbitrary input data. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, 3, 1], ... "b": ["a", "b", "c", "c"], ... } ... ) The function is applied to each element of column `'a'`: >>> df.with_columns( # doctest: +SKIP ... pl.col("a") ... .map_elements(lambda x: x * 2, return_dtype=pl.self_dtype()) ... .alias("a_times_2"), ... ) shape: (4, 3) ┌─────┬─────┬───────────┐ │ a ┆ b ┆ a_times_2 │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ i64 │ ╞═════╪═════╪═══════════╡ │ 1 ┆ a ┆ 2 │ │ 2 ┆ b ┆ 4 │ │ 3 ┆ c ┆ 6 │ │ 1 ┆ c ┆ 2 │ └─────┴─────┴───────────┘ Tip: it is better to implement this with an expression: >>> df.with_columns( ... (pl.col("a") * 2).alias("a_times_2"), ... ) # doctest: +IGNORE_RESULT >>> ( ... df.lazy() ... .group_by("b") ... .agg( ... pl.col("a") ... .implode() ... .map_elements(lambda x: x.sum(), return_dtype=pl.Int64) ... ) ... .collect() ... ) # doctest: +IGNORE_RESULT shape: (3, 2) ┌─────┬─────┐ │ b ┆ a │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════╪═════╡ │ a ┆ 1 │ │ b ┆ 2 │ │ c ┆ 4 │ └─────┴─────┘ Tip: again, it is better to implement this with an expression: >>> ( ... df.lazy() ... .group_by("b", maintain_order=True) ... .agg(pl.col("a").sum()) ... .collect() ... ) # doctest: +IGNORE_RESULT Window function application using `over` will behave as a GroupBy context, with your function receiving individual window groups: >>> df = pl.DataFrame( ... { ... "key": ["x", "x", "y", "x", "y", "z"], ... "val": [1, 1, 1, 1, 1, 1], ... } ... ) >>> df.with_columns( ... scaled=pl.col("val") ... .implode() ... .map_elements(lambda s: s * len(s), return_dtype=pl.List(pl.Int64)) ... .explode() ... .over("key"), ... ).sort("key") shape: (6, 3) ┌─────┬─────┬────────┐ │ key ┆ val ┆ scaled │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞═════╪═════╪════════╡ │ x ┆ 1 ┆ 3 │ │ x ┆ 1 ┆ 3 │ │ x ┆ 1 ┆ 3 │ │ y ┆ 1 ┆ 2 │ │ y ┆ 1 ┆ 2 │ │ z ┆ 1 ┆ 1 │ └─────┴─────┴────────┘ Note that this function would *also* be better-implemented natively: >>> df.with_columns( ... scaled=(pl.col("val") * pl.col("val").count()).over("key"), ... ).sort("key") # doctest: +IGNORE_RESULT """ if strategy == "threading": issue_unstable_warning( "the 'threading' strategy for `map_elements` is considered unstable." ) # input x: Series of type list containing the group values from polars._utils.udfs import warn_on_inefficient_map root_names = self.meta.root_names() if len(root_names) > 0: warn_on_inefficient_map(function, columns=root_names, map_target="expr") if pass_name: def wrap_f(x: Series, **kwargs: Any) -> Series: # pragma: no cover return_dtype = kwargs["return_dtype"] def inner(s: Series | Any) -> Series: # pragma: no cover if isinstance(s, pl.Series): s = s.alias(x.name) return function(s) with warnings.catch_warnings(): warnings.simplefilter("ignore", PolarsInefficientMapWarning) return x.map_elements( inner, return_dtype=return_dtype, skip_nulls=skip_nulls ) else: def wrap_f(x: Series, **kwargs: Any) -> Series: # pragma: no cover return_dtype = kwargs["return_dtype"] with warnings.catch_warnings(): warnings.simplefilter("ignore", PolarsInefficientMapWarning) return x.map_elements( function, return_dtype=return_dtype, skip_nulls=skip_nulls ) if strategy == "thread_local": return self.map_batches( wrap_f, agg_list=False, return_dtype=return_dtype, returns_scalar=False, is_elementwise=True, ) elif strategy == "threading": def wrap_threading(x: Series) -> Series: def get_lazy_promise(df: DataFrame) -> LazyFrame: return df.lazy().select( F.col("x").map_batches( wrap_f, agg_list=False, return_dtype=return_dtype, returns_scalar=False, ) ) df = x.to_frame("x") if x.len() == 0: return get_lazy_promise(df).collect().to_series() n_threads = thread_pool_size() chunk_size = x.len() // n_threads remainder = x.len() % n_threads if chunk_size == 0: chunk_sizes = [1 for _ in range(remainder)] else: chunk_sizes = [ chunk_size + 1 if i < remainder else chunk_size for i in range(n_threads) ] # create partitions with LazyFrames # these are promises on a computation partitions = [] b = 0 for step in chunk_sizes: a = b b = b + step partition_df = df[a:b, :] partitions.append(get_lazy_promise(partition_df)) out = [df.to_series() for df in F.collect_all(partitions)] return F.concat(out, rechunk=False) return self.map_batches( wrap_threading, agg_list=False, return_dtype=return_dtype, returns_scalar=False, is_elementwise=True, ) else: msg = f"strategy {strategy!r} is not supported" raise ValueError(msg) def flatten(self) -> Expr: """ Flatten a list or string column. Alias for :func:`Expr.list.explode`. Examples -------- >>> df = pl.DataFrame( ... { ... "group": ["a", "b", "b"], ... "values": [[1, 2], [2, 3], [4]], ... } ... ) >>> df.group_by("group").agg(pl.col("values").flatten()) # doctest: +SKIP shape: (2, 2) ┌───────┬───────────┐ │ group ┆ values │ │ --- ┆ --- │ │ str ┆ list[i64] │ ╞═══════╪═══════════╡ │ a ┆ [1, 2] │ │ b ┆ [2, 3, 4] │ └───────┴───────────┘ """ return self.explode(empty_as_null=True, keep_nulls=True) def explode(self, *, empty_as_null: bool = True, keep_nulls: bool = True) -> Expr: """ Explode a list expression. This means that every item is expanded to a new row. Parameters ---------- empty_as_null Explode an empty list/array into a `null`. keep_nulls Explode a `null` list/array into a `null`. Returns ------- Expr Expression with the data type of the list elements. See Also -------- Expr.list.explode : Explode a list column. Examples -------- >>> df = pl.DataFrame( ... { ... "group": ["a", "b"], ... "values": [ ... [1, 2], ... [3, 4], ... ], ... } ... ) >>> df.select(pl.col("values").explode()) shape: (4, 1) ┌────────┐ │ values │ │ --- │ │ i64 │ ╞════════╡ │ 1 │ │ 2 │ │ 3 │ │ 4 │ └────────┘ """ return wrap_expr( self._pyexpr.explode(empty_as_null=empty_as_null, keep_nulls=keep_nulls) ) def implode(self) -> Expr: """ Aggregate values into a list. The returned list itself is a scalar value of `list` dtype. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, 3], ... "b": [4, 5, 6], ... } ... ) >>> df.select(pl.all().implode()) shape: (1, 2) ┌───────────┬───────────┐ │ a ┆ b │ │ --- ┆ --- │ │ list[i64] ┆ list[i64] │ ╞═══════════╪═══════════╡ │ [1, 2, 3] ┆ [4, 5, 6] │ └───────────┴───────────┘ """ return wrap_expr(self._pyexpr.implode()) def gather_every(self, n: int, offset: int = 0) -> Expr: """ Take every nth value in the Series and return as a new Series. Parameters ---------- n Gather every *n*-th row. offset Starting index. Examples -------- >>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5, 6, 7, 8, 9]}) >>> df.select(pl.col("foo").gather_every(3)) shape: (3, 1) ┌─────┐ │ foo │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 4 │ │ 7 │ └─────┘ >>> df.select(pl.col("foo").gather_every(3, offset=1)) shape: (3, 1) ┌─────┐ │ foo │ │ --- │ │ i64 │ ╞═════╡ │ 2 │ │ 5 │ │ 8 │ └─────┘ """ return wrap_expr(self._pyexpr.gather_every(n, offset)) def head(self, n: int | Expr = 10) -> Expr: """ Get the first `n` rows. Parameters ---------- n Number of rows to return. Examples -------- >>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5, 6, 7]}) >>> df.select(pl.col("foo").head(3)) shape: (3, 1) ┌─────┐ │ foo │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ │ 3 │ └─────┘ """ return self.slice(0, n) def tail(self, n: int | Expr = 10) -> Expr: """ Get the last `n` rows. Parameters ---------- n Number of rows to return. Examples -------- >>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5, 6, 7]}) >>> df.select(pl.col("foo").tail(3)) shape: (3, 1) ┌─────┐ │ foo │ │ --- │ │ i64 │ ╞═════╡ │ 5 │ │ 6 │ │ 7 │ └─────┘ """ # This cast enables tail with expressions that return unsigned integers, # for which negate otherwise raises InvalidOperationError. offset = -( wrap_expr(parse_into_expression(n)).cast( Int64, strict=False, wrap_numerical=True ) ) return self.slice(offset, n) def limit(self, n: int | Expr = 10) -> Expr: """ Get the first `n` rows (alias for :func:`Expr.head`). Parameters ---------- n Number of rows to return. Examples -------- >>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5, 6, 7]}) >>> df.select(pl.col("foo").limit(3)) shape: (3, 1) ┌─────┐ │ foo │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ │ 3 │ └─────┘ """ return self.head(n) def and_(self, *others: Any) -> Expr: """ Method equivalent of bitwise "and" operator `expr & other & ...`. This has the effect of combining logical boolean expressions, but operates bitwise on integers. Parameters ---------- *others One or more integer or boolean expressions to evaluate/combine. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [5, 6, 7, 4, 8], ... "y": [1.5, 2.5, 1.0, 4.0, -5.75], ... "z": [-9, 2, -1, 4, 8], ... } ... ) Combine logical "and" conditions: >>> df.select( ... (pl.col("x") >= pl.col("z")) ... .and_( ... pl.col("y") >= pl.col("z"), ... pl.col("y") == pl.col("y"), ... pl.col("z") <= pl.col("x"), ... pl.col("y") != pl.col("x"), ... ) ... .alias("all") ... ) shape: (5, 1) ┌───────┐ │ all │ │ --- │ │ bool │ ╞═══════╡ │ true │ │ true │ │ true │ │ false │ │ false │ └───────┘ Bitwise "and" operation on integer columns: >>> df.select("x", "z", x_and_z=pl.col("x").and_(pl.col("z"))) shape: (5, 3) ┌─────┬─────┬─────────┐ │ x ┆ z ┆ x_and_z │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════════╡ │ 5 ┆ -9 ┆ 5 │ │ 6 ┆ 2 ┆ 2 │ │ 7 ┆ -1 ┆ 7 │ │ 4 ┆ 4 ┆ 4 │ │ 8 ┆ 8 ┆ 8 │ └─────┴─────┴─────────┘ """ return reduce(operator.and_, (self, *others)) def or_(self, *others: Any) -> Expr: """ Method equivalent of bitwise "or" operator `expr | other | ...`. This has the effect of combining logical boolean expressions, but operates bitwise on integers. Parameters ---------- *others One or more integer or boolean expressions to evaluate/combine. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [5, 6, 7, 4, 8], ... "y": [1.5, 2.5, 1.0, 4.0, -5.75], ... "z": [-9, 2, -1, 4, 8], ... } ... ) Combine logical "or" conditions: >>> df.select( ... (pl.col("x") == pl.col("y")) ... .or_( ... pl.col("x") == pl.col("y"), ... pl.col("y") == pl.col("z"), ... pl.col("y").cast(int) == pl.col("z"), ... ) ... .alias("any") ... ) shape: (5, 1) ┌───────┐ │ any │ │ --- │ │ bool │ ╞═══════╡ │ false │ │ true │ │ false │ │ true │ │ false │ └───────┘ Bitwise "or" operation on integer columns: >>> df.select("x", "z", x_or_z=pl.col("x").or_(pl.col("z"))) shape: (5, 3) ┌─────┬─────┬────────┐ │ x ┆ z ┆ x_or_z │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪════════╡ │ 5 ┆ -9 ┆ -9 │ │ 6 ┆ 2 ┆ 6 │ │ 7 ┆ -1 ┆ -1 │ │ 4 ┆ 4 ┆ 4 │ │ 8 ┆ 8 ┆ 8 │ └─────┴─────┴────────┘ """ return reduce(operator.or_, (self,) + others) def eq(self, other: Any) -> Expr: """ Method equivalent of equality operator `expr == other`. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [1.0, 2.0, float("nan"), 4.0], ... "y": [2.0, 2.0, float("nan"), 4.0], ... } ... ) >>> df.with_columns( ... pl.col("x").eq(pl.col("y")).alias("x == y"), ... ) shape: (4, 3) ┌─────┬─────┬────────┐ │ x ┆ y ┆ x == y │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool │ ╞═════╪═════╪════════╡ │ 1.0 ┆ 2.0 ┆ false │ │ 2.0 ┆ 2.0 ┆ true │ │ NaN ┆ NaN ┆ true │ │ 4.0 ┆ 4.0 ┆ true │ └─────┴─────┴────────┘ """ return self.__eq__(other) def eq_missing(self, other: Any) -> Expr: """ Method equivalent of equality operator `expr == other` where `None == None`. This differs from default `eq` where null values are propagated. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [1.0, 2.0, float("nan"), 4.0, None, None], ... "y": [2.0, 2.0, float("nan"), 4.0, 5.0, None], ... } ... ) >>> df.with_columns( ... pl.col("x").eq(pl.col("y")).alias("x eq y"), ... pl.col("x").eq_missing(pl.col("y")).alias("x eq_missing y"), ... ) shape: (6, 4) ┌──────┬──────┬────────┬────────────────┐ │ x ┆ y ┆ x eq y ┆ x eq_missing y │ │ --- ┆ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool ┆ bool │ ╞══════╪══════╪════════╪════════════════╡ │ 1.0 ┆ 2.0 ┆ false ┆ false │ │ 2.0 ┆ 2.0 ┆ true ┆ true │ │ NaN ┆ NaN ┆ true ┆ true │ │ 4.0 ┆ 4.0 ┆ true ┆ true │ │ null ┆ 5.0 ┆ null ┆ false │ │ null ┆ null ┆ null ┆ true │ └──────┴──────┴────────┴────────────────┘ """ other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.eq_missing(other_pyexpr)) def ge(self, other: Any) -> Expr: """ Method equivalent of "greater than or equal" operator `expr >= other`. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [5.0, 4.0, float("nan"), 2.0], ... "y": [5.0, 3.0, float("nan"), 1.0], ... } ... ) >>> df.with_columns( ... pl.col("x").ge(pl.col("y")).alias("x >= y"), ... ) shape: (4, 3) ┌─────┬─────┬────────┐ │ x ┆ y ┆ x >= y │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool │ ╞═════╪═════╪════════╡ │ 5.0 ┆ 5.0 ┆ true │ │ 4.0 ┆ 3.0 ┆ true │ │ NaN ┆ NaN ┆ true │ │ 2.0 ┆ 1.0 ┆ true │ └─────┴─────┴────────┘ """ return self.__ge__(other) def gt(self, other: Any) -> Expr: """ Method equivalent of "greater than" operator `expr > other`. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [5.0, 4.0, float("nan"), 2.0], ... "y": [5.0, 3.0, float("nan"), 1.0], ... } ... ) >>> df.with_columns( ... pl.col("x").gt(pl.col("y")).alias("x > y"), ... ) shape: (4, 3) ┌─────┬─────┬───────┐ │ x ┆ y ┆ x > y │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool │ ╞═════╪═════╪═══════╡ │ 5.0 ┆ 5.0 ┆ false │ │ 4.0 ┆ 3.0 ┆ true │ │ NaN ┆ NaN ┆ false │ │ 2.0 ┆ 1.0 ┆ true │ └─────┴─────┴───────┘ """ return self.__gt__(other) def le(self, other: Any) -> Expr: """ Method equivalent of "less than or equal" operator `expr <= other`. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [5.0, 4.0, float("nan"), 0.5], ... "y": [5.0, 3.5, float("nan"), 2.0], ... } ... ) >>> df.with_columns( ... pl.col("x").le(pl.col("y")).alias("x <= y"), ... ) shape: (4, 3) ┌─────┬─────┬────────┐ │ x ┆ y ┆ x <= y │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool │ ╞═════╪═════╪════════╡ │ 5.0 ┆ 5.0 ┆ true │ │ 4.0 ┆ 3.5 ┆ false │ │ NaN ┆ NaN ┆ true │ │ 0.5 ┆ 2.0 ┆ true │ └─────┴─────┴────────┘ """ return self.__le__(other) def lt(self, other: Any) -> Expr: """ Method equivalent of "less than" operator `expr < other`. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [1.0, 2.0, float("nan"), 3.0], ... "y": [2.0, 2.0, float("nan"), 4.0], ... } ... ) >>> df.with_columns( ... pl.col("x").lt(pl.col("y")).alias("x < y"), ... ) shape: (4, 3) ┌─────┬─────┬───────┐ │ x ┆ y ┆ x < y │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool │ ╞═════╪═════╪═══════╡ │ 1.0 ┆ 2.0 ┆ true │ │ 2.0 ┆ 2.0 ┆ false │ │ NaN ┆ NaN ┆ false │ │ 3.0 ┆ 4.0 ┆ true │ └─────┴─────┴───────┘ """ return self.__lt__(other) def ne(self, other: Any) -> Expr: """ Method equivalent of inequality operator `expr != other`. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [1.0, 2.0, float("nan"), 4.0], ... "y": [2.0, 2.0, float("nan"), 4.0], ... } ... ) >>> df.with_columns( ... pl.col("x").ne(pl.col("y")).alias("x != y"), ... ) shape: (4, 3) ┌─────┬─────┬────────┐ │ x ┆ y ┆ x != y │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool │ ╞═════╪═════╪════════╡ │ 1.0 ┆ 2.0 ┆ true │ │ 2.0 ┆ 2.0 ┆ false │ │ NaN ┆ NaN ┆ false │ │ 4.0 ┆ 4.0 ┆ false │ └─────┴─────┴────────┘ """ return self.__ne__(other) def ne_missing(self, other: Any) -> Expr: """ Method equivalent of equality operator `expr != other` where `None == None`. This differs from default `ne` where null values are propagated. Parameters ---------- other A literal or expression value to compare with. Examples -------- >>> df = pl.DataFrame( ... data={ ... "x": [1.0, 2.0, float("nan"), 4.0, None, None], ... "y": [2.0, 2.0, float("nan"), 4.0, 5.0, None], ... } ... ) >>> df.with_columns( ... pl.col("x").ne(pl.col("y")).alias("x ne y"), ... pl.col("x").ne_missing(pl.col("y")).alias("x ne_missing y"), ... ) shape: (6, 4) ┌──────┬──────┬────────┬────────────────┐ │ x ┆ y ┆ x ne y ┆ x ne_missing y │ │ --- ┆ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool ┆ bool │ ╞══════╪══════╪════════╪════════════════╡ │ 1.0 ┆ 2.0 ┆ true ┆ true │ │ 2.0 ┆ 2.0 ┆ false ┆ false │ │ NaN ┆ NaN ┆ false ┆ false │ │ 4.0 ┆ 4.0 ┆ false ┆ false │ │ null ┆ 5.0 ┆ null ┆ true │ │ null ┆ null ┆ null ┆ false │ └──────┴──────┴────────┴────────────────┘ """ other_pyexpr = parse_into_expression(other, str_as_lit=True) return wrap_expr(self._pyexpr.neq_missing(other_pyexpr)) def add(self, other: Any) -> Expr: """ Method equivalent of addition operator `expr + other`. Parameters ---------- other numeric or string value; accepts expression input. Examples -------- >>> df = pl.DataFrame({"x": [1, 2, 3, 4, 5]}) >>> df.with_columns( ... pl.col("x").add(2).alias("x+int"), ... pl.col("x").add(pl.col("x").cum_prod()).alias("x+expr"), ... ) shape: (5, 3) ┌─────┬───────┬────────┐ │ x ┆ x+int ┆ x+expr │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═══════╪════════╡ │ 1 ┆ 3 ┆ 2 │ │ 2 ┆ 4 ┆ 4 │ │ 3 ┆ 5 ┆ 9 │ │ 4 ┆ 6 ┆ 28 │ │ 5 ┆ 7 ┆ 125 │ └─────┴───────┴────────┘ >>> df = pl.DataFrame( ... {"x": ["a", "d", "g"], "y": ["b", "e", "h"], "z": ["c", "f", "i"]} ... ) >>> df.with_columns(pl.col("x").add(pl.col("y")).add(pl.col("z")).alias("xyz")) shape: (3, 4) ┌─────┬─────┬─────┬─────┐ │ x ┆ y ┆ z ┆ xyz │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ str ┆ str ┆ str │ ╞═════╪═════╪═════╪═════╡ │ a ┆ b ┆ c ┆ abc │ │ d ┆ e ┆ f ┆ def │ │ g ┆ h ┆ i ┆ ghi │ └─────┴─────┴─────┴─────┘ """ return self.__add__(other) def floordiv(self, other: Any) -> Expr: """ Method equivalent of integer division operator `expr // other`. Parameters ---------- other Numeric literal or expression value. See Also -------- truediv Examples -------- >>> df = pl.DataFrame({"x": [1, 2, 3, 4, 5]}) >>> df.with_columns( ... pl.col("x").truediv(2).alias("x/2"), ... pl.col("x").floordiv(2).alias("x//2"), ... ) shape: (5, 3) ┌─────┬─────┬──────┐ │ x ┆ x/2 ┆ x//2 │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ i64 │ ╞═════╪═════╪══════╡ │ 1 ┆ 0.5 ┆ 0 │ │ 2 ┆ 1.0 ┆ 1 │ │ 3 ┆ 1.5 ┆ 1 │ │ 4 ┆ 2.0 ┆ 2 │ │ 5 ┆ 2.5 ┆ 2 │ └─────┴─────┴──────┘ Note that Polars' `floordiv` is subtly different from Python's floor division. For example, consider 6.0 floor-divided by 0.1. Python gives: >>> 6.0 // 0.1 59.0 because `0.1` is not represented internally as that exact value, but a slightly larger value. So the result of the division is slightly less than 60, meaning the flooring operation returns 59.0. Polars instead first does the floating-point division, resulting in a floating-point value of 60.0, and then performs the flooring operation using :any:`floor`: >>> df = pl.DataFrame({"x": [6.0, 6.03]}) >>> df.with_columns( ... pl.col("x").truediv(0.1).alias("x/0.1"), ... ).with_columns( ... pl.col("x/0.1").floor().alias("x/0.1 floor"), ... ) shape: (2, 3) ┌──────┬───────┬─────────────┐ │ x ┆ x/0.1 ┆ x/0.1 floor │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ f64 │ ╞══════╪═══════╪═════════════╡ │ 6.0 ┆ 60.0 ┆ 60.0 │ │ 6.03 ┆ 60.3 ┆ 60.0 │ └──────┴───────┴─────────────┘ yielding the more intuitive result 60.0. The row with x = 6.03 is included to demonstrate the effect of the flooring operation. `floordiv` combines those two steps to give the same result with one expression: >>> df.with_columns( ... pl.col("x").floordiv(0.1).alias("x//0.1"), ... ) shape: (2, 2) ┌──────┬────────┐ │ x ┆ x//0.1 │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞══════╪════════╡ │ 6.0 ┆ 60.0 │ │ 6.03 ┆ 60.0 │ └──────┴────────┘ """ return self.__floordiv__(other) def mod(self, other: Any) -> Expr: """ Method equivalent of modulus operator `expr % other`. Parameters ---------- other Numeric literal or expression value. Examples -------- >>> df = pl.DataFrame({"x": [0, 1, 2, 3, 4]}) >>> df.with_columns(pl.col("x").mod(2).alias("x%2")) shape: (5, 2) ┌─────┬─────┐ │ x ┆ x%2 │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 0 ┆ 0 │ │ 1 ┆ 1 │ │ 2 ┆ 0 │ │ 3 ┆ 1 │ │ 4 ┆ 0 │ └─────┴─────┘ """ return self.__mod__(other) def mul(self, other: Any) -> Expr: """ Method equivalent of multiplication operator `expr * other`. Parameters ---------- other Numeric literal or expression value. Examples -------- >>> df = pl.DataFrame({"x": [1, 2, 4, 8, 16]}) >>> df.with_columns( ... pl.col("x").mul(2).alias("x*2"), ... pl.col("x").mul(pl.col("x").log(2)).alias("x * xlog2"), ... ) shape: (5, 3) ┌─────┬─────┬───────────┐ │ x ┆ x*2 ┆ x * xlog2 │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ f64 │ ╞═════╪═════╪═══════════╡ │ 1 ┆ 2 ┆ 0.0 │ │ 2 ┆ 4 ┆ 2.0 │ │ 4 ┆ 8 ┆ 8.0 │ │ 8 ┆ 16 ┆ 24.0 │ │ 16 ┆ 32 ┆ 64.0 │ └─────┴─────┴───────────┘ """ return self.__mul__(other) def sub(self, other: Any) -> Expr: """ Method equivalent of subtraction operator `expr - other`. Parameters ---------- other Numeric literal or expression value. Examples -------- >>> df = pl.DataFrame({"x": [0, 1, 2, 3, 4]}) >>> df.with_columns( ... pl.col("x").sub(2).alias("x-2"), ... pl.col("x").sub(pl.col("x").cum_sum()).alias("x-expr"), ... ) shape: (5, 3) ┌─────┬─────┬────────┐ │ x ┆ x-2 ┆ x-expr │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪════════╡ │ 0 ┆ -2 ┆ 0 │ │ 1 ┆ -1 ┆ 0 │ │ 2 ┆ 0 ┆ -1 │ │ 3 ┆ 1 ┆ -3 │ │ 4 ┆ 2 ┆ -6 │ └─────┴─────┴────────┘ """ return self.__sub__(other) def neg(self) -> Expr: """ Method equivalent of unary minus operator `-expr`. Examples -------- >>> df = pl.DataFrame({"a": [-1, 0, 2, None]}) >>> df.with_columns(pl.col("a").neg()) shape: (4, 1) ┌──────┐ │ a │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ 0 │ │ -2 │ │ null │ └──────┘ """ return self.__neg__() def truediv(self, other: Any) -> Expr: """ Method equivalent of float division operator `expr / other`. Parameters ---------- other Numeric literal or expression value. Notes ----- Zero-division behaviour follows IEEE-754: 0/0: Invalid operation - mathematically undefined, returns NaN. n/0: On finite operands gives an exact infinite result, eg: ±infinity. See Also -------- floordiv Examples -------- >>> df = pl.DataFrame( ... data={"x": [-2, -1, 0, 1, 2], "y": [0.5, 0.0, 0.0, -4.0, -0.5]} ... ) >>> df.with_columns( ... pl.col("x").truediv(2).alias("x/2"), ... pl.col("x").truediv(pl.col("y")).alias("x/y"), ... ) shape: (5, 4) ┌─────┬──────┬──────┬───────┐ │ x ┆ y ┆ x/2 ┆ x/y │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ f64 ┆ f64 │ ╞═════╪══════╪══════╪═══════╡ │ -2 ┆ 0.5 ┆ -1.0 ┆ -4.0 │ │ -1 ┆ 0.0 ┆ -0.5 ┆ -inf │ │ 0 ┆ 0.0 ┆ 0.0 ┆ NaN │ │ 1 ┆ -4.0 ┆ 0.5 ┆ -0.25 │ │ 2 ┆ -0.5 ┆ 1.0 ┆ -4.0 │ └─────┴──────┴──────┴───────┘ """ return self.__truediv__(other) def pow(self, exponent: IntoExprColumn | int | float) -> Expr: """ Method equivalent of exponentiation operator `expr ** exponent`. If the exponent is float, the result follows the dtype of exponent. Otherwise, it follows dtype of base. Parameters ---------- exponent Numeric literal or expression exponent value. Examples -------- >>> df = pl.DataFrame({"x": [1, 2, 4, 8]}) >>> df.with_columns( ... pl.col("x").pow(3).alias("cube"), ... pl.col("x").pow(pl.col("x").log(2)).alias("x ** xlog2"), ... ) shape: (4, 3) ┌─────┬──────┬────────────┐ │ x ┆ cube ┆ x ** xlog2 │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ f64 │ ╞═════╪══════╪════════════╡ │ 1 ┆ 1 ┆ 1.0 │ │ 2 ┆ 8 ┆ 2.0 │ │ 4 ┆ 64 ┆ 16.0 │ │ 8 ┆ 512 ┆ 512.0 │ └─────┴──────┴────────────┘ Raising an integer to a positive integer results in an integer - in order to raise to a negative integer, you can cast either the base or the exponent to float first: >>> df.with_columns( ... x_squared=pl.col("x").pow(2), ... x_inverse=pl.col("x").pow(-1.0), ... ) shape: (4, 3) ┌─────┬───────────┬───────────┐ │ x ┆ x_squared ┆ x_inverse │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ f64 │ ╞═════╪═══════════╪═══════════╡ │ 1 ┆ 1 ┆ 1.0 │ │ 2 ┆ 4 ┆ 0.5 │ │ 4 ┆ 16 ┆ 0.25 │ │ 8 ┆ 64 ┆ 0.125 │ └─────┴───────────┴───────────┘ """ return self.__pow__(exponent) def xor(self, other: Any) -> Expr: """ Method equivalent of bitwise exclusive-or operator `expr ^ other`. Parameters ---------- other Integer or boolean value; accepts expression input. Examples -------- >>> df = pl.DataFrame( ... {"x": [True, False, True, False], "y": [True, True, False, False]} ... ) >>> df.with_columns(pl.col("x").xor(pl.col("y")).alias("x ^ y")) shape: (4, 3) ┌───────┬───────┬───────┐ │ x ┆ y ┆ x ^ y │ │ --- ┆ --- ┆ --- │ │ bool ┆ bool ┆ bool │ ╞═══════╪═══════╪═══════╡ │ true ┆ true ┆ false │ │ false ┆ true ┆ true │ │ true ┆ false ┆ true │ │ false ┆ false ┆ false │ └───────┴───────┴───────┘ >>> def binary_string(n: int) -> str: ... return bin(n)[2:].zfill(8) >>> >>> df = pl.DataFrame( ... data={"x": [10, 8, 250, 66], "y": [1, 2, 3, 4]}, ... schema={"x": pl.UInt8, "y": pl.UInt8}, ... ) >>> df.with_columns( ... pl.col("x") ... .map_elements(binary_string, return_dtype=pl.String) ... .alias("bin_x"), ... pl.col("y") ... .map_elements(binary_string, return_dtype=pl.String) ... .alias("bin_y"), ... pl.col("x").xor(pl.col("y")).alias("xor_xy"), ... pl.col("x") ... .xor(pl.col("y")) ... .map_elements(binary_string, return_dtype=pl.String) ... .alias("bin_xor_xy"), ... ) shape: (4, 6) ┌─────┬─────┬──────────┬──────────┬────────┬────────────┐ │ x ┆ y ┆ bin_x ┆ bin_y ┆ xor_xy ┆ bin_xor_xy │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ u8 ┆ u8 ┆ str ┆ str ┆ u8 ┆ str │ ╞═════╪═════╪══════════╪══════════╪════════╪════════════╡ │ 10 ┆ 1 ┆ 00001010 ┆ 00000001 ┆ 11 ┆ 00001011 │ │ 8 ┆ 2 ┆ 00001000 ┆ 00000010 ┆ 10 ┆ 00001010 │ │ 250 ┆ 3 ┆ 11111010 ┆ 00000011 ┆ 249 ┆ 11111001 │ │ 66 ┆ 4 ┆ 01000010 ┆ 00000100 ┆ 70 ┆ 01000110 │ └─────┴─────┴──────────┴──────────┴────────┴────────────┘ """ return self.__xor__(other) def is_in( self, other: Expr | Collection[Any] | Series, *, nulls_equal: bool = False, ) -> Expr: """ Check if elements of this expression are present in the other Series. Parameters ---------- other Series or sequence of primitive type. nulls_equal : bool, default False If True, treat null as a distinct value. Null values will not propagate. Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame( ... {"sets": [[1, 2, 3], [1, 2], [9, 10]], "optional_members": [1, 2, 3]} ... ) >>> df.with_columns(contains=pl.col("optional_members").is_in("sets")) shape: (3, 3) ┌───────────┬──────────────────┬──────────┐ │ sets ┆ optional_members ┆ contains │ │ --- ┆ --- ┆ --- │ │ list[i64] ┆ i64 ┆ bool │ ╞═══════════╪══════════════════╪══════════╡ │ [1, 2, 3] ┆ 1 ┆ true │ │ [1, 2] ┆ 2 ┆ true │ │ [9, 10] ┆ 3 ┆ false │ └───────────┴──────────────────┴──────────┘ """ if isinstance(other, Collection) and not isinstance(other, (str, pl.Series)): other = list(other) # eg: set, frozenset, etc other_pyexpr = parse_into_expression(other) return wrap_expr(self._pyexpr.is_in(other_pyexpr, nulls_equal)) def repeat_by(self, by: pl.Series | Expr | str | int) -> Expr: """ Repeat the elements in this Series as specified in the given expression. The repeated elements are expanded into a `List`. Parameters ---------- by Numeric column that determines how often the values will be repeated. The column will be coerced to UInt32. Give this dtype to make the coercion a no-op. Returns ------- Expr Expression of data type :class:`List`, where the inner data type is equal to the original data type. Examples -------- >>> df = pl.DataFrame( ... { ... "a": ["x", "y", "z"], ... "n": [1, 2, 3], ... } ... ) >>> df.select(pl.col("a").repeat_by("n")) shape: (3, 1) ┌─────────────────┐ │ a │ │ --- │ │ list[str] │ ╞═════════════════╡ │ ["x"] │ │ ["y", "y"] │ │ ["z", "z", "z"] │ └─────────────────┘ """ by_pyexpr = parse_into_expression(by) return wrap_expr(self._pyexpr.repeat_by(by_pyexpr)) def is_between( self, lower_bound: IntoExpr, upper_bound: IntoExpr, closed: ClosedInterval = "both", ) -> Expr: """ Check if this expression is between the given lower and upper bounds. Parameters ---------- lower_bound Lower bound value. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals. upper_bound Upper bound value. Accepts expression input. Strings are parsed as column names, other non-expression inputs are parsed as literals. closed : {'both', 'left', 'right', 'none'} Define which sides of the interval are closed (inclusive). Notes ----- If the value of the `lower_bound` is greater than that of the `upper_bound` then the result will be False, as no value can satisfy the condition. Returns ------- Expr Expression of data type :class:`Boolean`. Examples -------- >>> df = pl.DataFrame({"num": [1, 2, 3, 4, 5]}) >>> df.with_columns(pl.col("num").is_between(2, 4).alias("is_between")) shape: (5, 2) ┌─────┬────────────┐ │ num ┆ is_between │ │ --- ┆ --- │ │ i64 ┆ bool │ ╞═════╪════════════╡ │ 1 ┆ false │ │ 2 ┆ true │ │ 3 ┆ true │ │ 4 ┆ true │ │ 5 ┆ false │ └─────┴────────────┘ Use the `closed` argument to include or exclude the values at the bounds: >>> df.with_columns( ... pl.col("num").is_between(2, 4, closed="left").alias("is_between") ... ) shape: (5, 2) ┌─────┬────────────┐ │ num ┆ is_between │ │ --- ┆ --- │ │ i64 ┆ bool │ ╞═════╪════════════╡ │ 1 ┆ false │ │ 2 ┆ true │ │ 3 ┆ true │ │ 4 ┆ false │ │ 5 ┆ false │ └─────┴────────────┘ You can also use strings as well as numeric/temporal values (note: ensure that string literals are wrapped with `lit` so as not to conflate them with column names): >>> df = pl.DataFrame({"a": ["a", "b", "c", "d", "e"]}) >>> df.with_columns( ... pl.col("a") ... .is_between(pl.lit("a"), pl.lit("c"), closed="both") ... .alias("is_between") ... ) shape: (5, 2) ┌─────┬────────────┐ │ a ┆ is_between │ │ --- ┆ --- │ │ str ┆ bool │ ╞═════╪════════════╡ │ a ┆ true │ │ b ┆ true │ │ c ┆ true │ │ d ┆ false │ │ e ┆ false │ └─────┴────────────┘ Use column expressions as lower/upper bounds, comparing to a literal value: >>> df = pl.DataFrame({"a": [1, 2, 3, 4, 5], "b": [5, 4, 3, 2, 1]}) >>> df.with_columns( ... pl.lit(3).is_between(pl.col("a"), pl.col("b")).alias("between_ab") ... ) shape: (5, 3) ┌─────┬─────┬────────────┐ │ a ┆ b ┆ between_ab │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ bool │ ╞═════╪═════╪════════════╡ │ 1 ┆ 5 ┆ true │ │ 2 ┆ 4 ┆ true │ │ 3 ┆ 3 ┆ true │ │ 4 ┆ 2 ┆ false │ │ 5 ┆ 1 ┆ false │ └─────┴─────┴────────────┘ """ lower_bound_pyexpr = parse_into_expression(lower_bound) upper_bound_pyexpr = parse_into_expression(upper_bound) return wrap_expr( self._pyexpr.is_between(lower_bound_pyexpr, upper_bound_pyexpr, closed) ) def is_close( self, other: IntoExpr, *, abs_tol: float = 0.0, rel_tol: float = 1e-09, nans_equal: bool = False, ) -> Expr: 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: .. math:: |a-b| \le max \{ \text{rel_tol} \cdot max \{ |a|, |b| \}, \text{abs_tol} \} Parameters ---------- other A literal or expression value 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 non-negative. nans_equal Whether NaN values should be considered equal. Returns ------- Expr Expression of data type :class:`Boolean`. Notes ----- The implementation of this method is symmetric and mirrors the behavior of :meth:`math.isclose`. Specifically note that this behavior is different to :meth:`numpy.isclose`. Examples -------- >>> df = pl.DataFrame({"a": [1.5, 2.0, 2.5], "b": [1.55, 2.2, 3.0]}) >>> df.with_columns(pl.col("a").is_close("b", abs_tol=0.1).alias("is_close")) shape: (3, 3) ┌─────┬──────┬──────────┐ │ a ┆ b ┆ is_close │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ bool │ ╞═════╪══════╪══════════╡ │ 1.5 ┆ 1.55 ┆ true │ │ 2.0 ┆ 2.2 ┆ false │ │ 2.5 ┆ 3.0 ┆ false │ └─────┴──────┴──────────┘ """ other_pyexpr = parse_into_expression(other) return wrap_expr( self._pyexpr.is_close(other_pyexpr, abs_tol, rel_tol, nans_equal) ) def hash( self, seed: int = 0, seed_1: int | None = None, seed_2: int | None = None, seed_3: int | None = None, ) -> Expr: """ Hash the elements in the selection. The hash value is of type `UInt64`. Parameters ---------- seed Random seed parameter. Defaults to 0. seed_1 Random seed parameter. Defaults to `seed` if not set. seed_2 Random seed parameter. Defaults to `seed` if not set. seed_3 Random seed parameter. Defaults to `seed` if not set. Notes ----- This implementation of `hash` does not guarantee stable results across different Polars versions. Its stability is only guaranteed within a single version. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [1, 2, None], ... "b": ["x", None, "z"], ... } ... ) >>> df.with_columns(pl.all().hash(10, 20, 30, 40)) # doctest: +IGNORE_RESULT shape: (3, 2) ┌──────────────────────┬──────────────────────┐ │ a ┆ b │ │ --- ┆ --- │ │ u64 ┆ u64 │ ╞══════════════════════╪══════════════════════╡ │ 9774092659964970114 ┆ 13614470193936745724 │ │ 1101441246220388612 ┆ 11638928888656214026 │ │ 11638928888656214026 ┆ 13382926553367784577 │ └──────────────────────┴──────────────────────┘ """ k0 = seed k1 = seed_1 if seed_1 is not None else seed k2 = seed_2 if seed_2 is not None else seed k3 = seed_3 if seed_3 is not None else seed return wrap_expr(self._pyexpr.hash(k0, k1, k2, k3)) def reinterpret(self, *, signed: bool = True) -> Expr: """ Reinterpret the underlying bits as a signed/unsigned integer. This operation is only allowed for 64bit integers. For lower bits integers, you can safely use that cast operation. Parameters ---------- signed If True, reinterpret as `pl.Int64`. Otherwise, reinterpret as `pl.UInt64`. Examples -------- >>> s = pl.Series("a", [1, 1, 2], dtype=pl.UInt64) >>> df = pl.DataFrame([s]) >>> df.select( ... [ ... pl.col("a").reinterpret(signed=True).alias("reinterpreted"), ... pl.col("a").alias("original"), ... ] ... ) shape: (3, 2) ┌───────────────┬──────────┐ │ reinterpreted ┆ original │ │ --- ┆ --- │ │ i64 ┆ u64 │ ╞═══════════════╪══════════╡ │ 1 ┆ 1 │ │ 1 ┆ 1 │ │ 2 ┆ 2 │ └───────────────┴──────────┘ """ return wrap_expr(self._pyexpr.reinterpret(signed)) def inspect(self, fmt: str = "{}") -> Expr: """ Print the value that this expression evaluates to and pass on the value. Examples -------- >>> df = pl.DataFrame({"foo": [1, 1, 2]}) >>> df.select(pl.col("foo").cum_sum().inspect("value is: {}").alias("bar")) value is: shape: (3,) Series: 'foo' [i64] [ 1 2 4 ] shape: (3, 1) ┌─────┐ │ bar │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ │ 4 │ └─────┘ """ def inspect(s: Series) -> Series: # pragma: no cover print(fmt.format(s)) return s return self.map_batches(inspect, return_dtype=F.dtype_of(self)) def interpolate(self, method: InterpolationMethod = "linear") -> Expr: """ Interpolate intermediate values. Nulls at the beginning and end of the series remain null. Parameters ---------- method : {'linear', 'nearest'} Interpolation method. Examples -------- Fill null values using linear interpolation. >>> df = pl.DataFrame( ... { ... "a": [1, None, 3], ... "b": [1.0, float("nan"), 3.0], ... } ... ) >>> df.select(pl.all().interpolate()) shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════╡ │ 1.0 ┆ 1.0 │ │ 2.0 ┆ NaN │ │ 3.0 ┆ 3.0 │ └─────┴─────┘ Fill null values using nearest interpolation. >>> df.select(pl.all().interpolate("nearest")) shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ f64 │ ╞═════╪═════╡ │ 1 ┆ 1.0 │ │ 3 ┆ NaN │ │ 3 ┆ 3.0 │ └─────┴─────┘ Regrid data to a new grid. >>> df_original_grid = pl.DataFrame( ... { ... "grid_points": [1, 3, 10], ... "values": [2.0, 6.0, 20.0], ... } ... ) # Interpolate from this to the new grid >>> df_new_grid = pl.DataFrame({"grid_points": range(1, 11)}) >>> df_new_grid.join( ... df_original_grid, on="grid_points", how="left", coalesce=True ... ).with_columns(pl.col("values").interpolate()) shape: (10, 2) ┌─────────────┬────────┐ │ grid_points ┆ values │ │ --- ┆ --- │ │ i64 ┆ f64 │ ╞═════════════╪════════╡ │ 1 ┆ 2.0 │ │ 2 ┆ 4.0 │ │ 3 ┆ 6.0 │ │ 4 ┆ 8.0 │ │ 5 ┆ 10.0 │ │ 6 ┆ 12.0 │ │ 7 ┆ 14.0 │ │ 8 ┆ 16.0 │ │ 9 ┆ 18.0 │ │ 10 ┆ 20.0 │ └─────────────┴────────┘ """ return wrap_expr(self._pyexpr.interpolate(method)) def interpolate_by(self, by: IntoExpr) -> Expr: """ Fill null values using interpolation based on another column. Nulls at the beginning and end of the series remain null. Parameters ---------- by Column to interpolate values based on. Examples -------- Fill null values using linear interpolation. >>> df = pl.DataFrame( ... { ... "a": [1, None, None, 3], ... "b": [1, 2, 7, 8], ... } ... ) >>> df.with_columns(a_interpolated=pl.col("a").interpolate_by("b")) shape: (4, 3) ┌──────┬─────┬────────────────┐ │ a ┆ b ┆ a_interpolated │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ f64 │ ╞══════╪═════╪════════════════╡ │ 1 ┆ 1 ┆ 1.0 │ │ null ┆ 2 ┆ 1.285714 │ │ null ┆ 7 ┆ 2.714286 │ │ 3 ┆ 8 ┆ 3.0 │ └──────┴─────┴────────────────┘ """ by_pyexpr = parse_into_expression(by) return wrap_expr(self._pyexpr.interpolate_by(by_pyexpr)) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_min_by( self, by: IntoExpr, window_size: timedelta | str, *, min_samples: int = 1, closed: ClosedInterval = "right", ) -> Expr: """ Apply a rolling min based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling min with the temporal windows closed on the right (default) >>> df_temporal.with_columns( ... rolling_row_min=pl.col("index").rolling_min_by("date", window_size="2h") ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_min │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ u32 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 1 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 2 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 3 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 19 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 20 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 21 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 22 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 23 │ └───────┴─────────────────────┴─────────────────┘ """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_min_by(by_pyexpr, window_size, min_samples, closed) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_max_by( self, by: IntoExpr, window_size: timedelta | str, *, min_samples: int = 1, closed: ClosedInterval = "right", ) -> Expr: """ Apply a rolling max based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling max with the temporal windows closed on the right (default) >>> df_temporal.with_columns( ... rolling_row_max=pl.col("index").rolling_max_by("date", window_size="2h") ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_max │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ u32 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 1 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 2 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 3 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 4 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 20 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 21 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 22 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 23 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 24 │ └───────┴─────────────────────┴─────────────────┘ Compute the rolling max with the closure of windows on both sides >>> df_temporal.with_columns( ... rolling_row_max=pl.col("index").rolling_max_by( ... "date", window_size="2h", closed="both" ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_max │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ u32 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 1 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 2 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 3 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 4 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 20 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 21 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 22 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 23 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 24 │ └───────┴─────────────────────┴─────────────────┘ """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_max_by(by_pyexpr, window_size, min_samples, closed) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_mean_by( self, by: IntoExpr, window_size: timedelta | str, *, min_samples: int = 1, closed: ClosedInterval = "right", ) -> Expr: """ Apply a rolling mean based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling mean with the temporal windows closed on the right (default) >>> df_temporal.with_columns( ... rolling_row_mean=pl.col("index").rolling_mean_by( ... "date", window_size="2h" ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬──────────────────┐ │ index ┆ date ┆ rolling_row_mean │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪══════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0.0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.5 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 1.5 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 2.5 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 3.5 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 19.5 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 20.5 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 21.5 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 22.5 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 23.5 │ └───────┴─────────────────────┴──────────────────┘ Compute the rolling mean with the closure of windows on both sides >>> df_temporal.with_columns( ... rolling_row_mean=pl.col("index").rolling_mean_by( ... "date", window_size="2h", closed="both" ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬──────────────────┐ │ index ┆ date ┆ rolling_row_mean │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪══════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0.0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.5 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 1.0 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 2.0 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 3.0 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 19.0 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 20.0 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 21.0 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 22.0 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 23.0 │ └───────┴─────────────────────┴──────────────────┘ """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_mean_by( by_pyexpr, window_size, min_samples, closed, ) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_sum_by( self, by: IntoExpr, window_size: timedelta | str, *, min_samples: int = 1, closed: ClosedInterval = "right", ) -> Expr: """ Apply a rolling sum based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling sum with the temporal windows closed on the right (default) >>> df_temporal.with_columns( ... rolling_row_sum=pl.col("index").rolling_sum_by("date", window_size="2h") ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_sum │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ u32 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 1 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 3 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 5 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 7 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 39 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 41 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 43 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 45 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 47 │ └───────┴─────────────────────┴─────────────────┘ Compute the rolling sum with the closure of windows on both sides >>> df_temporal.with_columns( ... rolling_row_sum=pl.col("index").rolling_sum_by( ... "date", window_size="2h", closed="both" ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_sum │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ u32 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 1 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 3 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 6 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 9 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 57 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 60 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 63 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 66 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 69 │ └───────┴─────────────────────┴─────────────────┘ """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_sum_by(by_pyexpr, window_size, min_samples, closed) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_std_by( self, by: IntoExpr, window_size: timedelta | str, *, min_samples: int = 1, closed: ClosedInterval = "right", ddof: int = 1, ) -> Expr: """ Compute a rolling standard deviation based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. ddof "Delta Degrees of Freedom": The divisor for a length N window is N - ddof Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling std with the temporal windows closed on the right (default) >>> df_temporal.with_columns( ... rolling_row_std=pl.col("index").rolling_std_by("date", window_size="2h") ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_std │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ null │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.707107 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 0.707107 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 0.707107 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 0.707107 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 0.707107 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 0.707107 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 0.707107 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 0.707107 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 0.707107 │ └───────┴─────────────────────┴─────────────────┘ Compute the rolling std with the closure of windows on both sides >>> df_temporal.with_columns( ... rolling_row_std=pl.col("index").rolling_std_by( ... "date", window_size="2h", closed="both" ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_std │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ null │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.707107 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 1.0 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 1.0 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 1.0 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 1.0 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 1.0 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 1.0 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 1.0 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 1.0 │ └───────┴─────────────────────┴─────────────────┘ """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_std_by( by_pyexpr, window_size, min_samples, closed, ddof, ) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_var_by( self, by: IntoExpr, window_size: timedelta | str, *, min_samples: int = 1, closed: ClosedInterval = "right", ddof: int = 1, ) -> Expr: """ Compute a rolling variance based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. ddof "Delta Degrees of Freedom": The divisor for a length N window is N - ddof Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling var with the temporal windows closed on the right (default) >>> df_temporal.with_columns( ... rolling_row_var=pl.col("index").rolling_var_by("date", window_size="2h") ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_var │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ null │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.5 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 0.5 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 0.5 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 0.5 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 0.5 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 0.5 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 0.5 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 0.5 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 0.5 │ └───────┴─────────────────────┴─────────────────┘ Compute the rolling var with the closure of windows on both sides >>> df_temporal.with_columns( ... rolling_row_var=pl.col("index").rolling_var_by( ... "date", window_size="2h", closed="both" ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬─────────────────┐ │ index ┆ date ┆ rolling_row_var │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪═════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ null │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.5 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 1.0 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 1.0 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 1.0 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 1.0 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 1.0 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 1.0 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 1.0 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 1.0 │ └───────┴─────────────────────┴─────────────────┘ """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_var_by( by_pyexpr, window_size, min_samples, closed, ddof, ) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_median_by( self, by: IntoExpr, window_size: timedelta | str, *, min_samples: int = 1, closed: ClosedInterval = "right", ) -> Expr: """ Compute a rolling median based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling median with the temporal windows closed on the right: >>> df_temporal.with_columns( ... rolling_row_median=pl.col("index").rolling_median_by( ... "date", window_size="2h" ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬────────────────────┐ │ index ┆ date ┆ rolling_row_median │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0.0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.5 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 1.5 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 2.5 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 3.5 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 19.5 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 20.5 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 21.5 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 22.5 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 23.5 │ └───────┴─────────────────────┴────────────────────┘ """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_median_by(by_pyexpr, window_size, min_samples, closed) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_quantile_by( self, by: IntoExpr, window_size: timedelta | str, *, quantile: float, interpolation: QuantileMethod = "nearest", min_samples: int = 1, closed: ClosedInterval = "right", ) -> Expr: """ Compute a rolling quantile based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). quantile Quantile between 0.0 and 1.0. interpolation : {'nearest', 'higher', 'lower', 'midpoint', 'linear', 'equiprobable'} Interpolation method. window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- Create a DataFrame with a datetime column and a row number column >>> from datetime import timedelta, datetime >>> start = datetime(2001, 1, 1) >>> stop = datetime(2001, 1, 2) >>> df_temporal = pl.DataFrame( ... {"date": pl.datetime_range(start, stop, "1h", eager=True)} ... ).with_row_index() >>> df_temporal shape: (25, 2) ┌───────┬─────────────────────┐ │ index ┆ date │ │ --- ┆ --- │ │ u32 ┆ datetime[μs] │ ╞═══════╪═════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 │ │ 1 ┆ 2001-01-01 01:00:00 │ │ 2 ┆ 2001-01-01 02:00:00 │ │ 3 ┆ 2001-01-01 03:00:00 │ │ 4 ┆ 2001-01-01 04:00:00 │ │ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 │ │ 21 ┆ 2001-01-01 21:00:00 │ │ 22 ┆ 2001-01-01 22:00:00 │ │ 23 ┆ 2001-01-01 23:00:00 │ │ 24 ┆ 2001-01-02 00:00:00 │ └───────┴─────────────────────┘ Compute the rolling quantile with the temporal windows closed on the right: >>> df_temporal.with_columns( ... rolling_row_quantile=pl.col("index").rolling_quantile_by( ... "date", window_size="2h", quantile=0.3 ... ) ... ) shape: (25, 3) ┌───────┬─────────────────────┬──────────────────────┐ │ index ┆ date ┆ rolling_row_quantile │ │ --- ┆ --- ┆ --- │ │ u32 ┆ datetime[μs] ┆ f64 │ ╞═══════╪═════════════════════╪══════════════════════╡ │ 0 ┆ 2001-01-01 00:00:00 ┆ 0.0 │ │ 1 ┆ 2001-01-01 01:00:00 ┆ 0.0 │ │ 2 ┆ 2001-01-01 02:00:00 ┆ 1.0 │ │ 3 ┆ 2001-01-01 03:00:00 ┆ 2.0 │ │ 4 ┆ 2001-01-01 04:00:00 ┆ 3.0 │ │ … ┆ … ┆ … │ │ 20 ┆ 2001-01-01 20:00:00 ┆ 19.0 │ │ 21 ┆ 2001-01-01 21:00:00 ┆ 20.0 │ │ 22 ┆ 2001-01-01 22:00:00 ┆ 21.0 │ │ 23 ┆ 2001-01-01 23:00:00 ┆ 22.0 │ │ 24 ┆ 2001-01-02 00:00:00 ┆ 23.0 │ └───────┴─────────────────────┴──────────────────────┘ """ # noqa: W505 window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_quantile_by( by_pyexpr, quantile, interpolation, window_size, min_samples, closed, ) ) @unstable() def rolling_rank_by( self, by: IntoExpr, window_size: timedelta | str, method: RankMethod = "average", *, seed: int | None = None, min_samples: int = 1, closed: ClosedInterval = "right", ) -> Expr: """ Compute a rolling rank based on another column. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Given a `by` column `<t_0, t_1, ..., t_n>`, then `closed="right"` (the default) means the windows will be: - (t_0 - window_size, t_0] - (t_1 - window_size, t_1] - ... - (t_n - window_size, t_n] Parameters ---------- by Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type (note that the integral ones require using `'i'` in `window size`). window_size The length of the window. Can be a dynamic temporal size indicated by a timedelta or the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 calendar day) - 1w (1 calendar week) - 1mo (1 calendar month) - 1q (1 calendar quarter) - 1y (1 calendar year) - 1i (1 index count) By "calendar day", we mean the corresponding time on the next day (which may not be 24 hours, due to daylight savings). Similarly for "calendar week", "calendar month", "calendar quarter", and "calendar year". method : {'average', 'min', 'max', 'dense', 'random'} 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. - 'random' : Choose a random rank for each value in a tie. seed Random seed used when `method='random'`. If set to None (default), a random seed is generated for each rolling rank operation. min_samples The number of values in the window that should be non-null before computing a result. closed : {'left', 'right', 'both', 'none'} Define which sides of the temporal interval are closed (inclusive), defaults to `'right'`. Returns ------- Expr An Expr of data :class:`.Float64` if `method` is `"average"` or, the index size (see :func:`.get_index_type()`) otherwise. """ window_size = _prepare_rolling_by_window_args(window_size) by_pyexpr = parse_into_expression(by) return wrap_expr( self._pyexpr.rolling_rank_by( by_pyexpr, window_size, method, seed, min_samples, closed, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_min( self, window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Apply a rolling min (moving min) over the values in this array. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. The resulting values will be aggregated to their min. The window at a given row will include the row itself, and the `window_size - 1` elements before it. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window. 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`. center Set the labels at the center of the window. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_min=pl.col("A").rolling_min(window_size=2), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_min │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.0 │ │ 3.0 ┆ 2.0 │ │ 4.0 ┆ 3.0 │ │ 5.0 ┆ 4.0 │ │ 6.0 ┆ 5.0 │ └─────┴─────────────┘ Specify weights to multiply the values in the window with: >>> df.with_columns( ... rolling_min=pl.col("A").rolling_min( ... window_size=2, weights=[0.25, 0.75] ... ), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_min │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 0.25 │ │ 3.0 ┆ 0.5 │ │ 4.0 ┆ 0.75 │ │ 5.0 ┆ 1.0 │ │ 6.0 ┆ 1.25 │ └─────┴─────────────┘ Center the values in the window >>> df.with_columns( ... rolling_min=pl.col("A").rolling_min(window_size=3, center=True), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_min │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.0 │ │ 3.0 ┆ 2.0 │ │ 4.0 ┆ 3.0 │ │ 5.0 ┆ 4.0 │ │ 6.0 ┆ null │ └─────┴─────────────┘ """ return wrap_expr( self._pyexpr.rolling_min( window_size, weights, min_samples, center=center, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_max( self, window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Apply a rolling max (moving max) over the values in this array. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. The resulting values will be aggregated to their max. The window at a given row will include the row itself, and the `window_size - 1` elements before it. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window. 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`. center Set the labels at the center of the window. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_max=pl.col("A").rolling_max(window_size=2), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_max │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 2.0 │ │ 3.0 ┆ 3.0 │ │ 4.0 ┆ 4.0 │ │ 5.0 ┆ 5.0 │ │ 6.0 ┆ 6.0 │ └─────┴─────────────┘ Specify weights to multiply the values in the window with: >>> df.with_columns( ... rolling_max=pl.col("A").rolling_max( ... window_size=2, weights=[0.25, 0.75] ... ), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_max │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.5 │ │ 3.0 ┆ 2.25 │ │ 4.0 ┆ 3.0 │ │ 5.0 ┆ 3.75 │ │ 6.0 ┆ 4.5 │ └─────┴─────────────┘ Center the values in the window >>> df.with_columns( ... rolling_max=pl.col("A").rolling_max(window_size=3, center=True), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_max │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 3.0 │ │ 3.0 ┆ 4.0 │ │ 4.0 ┆ 5.0 │ │ 5.0 ┆ 6.0 │ │ 6.0 ┆ null │ └─────┴─────────────┘ """ return wrap_expr( self._pyexpr.rolling_max( window_size, weights, min_samples, center, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_mean( self, window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Apply a rolling mean (moving mean) over the values in this array. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. The resulting values will be aggregated to their mean. Weights are normalized to sum to 1. The window at a given row will include the row itself, and the `window_size - 1` elements before it. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window, after being normalized to sum to 1. 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`. center Set the labels at the center of the window. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_mean=pl.col("A").rolling_mean(window_size=2), ... ) shape: (6, 2) ┌─────┬──────────────┐ │ A ┆ rolling_mean │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪══════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.5 │ │ 3.0 ┆ 2.5 │ │ 4.0 ┆ 3.5 │ │ 5.0 ┆ 4.5 │ │ 6.0 ┆ 5.5 │ └─────┴──────────────┘ Specify weights to multiply the values in the window with: >>> df.with_columns( ... rolling_mean=pl.col("A").rolling_mean( ... window_size=2, weights=[0.25, 0.75] ... ), ... ) shape: (6, 2) ┌─────┬──────────────┐ │ A ┆ rolling_mean │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪══════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.75 │ │ 3.0 ┆ 2.75 │ │ 4.0 ┆ 3.75 │ │ 5.0 ┆ 4.75 │ │ 6.0 ┆ 5.75 │ └─────┴──────────────┘ Center the values in the window >>> df.with_columns( ... rolling_mean=pl.col("A").rolling_mean(window_size=3, center=True), ... ) shape: (6, 2) ┌─────┬──────────────┐ │ A ┆ rolling_mean │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪══════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 2.0 │ │ 3.0 ┆ 3.0 │ │ 4.0 ┆ 4.0 │ │ 5.0 ┆ 5.0 │ │ 6.0 ┆ null │ └─────┴──────────────┘ """ return wrap_expr( self._pyexpr.rolling_mean( window_size, weights, min_samples, center, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_sum( self, window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Apply a rolling sum (moving sum) over the values in this array. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. 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. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window. 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`. center Set the labels at the center of the window. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_sum=pl.col("A").rolling_sum(window_size=2), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_sum │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 3.0 │ │ 3.0 ┆ 5.0 │ │ 4.0 ┆ 7.0 │ │ 5.0 ┆ 9.0 │ │ 6.0 ┆ 11.0 │ └─────┴─────────────┘ Specify weights to multiply the values in the window with: >>> df.with_columns( ... rolling_sum=pl.col("A").rolling_sum( ... window_size=2, weights=[0.25, 0.75] ... ), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_sum │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.75 │ │ 3.0 ┆ 2.75 │ │ 4.0 ┆ 3.75 │ │ 5.0 ┆ 4.75 │ │ 6.0 ┆ 5.75 │ └─────┴─────────────┘ Center the values in the window >>> df.with_columns( ... rolling_sum=pl.col("A").rolling_sum(window_size=3, center=True), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_sum │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 6.0 │ │ 3.0 ┆ 9.0 │ │ 4.0 ┆ 12.0 │ │ 5.0 ┆ 15.0 │ │ 6.0 ┆ null │ └─────┴─────────────┘ """ return wrap_expr( self._pyexpr.rolling_sum( window_size, weights, min_samples, center, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_std( self, window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ddof: int = 1, ) -> Expr: """ Compute a rolling standard deviation. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. The resulting values will be aggregated to their std. Weights are normalized to sum to 1. The window at a given row will include the row itself, and the `window_size - 1` elements before it. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window after being normalized to sum to 1. 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`. 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 Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_std=pl.col("A").rolling_std(window_size=2), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_std │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 0.707107 │ │ 3.0 ┆ 0.707107 │ │ 4.0 ┆ 0.707107 │ │ 5.0 ┆ 0.707107 │ │ 6.0 ┆ 0.707107 │ └─────┴─────────────┘ Specify weights to multiply the values in the window with: >>> df.with_columns( ... rolling_std=pl.col("A").rolling_std( ... window_size=2, weights=[0.25, 0.75] ... ), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_std │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 0.433013 │ │ 3.0 ┆ 0.433013 │ │ 4.0 ┆ 0.433013 │ │ 5.0 ┆ 0.433013 │ │ 6.0 ┆ 0.433013 │ └─────┴─────────────┘ Center the values in the window >>> df.with_columns( ... rolling_std=pl.col("A").rolling_std(window_size=3, center=True), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_std │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.0 │ │ 3.0 ┆ 1.0 │ │ 4.0 ┆ 1.0 │ │ 5.0 ┆ 1.0 │ │ 6.0 ┆ null │ └─────┴─────────────┘ """ return wrap_expr( self._pyexpr.rolling_std( window_size, weights, min_samples, center=center, ddof=ddof, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_var( self, window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ddof: int = 1, ) -> Expr: """ Compute a rolling variance. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. The resulting values will be aggregated to their var. Weights are normalized to sum to 1. The window at a given row will include the row itself, and the `window_size - 1` elements before it. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window after being normalized to sum to 1. 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`. 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 Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_var=pl.col("A").rolling_var(window_size=2), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_var │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 0.5 │ │ 3.0 ┆ 0.5 │ │ 4.0 ┆ 0.5 │ │ 5.0 ┆ 0.5 │ │ 6.0 ┆ 0.5 │ └─────┴─────────────┘ Specify weights to multiply the values in the window with: >>> df.with_columns( ... rolling_var=pl.col("A").rolling_var( ... window_size=2, weights=[0.25, 0.75] ... ), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_var │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 0.1875 │ │ 3.0 ┆ 0.1875 │ │ 4.0 ┆ 0.1875 │ │ 5.0 ┆ 0.1875 │ │ 6.0 ┆ 0.1875 │ └─────┴─────────────┘ Center the values in the window >>> df.with_columns( ... rolling_var=pl.col("A").rolling_var(window_size=3, center=True), ... ) shape: (6, 2) ┌─────┬─────────────┐ │ A ┆ rolling_var │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪═════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.0 │ │ 3.0 ┆ 1.0 │ │ 4.0 ┆ 1.0 │ │ 5.0 ┆ 1.0 │ │ 6.0 ┆ null │ └─────┴─────────────┘ """ return wrap_expr( self._pyexpr.rolling_var( window_size, weights, min_samples, center=center, ddof=ddof, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_median( self, window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Compute a rolling median. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. The resulting values will be aggregated to their median. The window at a given row will include the row itself, and the `window_size - 1` elements before it. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window. 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`. center Set the labels at the center of the window. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_median=pl.col("A").rolling_median(window_size=2), ... ) shape: (6, 2) ┌─────┬────────────────┐ │ A ┆ rolling_median │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪════════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.5 │ │ 3.0 ┆ 2.5 │ │ 4.0 ┆ 3.5 │ │ 5.0 ┆ 4.5 │ │ 6.0 ┆ 5.5 │ └─────┴────────────────┘ Specify weights for the values in each window: >>> df.with_columns( ... rolling_median=pl.col("A").rolling_median( ... window_size=2, weights=[0.25, 0.75] ... ), ... ) shape: (6, 2) ┌─────┬────────────────┐ │ A ┆ rolling_median │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪════════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 1.5 │ │ 3.0 ┆ 2.5 │ │ 4.0 ┆ 3.5 │ │ 5.0 ┆ 4.5 │ │ 6.0 ┆ 5.5 │ └─────┴────────────────┘ Center the values in the window >>> df.with_columns( ... rolling_median=pl.col("A").rolling_median(window_size=3, center=True), ... ) shape: (6, 2) ┌─────┬────────────────┐ │ A ┆ rolling_median │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪════════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ 2.0 │ │ 3.0 ┆ 3.0 │ │ 4.0 ┆ 4.0 │ │ 5.0 ┆ 5.0 │ │ 6.0 ┆ null │ └─────┴────────────────┘ """ return wrap_expr( self._pyexpr.rolling_median( window_size, weights, min_samples, center=center, ) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_quantile( self, quantile: float, interpolation: QuantileMethod = "nearest", window_size: int = 2, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Compute a rolling quantile. A window of length `window_size` will traverse the array. The values that fill this window will (optionally) be multiplied with the weights given by the `weights` vector. The resulting values will be aggregated to their quantile. The window at a given row will include the row itself, and the `window_size - 1` elements before it. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- quantile Quantile between 0.0 and 1.0. interpolation : {'nearest', 'higher', 'lower', 'midpoint', 'linear', 'equiprobable'} Interpolation method. window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window. 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`. center Set the labels at the center of the window. Notes ----- If you want to compute multiple aggregation statistics over the same dynamic window, consider using `rolling` - this method can cache the window size computation. Examples -------- >>> df = pl.DataFrame({"A": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]}) >>> df.with_columns( ... rolling_quantile=pl.col("A").rolling_quantile( ... quantile=0.25, window_size=4 ... ), ... ) shape: (6, 2) ┌─────┬──────────────────┐ │ A ┆ rolling_quantile │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪══════════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ null │ │ 3.0 ┆ null │ │ 4.0 ┆ 2.0 │ │ 5.0 ┆ 3.0 │ │ 6.0 ┆ 4.0 │ └─────┴──────────────────┘ Specify weights for the values in each window: >>> df.with_columns( ... rolling_quantile=pl.col("A").rolling_quantile( ... quantile=0.25, window_size=4, weights=[0.2, 0.4, 0.4, 0.2] ... ), ... ) shape: (6, 2) ┌─────┬──────────────────┐ │ A ┆ rolling_quantile │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪══════════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ null │ │ 3.0 ┆ null │ │ 4.0 ┆ 2.0 │ │ 5.0 ┆ 3.0 │ │ 6.0 ┆ 4.0 │ └─────┴──────────────────┘ Specify weights and interpolation method >>> df.with_columns( ... rolling_quantile=pl.col("A").rolling_quantile( ... quantile=0.25, ... window_size=4, ... weights=[0.2, 0.4, 0.4, 0.2], ... interpolation="linear", ... ), ... ) shape: (6, 2) ┌─────┬──────────────────┐ │ A ┆ rolling_quantile │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪══════════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ null │ │ 3.0 ┆ null │ │ 4.0 ┆ 1.625 │ │ 5.0 ┆ 2.625 │ │ 6.0 ┆ 3.625 │ └─────┴──────────────────┘ Center the values in the window >>> df.with_columns( ... rolling_quantile=pl.col("A").rolling_quantile( ... quantile=0.2, window_size=5, center=True ... ), ... ) shape: (6, 2) ┌─────┬──────────────────┐ │ A ┆ rolling_quantile │ │ --- ┆ --- │ │ f64 ┆ f64 │ ╞═════╪══════════════════╡ │ 1.0 ┆ null │ │ 2.0 ┆ null │ │ 3.0 ┆ 2.0 │ │ 4.0 ┆ 3.0 │ │ 5.0 ┆ null │ │ 6.0 ┆ null │ └─────┴──────────────────┘ """ # noqa: W505 return wrap_expr( self._pyexpr.rolling_quantile( quantile, interpolation, window_size, weights, min_samples, center=center, ) ) @unstable() def rolling_rank( self, window_size: int, method: RankMethod = "average", *, seed: int | None = None, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Compute a rolling rank. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. A window of length `window_size` will traverse the array. The values that fill this window will be ranked according to the `method` parameter. The resulting values will be the rank of the value that is at the end of the sliding window. Parameters ---------- window_size Integer size of the rolling window. method : {'average', 'min', 'max', 'dense', 'random'} 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. - 'random' : Choose a random rank for each value in a tie. seed Random seed used when `method='random'`. If set to None (default), a random seed is generated for each rolling rank operation. 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`. center Set the labels at the center of the window. Returns ------- Expr An Expr of data :class:`.Float64` if `method` is `"average"` or, the index size (see :func:`.get_index_type()`) otherwise. Examples -------- >>> df = pl.DataFrame({"a": [1, 4, 4, 1, 9]}) >>> df.select(pl.col("a").rolling_rank(3, method="average")) shape: (5, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ null │ │ null │ │ 2.5 │ │ 1.0 │ │ 3.0 │ └──────┘ """ return wrap_expr( self._pyexpr.rolling_rank( window_size, method, seed, min_samples, center, ) ) @unstable() def rolling_skew( self, window_size: int, *, bias: bool = True, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Compute a rolling skew. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. The window at a given row will include the row itself, and the `window_size - 1` elements before it. Parameters ---------- window_size Integer size of the rolling window. bias If False, the calculations are corrected for statistical bias. bias: bool = True, 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`. center Set the labels at the center of the window. See Also -------- Expr.skew Examples -------- >>> df = pl.DataFrame({"a": [1, 4, 2, 9]}) >>> df.select(pl.col("a").rolling_skew(3)) shape: (4, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ null │ │ null │ │ 0.381802 │ │ 0.47033 │ └──────────┘ Note how the values match the following: >>> pl.Series([1, 4, 2]).skew(), pl.Series([4, 2, 9]).skew() (0.38180177416060584, 0.47033046033698594) """ return wrap_expr( self._pyexpr.rolling_skew( window_size, bias=bias, min_periods=min_samples, center=center ) ) @unstable() def rolling_kurtosis( self, window_size: int, *, fisher: bool = True, bias: bool = True, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Compute a rolling kurtosis. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. The window at a given row will include the row itself, and the `window_size - 1` elements before it. Parameters ---------- window_size Integer size of the rolling window. fisher : bool, optional If True, Fisher's definition is used (normal ==> 0.0). If False, Pearson's definition is used (normal ==> 3.0). bias : bool, optional If False, the calculations are corrected for statistical bias. 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`. center Set the labels at the center of the window. See Also -------- Expr.kurtosis Examples -------- >>> df = pl.DataFrame({"a": [1, 4, 2, 9]}) >>> df.select(pl.col("a").rolling_kurtosis(3)) shape: (4, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ null │ │ null │ │ -1.5 │ │ -1.5 │ └──────┘ """ return wrap_expr( self._pyexpr.rolling_kurtosis( window_size, fisher=fisher, bias=bias, min_periods=min_samples, center=center, ) ) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def rolling_map( self, function: Callable[[Series], Any], window_size: int, weights: list[float] | None = None, *, min_samples: int | None = None, center: bool = False, ) -> Expr: """ Compute a custom rolling window function. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- function Custom aggregation function. window_size The length of the window in number of elements. weights An optional slice with the same length as the window that will be multiplied elementwise with the values in the window. 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`. center Set the labels at the center of the window. Warnings -------- Computing custom functions is extremely slow. Use specialized rolling functions such as :func:`Expr.rolling_sum` if at all possible. Examples -------- >>> from numpy import nansum >>> df = pl.DataFrame({"a": [11.0, 2.0, 9.0, float("nan"), 8.0]}) >>> df.select(pl.col("a").rolling_map(nansum, window_size=3)) shape: (5, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ null │ │ null │ │ 22.0 │ │ 11.0 │ │ 17.0 │ └──────┘ """ if min_samples is None: min_samples = window_size def _wrap(pys: PySeries) -> PySeries: s = wrap_s(pys) rv = function(s) if isinstance(rv, pl.Series): return rv._s return pl.Series([rv])._s return wrap_expr( self._pyexpr.rolling_map(_wrap, window_size, weights, min_samples, center) ) def abs(self) -> Expr: """ Compute absolute values. Same as `abs(expr)`. Examples -------- >>> df = pl.DataFrame( ... { ... "A": [-1.0, 0.0, 1.0, 2.0], ... } ... ) >>> df.select(pl.col("A").abs()) shape: (4, 1) ┌─────┐ │ A │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ │ 0.0 │ │ 1.0 │ │ 2.0 │ └─────┘ """ return wrap_expr(self._pyexpr.abs()) def rank( self, method: RankMethod = "average", *, descending: bool = False, seed: int | None = None, ) -> Expr: """ Assign ranks to data, dealing with ties appropriately. Parameters ---------- method : {'average', 'min', 'max', 'dense', 'ordinal', 'random'} 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. - 'random' : Like 'ordinal', but the rank for ties is not dependent on the order that the values occur in the Series. descending Rank in descending order. seed If `method="random"`, use this as seed. Examples -------- The 'average' method: >>> df = pl.DataFrame({"a": [3, 6, 1, 1, 6]}) >>> df.select(pl.col("a").rank()) shape: (5, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 3.0 │ │ 4.5 │ │ 1.5 │ │ 1.5 │ │ 4.5 │ └─────┘ The 'ordinal' method: >>> df = pl.DataFrame({"a": [3, 6, 1, 1, 6]}) >>> df.select(pl.col("a").rank("ordinal")) shape: (5, 1) ┌─────┐ │ a │ │ --- │ │ u32 │ ╞═════╡ │ 3 │ │ 4 │ │ 1 │ │ 2 │ │ 5 │ └─────┘ Use 'rank' with 'over' to rank within groups: >>> df = pl.DataFrame({"a": [1, 1, 2, 2, 2], "b": [6, 7, 5, 14, 11]}) >>> df.with_columns(pl.col("b").rank().over("a").alias("rank")) shape: (5, 3) ┌─────┬─────┬──────┐ │ a ┆ b ┆ rank │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ f64 │ ╞═════╪═════╪══════╡ │ 1 ┆ 6 ┆ 1.0 │ │ 1 ┆ 7 ┆ 2.0 │ │ 2 ┆ 5 ┆ 1.0 │ │ 2 ┆ 14 ┆ 3.0 │ │ 2 ┆ 11 ┆ 2.0 │ └─────┴─────┴──────┘ Divide by the length or number of non-null values to compute the percentile rank. >>> df = pl.DataFrame({"a": [6, 7, None, 14, 11]}) >>> df.with_columns( ... pct=pl.col("a").rank() / pl.len(), ... pct_valid=pl.col("a").rank() / pl.count("a"), ... ) shape: (5, 3) ┌──────┬──────┬───────────┐ │ a ┆ pct ┆ pct_valid │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ f64 │ ╞══════╪══════╪═══════════╡ │ 6 ┆ 0.2 ┆ 0.25 │ │ 7 ┆ 0.4 ┆ 0.5 │ │ null ┆ null ┆ null │ │ 14 ┆ 0.8 ┆ 1.0 │ │ 11 ┆ 0.6 ┆ 0.75 │ └──────┴──────┴───────────┘ """ return wrap_expr(self._pyexpr.rank(method, descending, seed)) def diff( self, n: int | IntoExpr = 1, null_behavior: NullBehavior = "ignore" ) -> Expr: """ Calculate the first discrete difference between shifted items. Parameters ---------- n Number of slots to shift. null_behavior : {'ignore', 'drop'} How to handle null values. Examples -------- >>> df = pl.DataFrame({"int": [20, 10, 30, 25, 35]}) >>> df.with_columns(change=pl.col("int").diff()) shape: (5, 2) ┌─────┬────────┐ │ int ┆ change │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪════════╡ │ 20 ┆ null │ │ 10 ┆ -10 │ │ 30 ┆ 20 │ │ 25 ┆ -5 │ │ 35 ┆ 10 │ └─────┴────────┘ >>> df.with_columns(change=pl.col("int").diff(n=2)) shape: (5, 2) ┌─────┬────────┐ │ int ┆ change │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪════════╡ │ 20 ┆ null │ │ 10 ┆ null │ │ 30 ┆ 10 │ │ 25 ┆ 15 │ │ 35 ┆ 5 │ └─────┴────────┘ >>> df.select(pl.col("int").diff(n=2, null_behavior="drop").alias("diff")) shape: (3, 1) ┌──────┐ │ diff │ │ --- │ │ i64 │ ╞══════╡ │ 10 │ │ 15 │ │ 5 │ └──────┘ """ n_pyexpr = parse_into_expression(n) return wrap_expr(self._pyexpr.diff(n_pyexpr, null_behavior)) def pct_change(self, n: int | IntoExprColumn = 1) -> Expr: """ Computes percentage change between values. Percentage change (as fraction) between current element and most-recent non-null element at least `n` period(s) before the current element. Computes the change from the previous row by default. Parameters ---------- n periods to shift for forming percent change. Notes ----- Null values are preserved. If you're coming from pandas, this matches their ``fill_method=None`` behaviour. Examples -------- >>> df = pl.DataFrame( ... { ... "a": [10, 11, 12, None, 12], ... } ... ) >>> df.with_columns(pl.col("a").pct_change().alias("pct_change")) shape: (5, 2) ┌──────┬────────────┐ │ a ┆ pct_change │ │ --- ┆ --- │ │ i64 ┆ f64 │ ╞══════╪════════════╡ │ 10 ┆ null │ │ 11 ┆ 0.1 │ │ 12 ┆ 0.090909 │ │ null ┆ null │ │ 12 ┆ null │ └──────┴────────────┘ """ n_pyexpr = parse_into_expression(n) return wrap_expr(self._pyexpr.pct_change(n_pyexpr)) def skew(self, *, bias: bool = True) -> Expr: r""" Compute the sample skewness of a data set. For normally distributed data, the skewness should be about zero. For unimodal continuous distributions, a skewness value greater than zero means that there is more weight in the right tail of the distribution. The function `skewtest` can be used to determine if the skewness value is close enough to zero, statistically speaking. See scipy.stats for more information. Parameters ---------- bias : bool, optional If False, the calculations are corrected for statistical bias. Notes ----- The sample skewness is computed as the Fisher-Pearson coefficient of skewness, i.e. .. math:: g_1=\frac{m_3}{m_2^{3/2}} where .. math:: m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i is the biased sample :math:`i\texttt{th}` central moment, and :math:`\bar{x}` is the sample mean. If `bias` is False, the calculations are corrected for bias and the value computed is the adjusted Fisher-Pearson standardized moment coefficient, i.e. .. math:: G_1 = \frac{k_3}{k_2^{3/2}} = \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}} Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3, 2, 1]}) >>> df.select(pl.col("a").skew()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.343622 │ └──────────┘ """ return wrap_expr(self._pyexpr.skew(bias)) def kurtosis(self, *, fisher: bool = True, bias: bool = True) -> Expr: """ Compute the kurtosis (Fisher or Pearson) of a dataset. Kurtosis is the fourth central moment divided by the square of the variance. If Fisher's definition is used, then 3.0 is subtracted from the result to give 0.0 for a normal distribution. If bias is False then the kurtosis is calculated using k statistics to eliminate bias coming from biased moment estimators. See scipy.stats for more information Parameters ---------- fisher : bool, optional If True, Fisher's definition is used (normal ==> 0.0). If False, Pearson's definition is used (normal ==> 3.0). bias : bool, optional If False, the calculations are corrected for statistical bias. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3, 2, 1]}) >>> df.select(pl.col("a").kurtosis()) shape: (1, 1) ┌───────────┐ │ a │ │ --- │ │ f64 │ ╞═══════════╡ │ -1.153061 │ └───────────┘ """ return wrap_expr(self._pyexpr.kurtosis(fisher, bias)) def clip( self, lower_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None, upper_bound: NumericLiteral | TemporalLiteral | IntoExprColumn | None = None, ) -> Expr: """ Set values outside the given boundaries to the boundary value. Parameters ---------- lower_bound Lower bound. Accepts expression input. Non-expression inputs are parsed as literals. Strings are parsed as column names. upper_bound Upper bound. Accepts expression input. Non-expression inputs are parsed as literals. Strings are parsed as column names. See Also -------- when Notes ----- This method only works for numeric and temporal columns. To clip other data types, consider writing a `when-then-otherwise` expression. See :func:`when`. Examples -------- Specifying both a lower and upper bound: >>> df = pl.DataFrame({"a": [-50, 5, 50, None]}) >>> df.with_columns(clip=pl.col("a").clip(1, 10)) shape: (4, 2) ┌──────┬──────┐ │ a ┆ clip │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ -50 ┆ 1 │ │ 5 ┆ 5 │ │ 50 ┆ 10 │ │ null ┆ null │ └──────┴──────┘ Specifying only a single bound: >>> df.with_columns(clip=pl.col("a").clip(upper_bound=10)) shape: (4, 2) ┌──────┬──────┐ │ a ┆ clip │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ -50 ┆ -50 │ │ 5 ┆ 5 │ │ 50 ┆ 10 │ │ null ┆ null │ └──────┴──────┘ Using columns as bounds: >>> df = pl.DataFrame( ... {"a": [-50, 5, 50, None], "low": [10, 1, 0, 0], "up": [20, 4, 3, 2]} ... ) >>> df.with_columns(clip=pl.col("a").clip("low", "up")) shape: (4, 4) ┌──────┬─────┬─────┬──────┐ │ a ┆ low ┆ up ┆ clip │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞══════╪═════╪═════╪══════╡ │ -50 ┆ 10 ┆ 20 ┆ 10 │ │ 5 ┆ 1 ┆ 4 ┆ 4 │ │ 50 ┆ 0 ┆ 3 ┆ 3 │ │ null ┆ 0 ┆ 2 ┆ null │ └──────┴─────┴─────┴──────┘ """ if lower_bound is not None: lower_bound_pyexpr = parse_into_expression(lower_bound) else: lower_bound_pyexpr = None if upper_bound is not None: upper_bound_pyexpr = parse_into_expression(upper_bound) else: upper_bound_pyexpr = None return wrap_expr(self._pyexpr.clip(lower_bound_pyexpr, upper_bound_pyexpr)) def lower_bound(self) -> Expr: """ Calculate the lower bound. Returns a unit Series with the lowest value possible for the dtype of this expression. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3, 2, 1]}) >>> df.select(pl.col("a").lower_bound()) shape: (1, 1) ┌──────────────────────┐ │ a │ │ --- │ │ i64 │ ╞══════════════════════╡ │ -9223372036854775808 │ └──────────────────────┘ """ return wrap_expr(self._pyexpr.lower_bound()) def upper_bound(self) -> Expr: """ Calculate the upper bound. Returns a unit Series with the highest value possible for the dtype of this expression. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3, 2, 1]}) >>> df.select(pl.col("a").upper_bound()) shape: (1, 1) ┌─────────────────────┐ │ a │ │ --- │ │ i64 │ ╞═════════════════════╡ │ 9223372036854775807 │ └─────────────────────┘ """ return wrap_expr(self._pyexpr.upper_bound()) def sign(self) -> Expr: """ Compute the element-wise sign function on numeric types. The returned value is computed as follows: * -1 if x < 0. * 1 if x > 0. * x otherwise (typically 0, but could be NaN if the input is). Null values are preserved as-is, and the dtype of the input is preserved. Examples -------- >>> df = pl.DataFrame({"a": [-9.0, -0.0, 0.0, 4.0, float("nan"), None]}) >>> df.select(pl.col.a.sign()) shape: (6, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ -1.0 │ │ -0.0 │ │ 0.0 │ │ 1.0 │ │ NaN │ │ null │ └──────┘ """ return wrap_expr(self._pyexpr.sign()) def sin(self) -> Expr: """ Compute the element-wise value for the sine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [0.0]}) >>> df.select(pl.col("a").sin()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 0.0 │ └─────┘ """ return wrap_expr(self._pyexpr.sin()) def cos(self) -> Expr: """ Compute the element-wise value for the cosine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [0.0]}) >>> df.select(pl.col("a").cos()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 1.0 │ └─────┘ """ return wrap_expr(self._pyexpr.cos()) def tan(self) -> Expr: """ Compute the element-wise value for the tangent. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").tan().round(2)) shape: (1, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ 1.56 │ └──────┘ """ return wrap_expr(self._pyexpr.tan()) def cot(self) -> Expr: """ Compute the element-wise value for the cotangent. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").cot().round(2)) shape: (1, 1) ┌──────┐ │ a │ │ --- │ │ f64 │ ╞══════╡ │ 0.64 │ └──────┘ """ return wrap_expr(self._pyexpr.cot()) def arcsin(self) -> Expr: """ Compute the element-wise value for the inverse sine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").arcsin()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 1.570796 │ └──────────┘ """ return wrap_expr(self._pyexpr.arcsin()) def arccos(self) -> Expr: """ Compute the element-wise value for the inverse cosine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [0.0]}) >>> df.select(pl.col("a").arccos()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 1.570796 │ └──────────┘ """ return wrap_expr(self._pyexpr.arccos()) def arctan(self) -> Expr: """ Compute the element-wise value for the inverse tangent. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").arctan()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.785398 │ └──────────┘ """ return wrap_expr(self._pyexpr.arctan()) def sinh(self) -> Expr: """ Compute the element-wise value for the hyperbolic sine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").sinh()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 1.175201 │ └──────────┘ """ return wrap_expr(self._pyexpr.sinh()) def cosh(self) -> Expr: """ Compute the element-wise value for the hyperbolic cosine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").cosh()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 1.543081 │ └──────────┘ """ return wrap_expr(self._pyexpr.cosh()) def tanh(self) -> Expr: """ Compute the element-wise value for the hyperbolic tangent. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").tanh()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.761594 │ └──────────┘ """ return wrap_expr(self._pyexpr.tanh()) def arcsinh(self) -> Expr: """ Compute the element-wise value for the inverse hyperbolic sine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").arcsinh()) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.881374 │ └──────────┘ """ return wrap_expr(self._pyexpr.arcsinh()) def arccosh(self) -> Expr: """ Compute the element-wise value for the inverse hyperbolic cosine. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").arccosh()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ 0.0 │ └─────┘ """ return wrap_expr(self._pyexpr.arccosh()) def arctanh(self) -> Expr: """ Compute the element-wise value for the inverse hyperbolic tangent. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [1.0]}) >>> df.select(pl.col("a").arctanh()) shape: (1, 1) ┌─────┐ │ a │ │ --- │ │ f64 │ ╞═════╡ │ inf │ └─────┘ """ return wrap_expr(self._pyexpr.arctanh()) def degrees(self) -> Expr: """ Convert from radians to degrees. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> import math >>> df = pl.DataFrame({"a": [x * math.pi for x in range(-4, 5)]}) >>> df.select(pl.col("a").degrees()) shape: (9, 1) ┌────────┐ │ a │ │ --- │ │ f64 │ ╞════════╡ │ -720.0 │ │ -540.0 │ │ -360.0 │ │ -180.0 │ │ 0.0 │ │ 180.0 │ │ 360.0 │ │ 540.0 │ │ 720.0 │ └────────┘ """ return wrap_expr(self._pyexpr.degrees()) def radians(self) -> Expr: """ Convert from degrees to radians. Returns ------- Expr Expression of data type :class:`Float64`. Examples -------- >>> df = pl.DataFrame({"a": [-720, -540, -360, -180, 0, 180, 360, 540, 720]}) >>> df.select(pl.col("a").radians()) shape: (9, 1) ┌────────────┐ │ a │ │ --- │ │ f64 │ ╞════════════╡ │ -12.566371 │ │ -9.424778 │ │ -6.283185 │ │ -3.141593 │ │ 0.0 │ │ 3.141593 │ │ 6.283185 │ │ 9.424778 │ │ 12.566371 │ └────────────┘ """ return wrap_expr(self._pyexpr.radians()) def reshape(self, dimensions: tuple[int, ...]) -> Expr: """ Reshape this Expr to a flat column or an Array column. Parameters ---------- dimensions Tuple of the dimension sizes. If -1 is used as the value for the first dimension, that dimension is inferred. Because the size of the Column may not be known in advance, it is only possible to use -1 for the first dimension. Returns ------- Expr If a single dimension is given, results in an expression of the original data type. If a multiple dimensions are given, results in an expression of data type :class:`Array` with shape `dimensions`. Examples -------- >>> df = pl.DataFrame({"foo": [1, 2, 3, 4, 5, 6, 7, 8, 9]}) >>> square = df.select(pl.col("foo").reshape((3, 3))) >>> square shape: (3, 1) ┌───────────────┐ │ foo │ │ --- │ │ array[i64, 3] │ ╞═══════════════╡ │ [1, 2, 3] │ │ [4, 5, 6] │ │ [7, 8, 9] │ └───────────────┘ >>> square.select(pl.col("foo").reshape((9,))) shape: (9, 1) ┌─────┐ │ foo │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ │ 3 │ │ 4 │ │ 5 │ │ 6 │ │ 7 │ │ 8 │ │ 9 │ └─────┘ See Also -------- Expr.list.explode : Explode a list column. """ return wrap_expr(self._pyexpr.reshape(dimensions)) def shuffle(self, seed: int | None = None) -> Expr: """ Shuffle the contents of this expression. Note this is shuffled independently of any other column or Expression. If you want each row to stay the same use df.sample(shuffle=True) Parameters ---------- seed Seed for the random number generator. If set to None (default), a random seed is generated each time the shuffle is called. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").shuffle(seed=1)) shape: (3, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 2 │ │ 3 │ │ 1 │ └─────┘ """ return wrap_expr(self._pyexpr.shuffle(seed)) def sample( self, n: int | IntoExprColumn | None = None, *, fraction: float | IntoExprColumn | None = None, with_replacement: bool = False, shuffle: bool = False, seed: int | None = None, ) -> Expr: """ Sample from this expression. Parameters ---------- n Number of items to return. Cannot be used with `fraction`. Defaults to 1 if `fraction` is None. fraction Fraction of items to return. Cannot be used with `n`. with_replacement Allow values to be sampled more than once. shuffle Shuffle the order of sampled data points. seed Seed for the random number generator. If set to None (default), a random seed is generated for each sample operation. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").sample(fraction=1.0, with_replacement=True, seed=1)) shape: (3, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 3 │ │ 3 │ │ 1 │ └─────┘ """ if n is not None and fraction is not None: msg = "cannot specify both `n` and `fraction`" raise ValueError(msg) if fraction is not None: fraction_pyexpr = parse_into_expression(fraction) return wrap_expr( self._pyexpr.sample_frac( fraction_pyexpr, with_replacement, shuffle, seed ) ) if n is None: n = 1 n_pyexpr = parse_into_expression(n) return wrap_expr( self._pyexpr.sample_n(n_pyexpr, with_replacement, shuffle, seed) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") 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, ) -> Expr: r""" Compute exponentially-weighted moving average. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- com Specify decay in terms of center of mass, :math:`\gamma`, with .. math:: \alpha = \frac{1}{1 + \gamma} \; \forall \; \gamma \geq 0 span Specify decay in terms of span, :math:`\theta`, with .. math:: \alpha = \frac{2}{\theta + 1} \; \forall \; \theta \geq 1 half_life Specify decay in terms of half-life, :math:`\tau`, with .. math:: \alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \tau } \right\} \; \forall \; \tau > 0 alpha Specify smoothing factor alpha directly, :math:`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 :math:`w_i = (1 - \alpha)^i` - When `adjust=False` the EW function is calculated recursively by .. math:: 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 :math:`x_0` and :math:`x_2` used in calculating the final weighted average of [:math:`x_0`, None, :math:`x_2`] are :math:`(1-\alpha)^2` and :math:`1` if `adjust=True`, and :math:`(1-\alpha)^2` and :math:`\alpha` if `adjust=False`. - When `ignore_nulls=True`, weights are based on relative positions. For example, the weights of :math:`x_0` and :math:`x_2` used in calculating the final weighted average of [:math:`x_0`, None, :math:`x_2`] are :math:`1-\alpha` and :math:`1` if `adjust=True`, and :math:`1-\alpha` and :math:`\alpha` if `adjust=False`. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").ewm_mean(com=1, ignore_nulls=False)) shape: (3, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 1.0 │ │ 1.666667 │ │ 2.428571 │ └──────────┘ """ alpha = _prepare_alpha(com, span, half_life, alpha) return wrap_expr( self._pyexpr.ewm_mean(alpha, adjust, min_samples, ignore_nulls) ) def ewm_mean_by( self, by: str | IntoExpr, *, half_life: str | timedelta, ) -> Expr: r""" Compute time-based exponentially weighted moving average. Given observations :math:`x_0, x_1, \ldots, x_{n-1}` at times :math:`t_0, t_1, \ldots, t_{n-1}`, the EWMA is calculated as .. math:: y_0 &= x_0 \alpha_i &= 1 - \exp \left\{ \frac{ -\ln(2)(t_i-t_{i-1}) } { \tau } \right\} y_i &= \alpha_i x_i + (1 - \alpha_i) y_{i-1}; \quad i > 0 where :math:`\tau` is the `half_life`. Parameters ---------- by Times to calculate average by. Should be ``DateTime``, ``Date``, ``UInt64``, ``UInt32``, ``Int64``, or ``Int32`` data type. half_life Unit over which observation decays to half its value. Can be created either from a timedelta, or by using the following string language: - 1ns (1 nanosecond) - 1us (1 microsecond) - 1ms (1 millisecond) - 1s (1 second) - 1m (1 minute) - 1h (1 hour) - 1d (1 day) - 1w (1 week) - 1i (1 index count) Or combine them: "3d12h4m25s" # 3 days, 12 hours, 4 minutes, and 25 seconds Note that `half_life` is treated as a constant duration - calendar durations such as months (or even days in the time-zone-aware case) are not supported, please express your duration in an approximately equivalent number of hours (e.g. '370h' instead of '1mo'). Returns ------- Expr :class:`.Float16` if input is `Float16`, class:`.Float32` if input is `Float32`, otherwise class:`.Float64`. Examples -------- >>> from datetime import date, timedelta >>> df = pl.DataFrame( ... { ... "values": [0, 1, 2, None, 4], ... "times": [ ... date(2020, 1, 1), ... date(2020, 1, 3), ... date(2020, 1, 10), ... date(2020, 1, 15), ... date(2020, 1, 17), ... ], ... } ... ).sort("times") >>> df.with_columns( ... result=pl.col("values").ewm_mean_by("times", half_life="4d"), ... ) shape: (5, 3) ┌────────┬────────────┬──────────┐ │ values ┆ times ┆ result │ │ --- ┆ --- ┆ --- │ │ i64 ┆ date ┆ f64 │ ╞════════╪════════════╪══════════╡ │ 0 ┆ 2020-01-01 ┆ 0.0 │ │ 1 ┆ 2020-01-03 ┆ 0.292893 │ │ 2 ┆ 2020-01-10 ┆ 1.492474 │ │ null ┆ 2020-01-15 ┆ null │ │ 4 ┆ 2020-01-17 ┆ 3.254508 │ └────────┴────────────┴──────────┘ """ by_pyexpr = parse_into_expression(by) half_life = parse_as_duration_string(half_life) return wrap_expr(self._pyexpr.ewm_mean_by(by_pyexpr, half_life)) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def ewm_std( self, *, com: float | None = None, span: float | None = None, half_life: float | None = None, alpha: float | None = None, adjust: bool = True, bias: bool = False, min_samples: int = 1, ignore_nulls: bool = False, ) -> Expr: r""" Compute exponentially-weighted moving standard deviation. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- com Specify decay in terms of center of mass, :math:`\gamma`, with .. math:: \alpha = \frac{1}{1 + \gamma} \; \forall \; \gamma \geq 0 span Specify decay in terms of span, :math:`\theta`, with .. math:: \alpha = \frac{2}{\theta + 1} \; \forall \; \theta \geq 1 half_life Specify decay in terms of half-life, :math:`\lambda`, with .. math:: \alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \lambda } \right\} \; \forall \; \lambda > 0 alpha Specify smoothing factor alpha directly, :math:`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 :math:`w_i = (1 - \alpha)^i` - When `adjust=False` the EW function is calculated recursively by .. math:: y_0 &= x_0 \\ y_t &= (1 - \alpha)y_{t - 1} + \alpha x_t bias When `bias=False`, apply a correction to make the estimate statistically unbiased. 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 :math:`x_0` and :math:`x_2` used in calculating the final weighted average of [:math:`x_0`, None, :math:`x_2`] are :math:`(1-\alpha)^2` and :math:`1` if `adjust=True`, and :math:`(1-\alpha)^2` and :math:`\alpha` if `adjust=False`. - When `ignore_nulls=True`, weights are based on relative positions. For example, the weights of :math:`x_0` and :math:`x_2` used in calculating the final weighted average of [:math:`x_0`, None, :math:`x_2`] are :math:`1-\alpha` and :math:`1` if `adjust=True`, and :math:`1-\alpha` and :math:`\alpha` if `adjust=False`. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").ewm_std(com=1, ignore_nulls=False)) shape: (3, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.0 │ │ 0.707107 │ │ 0.963624 │ └──────────┘ """ alpha = _prepare_alpha(com, span, half_life, alpha) return wrap_expr( self._pyexpr.ewm_std(alpha, adjust, bias, min_samples, ignore_nulls) ) @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def ewm_var( self, *, com: float | None = None, span: float | None = None, half_life: float | None = None, alpha: float | None = None, adjust: bool = True, bias: bool = False, min_samples: int = 1, ignore_nulls: bool = False, ) -> Expr: r""" Compute exponentially-weighted moving variance. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- com Specify decay in terms of center of mass, :math:`\gamma`, with .. math:: \alpha = \frac{1}{1 + \gamma} \; \forall \; \gamma \geq 0 span Specify decay in terms of span, :math:`\theta`, with .. math:: \alpha = \frac{2}{\theta + 1} \; \forall \; \theta \geq 1 half_life Specify decay in terms of half-life, :math:`\lambda`, with .. math:: \alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \lambda } \right\} \; \forall \; \lambda > 0 alpha Specify smoothing factor alpha directly, :math:`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 :math:`w_i = (1 - \alpha)^i` - When `adjust=False` the EW function is calculated recursively by .. math:: y_0 &= x_0 \\ y_t &= (1 - \alpha)y_{t - 1} + \alpha x_t bias When `bias=False`, apply a correction to make the estimate statistically unbiased. 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 :math:`x_0` and :math:`x_2` used in calculating the final weighted average of [:math:`x_0`, None, :math:`x_2`] are :math:`(1-\alpha)^2` and :math:`1` if `adjust=True`, and :math:`(1-\alpha)^2` and :math:`\alpha` if `adjust=False`. - When `ignore_nulls=True`, weights are based on relative positions. For example, the weights of :math:`x_0` and :math:`x_2` used in calculating the final weighted average of [:math:`x_0`, None, :math:`x_2`] are :math:`1-\alpha` and :math:`1` if `adjust=True`, and :math:`1-\alpha` and :math:`\alpha` if `adjust=False`. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").ewm_var(com=1, ignore_nulls=False)) shape: (3, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.0 │ │ 0.5 │ │ 0.928571 │ └──────────┘ """ alpha = _prepare_alpha(com, span, half_life, alpha) return wrap_expr( self._pyexpr.ewm_var(alpha, adjust, bias, min_samples, ignore_nulls) ) def extend_constant(self, value: IntoExpr, n: int | IntoExprColumn) -> Expr: """ Extremely fast method for extending the Series with 'n' copies of a value. Parameters ---------- value A constant literal value or a unit expression with which to extend the expression result Series; can pass None to extend with nulls. n The number of additional values that will be added. Examples -------- >>> df = pl.DataFrame({"values": [1, 2, 3]}) >>> df.select((pl.col("values") - 1).extend_constant(99, n=2)) shape: (5, 1) ┌────────┐ │ values │ │ --- │ │ i64 │ ╞════════╡ │ 0 │ │ 1 │ │ 2 │ │ 99 │ │ 99 │ └────────┘ """ value_pyexpr = parse_into_expression(value, str_as_lit=True) n_pyexpr = parse_into_expression(n) return wrap_expr(self._pyexpr.extend_constant(value_pyexpr, n_pyexpr)) def value_counts( self, *, sort: bool = False, parallel: bool = False, name: str | None = None, normalize: bool = False, ) -> Expr: """ Count the occurrence of unique values. Parameters ---------- sort Sort the output by count, in descending order. If set to `False` (default), the order is non-deterministic. parallel Execute the computation in parallel. .. note:: This option should likely *not* be enabled in a `group_by` context, as the computation will already be parallelized per group. name Give the resulting count column a specific name; if `normalize` is True this defaults to "proportion", otherwise defaults to "count". normalize If True, the count is returned as the relative frequency of unique values normalized to 1.0. Returns ------- Expr Expression of type :class:`Struct`, mapping unique values to their count (or proportion). Examples -------- >>> df = pl.DataFrame( ... {"color": ["red", "blue", "red", "green", "blue", "blue"]} ... ) >>> df_count = df.select(pl.col("color").value_counts()) >>> df_count # doctest: +IGNORE_RESULT shape: (3, 1) ┌─────────────┐ │ color │ │ --- │ │ struct[2] │ ╞═════════════╡ │ {"green",1} │ │ {"blue",3} │ │ {"red",2} │ └─────────────┘ >>> df_count.unnest("color") # doctest: +IGNORE_RESULT shape: (3, 2) ┌───────┬───────┐ │ color ┆ count │ │ --- ┆ --- │ │ str ┆ u32 │ ╞═══════╪═══════╡ │ green ┆ 1 │ │ blue ┆ 3 │ │ red ┆ 2 │ └───────┴───────┘ Sort the output by (descending) count, customize the field name, and normalize the count to its relative proportion (of 1.0). >>> df_count = df.select( ... pl.col("color").value_counts( ... name="fraction", ... normalize=True, ... sort=True, ... ) ... ) >>> df_count shape: (3, 1) ┌────────────────────┐ │ color │ │ --- │ │ struct[2] │ ╞════════════════════╡ │ {"blue",0.5} │ │ {"red",0.333333} │ │ {"green",0.166667} │ └────────────────────┘ >>> df_count.unnest("color") shape: (3, 2) ┌───────┬──────────┐ │ color ┆ fraction │ │ --- ┆ --- │ │ str ┆ f64 │ ╞═══════╪══════════╡ │ blue ┆ 0.5 │ │ red ┆ 0.333333 │ │ green ┆ 0.166667 │ └───────┴──────────┘ Note that `group_by` can be used to generate counts. >>> df.group_by("color").len() # doctest: +IGNORE_RESULT shape: (3, 2) ┌───────┬─────┐ │ color ┆ len │ │ --- ┆ --- │ │ str ┆ u32 │ ╞═══════╪═════╡ │ red ┆ 2 │ │ green ┆ 1 │ │ blue ┆ 3 │ └───────┴─────┘ To add counts as a new column `pl.len()` can be used as a window function. >>> df.with_columns(pl.len().over("color")) shape: (6, 2) ┌───────┬─────┐ │ color ┆ len │ │ --- ┆ --- │ │ str ┆ u32 │ ╞═══════╪═════╡ │ red ┆ 2 │ │ blue ┆ 3 │ │ red ┆ 2 │ │ green ┆ 1 │ │ blue ┆ 3 │ │ blue ┆ 3 │ └───────┴─────┘ >>> df.with_columns((pl.len().over("color") / pl.len()).alias("fraction")) shape: (6, 2) ┌───────┬──────────┐ │ color ┆ fraction │ │ --- ┆ --- │ │ str ┆ f64 │ ╞═══════╪══════════╡ │ red ┆ 0.333333 │ │ blue ┆ 0.5 │ │ red ┆ 0.333333 │ │ green ┆ 0.166667 │ │ blue ┆ 0.5 │ │ blue ┆ 0.5 │ └───────┴──────────┘ """ name = name or ("proportion" if normalize else "count") return wrap_expr(self._pyexpr.value_counts(sort, parallel, name, normalize)) def unique_counts(self) -> Expr: """ Return a count of the unique values in the order of appearance. This method differs from `value_counts` in that it does not return the values, only the counts and might be faster Examples -------- >>> df = pl.DataFrame( ... { ... "id": ["a", "b", "b", "c", "c", "c"], ... } ... ) >>> df.select(pl.col("id").unique_counts()) shape: (3, 1) ┌─────┐ │ id │ │ --- │ │ u32 │ ╞═════╡ │ 1 │ │ 2 │ │ 3 │ └─────┘ Note that `group_by` can be used to generate counts. >>> df.group_by("id", maintain_order=True).len().select("len") shape: (3, 1) ┌─────┐ │ len │ │ --- │ │ u32 │ ╞═════╡ │ 1 │ │ 2 │ │ 3 │ └─────┘ To add counts as a new column `pl.len()` can be used as a window function. >>> df.with_columns(pl.len().over("id")) shape: (6, 2) ┌─────┬─────┐ │ id ┆ len │ │ --- ┆ --- │ │ str ┆ u32 │ ╞═════╪═════╡ │ a ┆ 1 │ │ b ┆ 2 │ │ b ┆ 2 │ │ c ┆ 3 │ │ c ┆ 3 │ │ c ┆ 3 │ └─────┴─────┘ """ return wrap_expr(self._pyexpr.unique_counts()) def log(self, base: float | IntoExpr = math.e) -> Expr: """ Compute the logarithm to a given base. Parameters ---------- base Given base, defaults to `e` Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").log(base=2)) shape: (3, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.0 │ │ 1.0 │ │ 1.584963 │ └──────────┘ """ base_pyexpr = parse_into_expression(base) return wrap_expr(self._pyexpr.log(base_pyexpr)) def log1p(self) -> Expr: """ Compute the natural logarithm of each element plus one. This computes `log(1 + x)` but is more numerically stable for `x` close to zero. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").log1p()) shape: (3, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 0.693147 │ │ 1.098612 │ │ 1.386294 │ └──────────┘ """ return wrap_expr(self._pyexpr.log1p()) def entropy(self, base: float = math.e, *, normalize: bool = True) -> Expr: """ Computes the entropy. Uses the formula `-sum(pk * log(pk))` where `pk` are discrete probabilities. Parameters ---------- base Given base, defaults to `e` normalize Normalize pk if it doesn't sum to 1. Examples -------- >>> df = pl.DataFrame({"a": [1, 2, 3]}) >>> df.select(pl.col("a").entropy(base=2)) shape: (1, 1) ┌──────────┐ │ a │ │ --- │ │ f64 │ ╞══════════╡ │ 1.459148 │ └──────────┘ >>> df.select(pl.col("a").entropy(base=2, normalize=False)) shape: (1, 1) ┌───────────┐ │ a │ │ --- │ │ f64 │ ╞═══════════╡ │ -6.754888 │ └───────────┘ """ return wrap_expr(self._pyexpr.entropy(base, normalize)) @unstable() @deprecate_renamed_parameter("min_periods", "min_samples", version="1.21.0") def cumulative_eval(self, expr: Expr, *, min_samples: int = 1) -> Expr: """ Run an expression over a sliding window that increases `1` slot every iteration. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. .. versionchanged:: 1.21.0 The `min_periods` parameter was renamed `min_samples`. Parameters ---------- expr Expression to evaluate min_samples Number of valid values there should be in the window before the expression is evaluated. valid values = `length - null_count` Warnings -------- This can be really slow as it can have `O(n^2)` complexity. Don't use this for operations that visit all elements. Examples -------- >>> df = pl.DataFrame({"values": [1, 2, 3, 4, 5]}) >>> df.select( ... [ ... pl.col("values").cumulative_eval( ... pl.element().first() - pl.element().last() ** 2 ... ) ... ] ... ) shape: (5, 1) ┌────────┐ │ values │ │ --- │ │ i64 │ ╞════════╡ │ 0 │ │ -3 │ │ -8 │ │ -15 │ │ -24 │ └────────┘ """ return wrap_expr(self._pyexpr.cumulative_eval(expr._pyexpr, min_samples)) def set_sorted(self, *, descending: bool = False) -> Expr: """ Flags the expression as 'sorted'. Enables downstream code to user fast paths for sorted arrays. Parameters ---------- descending Whether the `Series` order is descending. Warnings -------- This can lead to incorrect results if the data is NOT sorted!! Use with care! Examples -------- >>> df = pl.DataFrame({"values": [1, 2, 3]}) >>> df.select(pl.col("values").set_sorted().max()) shape: (1, 1) ┌────────┐ │ values │ │ --- │ │ i64 │ ╞════════╡ │ 3 │ └────────┘ """ return wrap_expr(self._pyexpr.set_sorted_flag(descending)) @deprecated( "`Expr.shrink_dtype` is deprecated and is a no-op; use `Series.shrink_dtype` instead." ) def shrink_dtype(self) -> Expr: """ Shrink numeric columns to the minimal required datatype. Shrink to the dtype needed to fit the extrema of this [`Series`]. This can be used to reduce memory pressure. .. versionchanged:: 1.33.0 Deprecated and turned into a no-op. The operation does not match the Polars data-model during lazy execution since the output datatype cannot be known without inspecting the data. Use `Series.shrink_dtype` instead. Examples -------- >>> pl.DataFrame( ... { ... "a": [1, 2, 3], ... "b": [1, 2, 2 << 32], ... "c": [-1, 2, 1 << 30], ... "d": [-112, 2, 112], ... "e": [-112, 2, 129], ... "f": ["a", "b", "c"], ... "g": [0.1, 1.32, 0.12], ... "h": [True, None, False], ... } ... ).select(pl.all().shrink_dtype()) # doctest: +SKIP shape: (3, 8) ┌─────┬────────────┬────────────┬──────┬──────┬─────┬──────┬───────┐ │ a ┆ b ┆ c ┆ d ┆ e ┆ f ┆ g ┆ h │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i8 ┆ i64 ┆ i32 ┆ i8 ┆ i16 ┆ str ┆ f32 ┆ bool │ ╞═════╪════════════╪════════════╪══════╪══════╪═════╪══════╪═══════╡ │ 1 ┆ 1 ┆ -1 ┆ -112 ┆ -112 ┆ a ┆ 0.1 ┆ true │ │ 2 ┆ 2 ┆ 2 ┆ 2 ┆ 2 ┆ b ┆ 1.32 ┆ null │ │ 3 ┆ 8589934592 ┆ 1073741824 ┆ 112 ┆ 129 ┆ c ┆ 0.12 ┆ false │ └─────┴────────────┴────────────┴──────┴──────┴─────┴──────┴───────┘ """ return self @unstable() def hist( self, bins: IntoExpr | None = None, *, bin_count: int | None = None, include_category: bool = False, include_breakpoint: bool = False, ) -> Expr: """ 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. Parameters ---------- bins Bin edges. If None given, we determine the edges based on the data. bin_count If `bins` is not provided, `bin_count` uniform bins are created that fully encompass the data. include_breakpoint Include a column that indicates the upper breakpoint. include_category Include a column that shows the intervals as categories. Returns ------- DataFrame Examples -------- >>> df = pl.DataFrame({"a": [1, 3, 8, 8, 2, 1, 3]}) >>> df.select(pl.col("a").hist(bins=[1, 2, 3])) shape: (2, 1) ┌─────┐ │ a │ │ --- │ │ u32 │ ╞═════╡ │ 3 │ │ 2 │ └─────┘ >>> df.select( ... pl.col("a").hist( ... bins=[1, 2, 3], include_breakpoint=True, include_category=True ... ) ... ) shape: (2, 1) ┌──────────────────────┐ │ a │ │ --- │ │ struct[3] │ ╞══════════════════════╡ │ {2.0,"[1.0, 2.0]",3} │ │ {3.0,"(2.0, 3.0]",2} │ └──────────────────────┘ """ if bins is not None: if isinstance(bins, list): bins = pl.Series(bins) bins_pyexpr = parse_into_expression(bins) else: bins_pyexpr = None return wrap_expr( self._pyexpr.hist( bins_pyexpr, bin_count, include_category, include_breakpoint ) ) def replace( self, old: IntoExpr | Sequence[Any] | Mapping[Any, Any], new: IntoExpr | Sequence[Any] | NoDefault = no_default, *, default: IntoExpr | NoDefault = no_default, return_dtype: PolarsDataType | None = None, ) -> Expr: """ Replace the given values by different values of the same data type. Parameters ---------- old Value or sequence of values to replace. Accepts expression input. Sequences are parsed as Series, other non-expression inputs are parsed as literals. Also accepts a mapping of values to their replacement as syntactic sugar for `replace(old=Series(mapping.keys()), new=Series(mapping.values()))`. new Value or sequence of values to replace by. Accepts expression input. Sequences are parsed as Series, other non-expression inputs are parsed as literals. Length must match the length of `old` or have length 1. default Set values that were not replaced to this value. Defaults to keeping the original value. Accepts expression input. Non-expression inputs are parsed as literals. .. deprecated:: 1.0.0 Use :meth:`replace_strict` instead to set a default while replacing values. return_dtype The data type of the resulting expression. If set to `None` (default), the data type of the original column is preserved. .. deprecated:: 1.0.0 Use :meth:`replace_strict` instead to set a return data type while replacing values, or explicitly call :meth:`cast` on the output. See Also -------- replace_strict str.replace Notes ----- The global string cache must be enabled when replacing categorical values. Examples -------- Replace a single value by another value. Values that were not replaced remain unchanged. >>> df = pl.DataFrame({"a": [1, 2, 2, 3]}) >>> df.with_columns(replaced=pl.col("a").replace(2, 100)) shape: (4, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════════╡ │ 1 ┆ 1 │ │ 2 ┆ 100 │ │ 2 ┆ 100 │ │ 3 ┆ 3 │ └─────┴──────────┘ Replace multiple values by passing sequences to the `old` and `new` parameters. >>> df.with_columns(replaced=pl.col("a").replace([2, 3], [100, 200])) shape: (4, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════════╡ │ 1 ┆ 1 │ │ 2 ┆ 100 │ │ 2 ┆ 100 │ │ 3 ┆ 200 │ └─────┴──────────┘ Passing a mapping with replacements is also supported as syntactic sugar. >>> mapping = {2: 100, 3: 200} >>> df.with_columns(replaced=pl.col("a").replace(mapping)) shape: (4, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════════╡ │ 1 ┆ 1 │ │ 2 ┆ 100 │ │ 2 ┆ 100 │ │ 3 ┆ 200 │ └─────┴──────────┘ The original data type is preserved when replacing by values of a different data type. Use :meth:`replace_strict` to replace and change the return data type. >>> df = pl.DataFrame({"a": ["x", "y", "z"]}) >>> mapping = {"x": 1, "y": 2, "z": 3} >>> df.with_columns(replaced=pl.col("a").replace(mapping)) shape: (3, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ str ┆ str │ ╞═════╪══════════╡ │ x ┆ 1 │ │ y ┆ 2 │ │ z ┆ 3 │ └─────┴──────────┘ Expression input is supported. >>> df = pl.DataFrame({"a": [1, 2, 2, 3], "b": [1.5, 2.5, 5.0, 1.0]}) >>> df.with_columns( ... replaced=pl.col("a").replace( ... old=pl.col("a").max(), ... new=pl.col("b").sum(), ... ) ... ) shape: (4, 3) ┌─────┬─────┬──────────┐ │ a ┆ b ┆ replaced │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ i64 │ ╞═════╪═════╪══════════╡ │ 1 ┆ 1.5 ┆ 1 │ │ 2 ┆ 2.5 ┆ 2 │ │ 2 ┆ 5.0 ┆ 2 │ │ 3 ┆ 1.0 ┆ 10 │ └─────┴─────┴──────────┘ """ if return_dtype is not None: issue_deprecation_warning( "the `return_dtype` parameter for `replace` is deprecated." " Use `replace_strict` instead to set a return data type while replacing values.", version="1.0.0", ) if default is not no_default: issue_deprecation_warning( "the `default` parameter for `replace` is deprecated." " Use `replace_strict` instead to set a default while replacing values.", version="1.0.0", ) return self.replace_strict( old, new, default=default, return_dtype=return_dtype ) if new is no_default: 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()) else: if isinstance(old, Sequence) and not isinstance(old, (str, pl.Series)): old = pl.Series(old) if isinstance(new, Sequence) and not isinstance(new, (str, pl.Series)): new = pl.Series(new) old_pyexpr = parse_into_expression(old, str_as_lit=True) # type: ignore[arg-type] new_pyexpr = parse_into_expression(new, str_as_lit=True) result = wrap_expr(self._pyexpr.replace(old_pyexpr, new_pyexpr)) if return_dtype is not None: result = result.cast(return_dtype) return result def replace_strict( self, old: IntoExpr | Sequence[Any] | Mapping[Any, Any], new: IntoExpr | Sequence[Any] | NoDefault = no_default, *, default: IntoExpr | NoDefault = no_default, return_dtype: PolarsDataType | pl.DataTypeExpr | None = None, ) -> Expr: """ Replace all values by different values. Parameters ---------- old Value or sequence of values to replace. Accepts expression input. Sequences are parsed as Series, other non-expression inputs are parsed as literals. Also accepts a mapping of values to their replacement as syntactic sugar for `replace_strict(old=Series(mapping.keys()), new=Series(mapping.values()))`. new Value or sequence of values to replace by. Accepts expression input. Sequences are parsed as Series, other non-expression inputs are parsed as literals. Length must match the length of `old` or have length 1. 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. See Also -------- replace str.replace Notes ----- The global string cache must be enabled when replacing categorical values. Examples -------- Replace values by passing sequences to the `old` and `new` parameters. >>> df = pl.DataFrame({"a": [1, 2, 2, 3]}) >>> df.with_columns( ... replaced=pl.col("a").replace_strict([1, 2, 3], [100, 200, 300]) ... ) shape: (4, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════════╡ │ 1 ┆ 100 │ │ 2 ┆ 200 │ │ 2 ┆ 200 │ │ 3 ┆ 300 │ └─────┴──────────┘ Passing a mapping with replacements is also supported as syntactic sugar. >>> mapping = {1: 100, 2: 200, 3: 300} >>> df.with_columns(replaced=pl.col("a").replace_strict(mapping)) shape: (4, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════════╡ │ 1 ┆ 100 │ │ 2 ┆ 200 │ │ 2 ┆ 200 │ │ 3 ┆ 300 │ └─────┴──────────┘ By default, an error is raised if any non-null values were not replaced. Specify a default to set all values that were not matched. >>> mapping = {2: 200, 3: 300} >>> df.with_columns( ... replaced=pl.col("a").replace_strict(mapping) ... ) # doctest: +SKIP Traceback (most recent call last): ... polars.exceptions.InvalidOperationError: incomplete mapping specified for `replace_strict` >>> df.with_columns(replaced=pl.col("a").replace_strict(mapping, default=-1)) shape: (4, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪══════════╡ │ 1 ┆ -1 │ │ 2 ┆ 200 │ │ 2 ┆ 200 │ │ 3 ┆ 300 │ └─────┴──────────┘ Replacing by values of a different data type sets the return type based on a combination of the `new` data type and the `default` data type. >>> df = pl.DataFrame({"a": ["x", "y", "z"]}) >>> mapping = {"x": 1, "y": 2, "z": 3} >>> df.with_columns(replaced=pl.col("a").replace_strict(mapping)) shape: (3, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════╪══════════╡ │ x ┆ 1 │ │ y ┆ 2 │ │ z ┆ 3 │ └─────┴──────────┘ >>> df.with_columns(replaced=pl.col("a").replace_strict(mapping, default="x")) shape: (3, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ str ┆ str │ ╞═════╪══════════╡ │ x ┆ 1 │ │ y ┆ 2 │ │ z ┆ 3 │ └─────┴──────────┘ Set the `return_dtype` parameter to control the resulting data type directly. >>> df.with_columns( ... replaced=pl.col("a").replace_strict(mapping, return_dtype=pl.UInt8) ... ) shape: (3, 2) ┌─────┬──────────┐ │ a ┆ replaced │ │ --- ┆ --- │ │ str ┆ u8 │ ╞═════╪══════════╡ │ x ┆ 1 │ │ y ┆ 2 │ │ z ┆ 3 │ └─────┴──────────┘ Expression input is supported for all parameters. >>> df = pl.DataFrame({"a": [1, 2, 2, 3], "b": [1.5, 2.5, 5.0, 1.0]}) >>> df.with_columns( ... replaced=pl.col("a").replace_strict( ... old=pl.col("a").max(), ... new=pl.col("b").sum(), ... default=pl.col("b"), ... ) ... ) shape: (4, 3) ┌─────┬─────┬──────────┐ │ a ┆ b ┆ replaced │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ f64 │ ╞═════╪═════╪══════════╡ │ 1 ┆ 1.5 ┆ 1.5 │ │ 2 ┆ 2.5 ┆ 2.5 │ │ 2 ┆ 5.0 ┆ 5.0 │ │ 3 ┆ 1.0 ┆ 10.0 │ └─────┴─────┴──────────┘ """ # noqa: W505 if new is no_default: 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()) old_pyexpr = parse_into_expression(old, str_as_lit=True) # type: ignore[arg-type] new_pyexpr = parse_into_expression(new, str_as_lit=True) # type: ignore[arg-type] dtype_pyexpr: plr.PyDataTypeExpr | None = None if return_dtype is not None: dtype_pyexpr = parse_into_datatype_expr(return_dtype)._pydatatype_expr else: dtype_pyexpr = None default_pyexpr = ( None if default is no_default else parse_into_expression(default, str_as_lit=True) ) return wrap_expr( self._pyexpr.replace_strict( old_pyexpr, new_pyexpr, default_pyexpr, dtype_pyexpr ) ) def bitwise_count_ones(self) -> Expr: """Evaluate the number of set bits.""" return wrap_expr(self._pyexpr.bitwise_count_ones()) def bitwise_count_zeros(self) -> Expr: """Evaluate the number of unset bits.""" return wrap_expr(self._pyexpr.bitwise_count_zeros()) def bitwise_leading_ones(self) -> Expr: """Evaluate the number most-significant set bits before seeing an unset bit.""" return wrap_expr(self._pyexpr.bitwise_leading_ones()) def bitwise_leading_zeros(self) -> Expr: """Evaluate the number most-significant unset bits before seeing a set bit.""" return wrap_expr(self._pyexpr.bitwise_leading_zeros()) def bitwise_trailing_ones(self) -> Expr: """Evaluate the number least-significant set bits before seeing an unset bit.""" return wrap_expr(self._pyexpr.bitwise_trailing_ones()) def bitwise_trailing_zeros(self) -> Expr: """Evaluate the number least-significant unset bits before seeing a set bit.""" return wrap_expr(self._pyexpr.bitwise_trailing_zeros()) def bitwise_and(self) -> Expr: """Perform an aggregation of bitwise ANDs. Examples -------- >>> df = pl.DataFrame({"n": [-1, 0, 1]}) >>> df.select(pl.col("n").bitwise_and()) shape: (1, 1) ┌─────┐ │ n │ │ --- │ │ i64 │ ╞═════╡ │ 0 │ └─────┘ >>> df = pl.DataFrame( ... {"grouper": ["a", "a", "a", "b", "b"], "n": [-1, 0, 1, -1, 1]} ... ) >>> df.group_by("grouper", maintain_order=True).agg(pl.col("n").bitwise_and()) shape: (2, 2) ┌─────────┬─────┐ │ grouper ┆ n │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════════╪═════╡ │ a ┆ 0 │ │ b ┆ 1 │ └─────────┴─────┘ """ return wrap_expr(self._pyexpr.bitwise_and()) def bitwise_or(self) -> Expr: """Perform an aggregation of bitwise ORs. Examples -------- >>> df = pl.DataFrame({"n": [-1, 0, 1]}) >>> df.select(pl.col("n").bitwise_or()) shape: (1, 1) ┌─────┐ │ n │ │ --- │ │ i64 │ ╞═════╡ │ -1 │ └─────┘ >>> df = pl.DataFrame( ... {"grouper": ["a", "a", "a", "b", "b"], "n": [-1, 0, 1, -1, 1]} ... ) >>> df.group_by("grouper", maintain_order=True).agg(pl.col("n").bitwise_or()) shape: (2, 2) ┌─────────┬─────┐ │ grouper ┆ n │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════════╪═════╡ │ a ┆ -1 │ │ b ┆ -1 │ └─────────┴─────┘ """ return wrap_expr(self._pyexpr.bitwise_or()) def bitwise_xor(self) -> Expr: """Perform an aggregation of bitwise XORs. Examples -------- >>> df = pl.DataFrame({"n": [-1, 0, 1]}) >>> df.select(pl.col("n").bitwise_xor()) shape: (1, 1) ┌─────┐ │ n │ │ --- │ │ i64 │ ╞═════╡ │ -2 │ └─────┘ >>> df = pl.DataFrame( ... {"grouper": ["a", "a", "a", "b", "b"], "n": [-1, 0, 1, -1, 1]} ... ) >>> df.group_by("grouper", maintain_order=True).agg(pl.col("n").bitwise_xor()) shape: (2, 2) ┌─────────┬─────┐ │ grouper ┆ n │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═════════╪═════╡ │ a ┆ -2 │ │ b ┆ -2 │ └─────────┴─────┘ """ return wrap_expr(self._pyexpr.bitwise_xor()) @deprecated( "`register_plugin` is deprecated; " "use `polars.plugins.register_plugin_function` instead." ) def register_plugin( self, *, lib: str, symbol: str, args: list[IntoExpr] | None = None, kwargs: dict[Any, Any] | None = None, is_elementwise: bool = False, input_wildcard_expansion: bool = False, returns_scalar: bool = False, cast_to_supertypes: bool = False, pass_name_to_apply: bool = False, changes_length: bool = False, ) -> Expr: """ Register a plugin function. .. deprecated:: 0.20.16 Use :func:`polars.plugins.register_plugin_function` instead. See the `user guide <https://docs.pola.rs/user-guide/plugins/>`_ for more information about plugins. Warnings -------- This method is deprecated. Use the new `polars.plugins.register_plugin_function` function instead. This is highly unsafe as this will call the C function loaded by `lib::symbol`. The parameters you set dictate how Polars will handle the function. Make sure they are correct! Parameters ---------- lib Library to load. symbol Function to load. args Arguments (other than self) passed to this function. These arguments have to be of type Expression. kwargs Non-expression arguments. They must be JSON serializable. is_elementwise If the function only operates on scalars this will trigger fast paths. input_wildcard_expansion Expand expressions as input of this function. returns_scalar Automatically explode on unit length if it ran as final aggregation. this is the case for aggregations like `sum`, `min`, `covariance` etc. cast_to_supertypes Cast the input datatypes to their supertype. pass_name_to_apply if set, then the `Series` passed to the function in the group_by operation will ensure the name is set. This is an extra heap allocation per group. changes_length For example a `unique` or a `slice` """ from polars.plugins import register_plugin_function if args is None: args = [self] else: args = [self, *list(args)] return register_plugin_function( plugin_path=lib, function_name=symbol, args=args, kwargs=kwargs, is_elementwise=is_elementwise, changes_length=changes_length, returns_scalar=returns_scalar, cast_to_supertype=cast_to_supertypes, input_wildcard_expansion=input_wildcard_expansion, pass_name_to_apply=pass_name_to_apply, ) def _row_encode( self, *, unordered: bool = False, descending: bool | None = None, nulls_last: bool | None = None, ) -> Expr: return F._row_encode( [self], unordered=unordered, descending=None if descending is None else [descending], nulls_last=None if nulls_last is None else [nulls_last], ) def _row_decode( self, names: Sequence[str], dtypes: Sequence[pl.DataTypeExpr | PolarsDataType], *, unordered: bool = False, descending: Sequence[bool] | None = None, nulls_last: Sequence[bool] | None = None, ) -> Expr: dtypes_pyexprs = [ parse_into_datatype_expr(dtype)._pydatatype_expr for dtype in dtypes ] if unordered: assert descending is None assert nulls_last is None result = self._pyexpr.row_decode_unordered(names, dtypes_pyexprs) else: result = self._pyexpr.row_decode_ordered( names, dtypes_pyexprs, descending, nulls_last ) return wrap_expr(result) @classmethod def from_json(cls, value: str) -> Expr: """ Read an expression from a JSON encoded string to construct an Expression. .. deprecated:: 0.20.11 This method has been renamed to :meth:`deserialize`. Note that the new method operates on file-like inputs rather than strings. Enclose your input in `io.StringIO` to keep the same behavior. Parameters ---------- value JSON encoded string value """ issue_deprecation_warning( "`Expr.from_json` is deprecated. It has been renamed to `Expr.deserialize`." " Note that the new method operates on file-like inputs rather than strings." " Enclose your input in `io.StringIO` to keep the same behavior.", version="0.20.11", ) return cls.deserialize(StringIO(value), format="json") @property def bin(self) -> ExprBinaryNameSpace: """ Create an object namespace of all binary related methods. See the individual method pages for full details """ return ExprBinaryNameSpace(self) @property def cat(self) -> ExprCatNameSpace: """ Create an object namespace of all categorical related methods. See the individual method pages for full details Examples -------- >>> df = pl.DataFrame({"values": ["a", "b"]}).select( ... pl.col("values").cast(pl.Categorical) ... ) >>> df.select(pl.col("values").cat.get_categories()) shape: (2, 1) ┌────────┐ │ values │ │ --- │ │ str │ ╞════════╡ │ a │ │ b │ └────────┘ """ return ExprCatNameSpace(self) @property def dt(self) -> ExprDateTimeNameSpace: """Create an object namespace of all datetime related methods.""" return ExprDateTimeNameSpace(self) # Keep the `list` and `str` properties below at the end of the definition of Expr, # as to not confuse mypy with the type annotation `str` and `list` @property def list(self) -> ExprListNameSpace: """ Create an object namespace of all list related methods. See the individual method pages for full details. """ return ExprListNameSpace(self) @property def arr(self) -> ExprArrayNameSpace: """ Create an object namespace of all array related methods. See the individual method pages for full details. """ return ExprArrayNameSpace(self) @property def meta(self) -> ExprMetaNameSpace: """ Create an object namespace of all meta related expression methods. This can be used to modify and traverse existing expressions. """ return ExprMetaNameSpace(self) @property def name(self) -> ExprNameNameSpace: """ Create an object namespace of all expressions that modify expression names. See the individual method pages for full details. """ return ExprNameNameSpace(self) @property def str(self) -> ExprStringNameSpace: """ Create an object namespace of all string related methods. See the individual method pages for full details. Examples -------- >>> df = pl.DataFrame({"letters": ["a", "b"]}) >>> df.select(pl.col("letters").str.to_uppercase()) shape: (2, 1) ┌─────────┐ │ letters │ │ --- │ │ str │ ╞═════════╡ │ A │ │ B │ └─────────┘ """ return ExprStringNameSpace(self) @property def struct(self) -> ExprStructNameSpace: """ Create an object namespace of all struct related methods. See the individual method pages for full details. Examples -------- >>> df = ( ... pl.DataFrame( ... { ... "int": [1, 2], ... "str": ["a", "b"], ... "bool": [True, None], ... "list": [[1, 2], [3]], ... } ... ) ... .to_struct("my_struct") ... .to_frame() ... ) >>> df.select(pl.col("my_struct").struct.field("str")) shape: (2, 1) ┌─────┐ │ str │ │ --- │ │ str │ ╞═════╡ │ a │ │ b │ └─────┘ """ return ExprStructNameSpace(self) @property def ext(self) -> ExprExtensionNameSpace: """ Create an object namespace of all extension type related expressions. See the individual method pages for full details. """ return ExprExtensionNameSpace(self) def _skip_batch_predicate(self, schema: SchemaDict) -> Expr | None: result = self._pyexpr.skip_batch_predicate(schema) if result is None: return None return wrap_expr(result) def _prepare_alpha( com: float | int | None = None, span: float | int | None = None, half_life: float | int | None = None, alpha: float | int | None = None, ) -> float: """Normalise EWM decay specification in terms of smoothing factor 'alpha'.""" if sum((param is not None) for param in (com, span, half_life, alpha)) > 1: msg = ( "parameters `com`, `span`, `half_life`, and `alpha` are mutually exclusive" ) raise ValueError(msg) if com is not None: if com < 0.0: msg = f"require `com` >= 0 (found {com!r})" raise ValueError(msg) alpha = 1.0 / (1.0 + com) elif span is not None: if span < 1.0: msg = f"require `span` >= 1 (found {span!r})" raise ValueError(msg) alpha = 2.0 / (span + 1.0) elif half_life is not None: if half_life <= 0.0: msg = f"require `half_life` > 0 (found {half_life!r})" raise ValueError(msg) alpha = 1.0 - math.exp(-math.log(2.0) / half_life) elif alpha is None: msg = "one of `com`, `span`, `half_life`, or `alpha` must be set" raise ValueError(msg) elif not (0 < alpha <= 1): msg = f"require 0 < `alpha` <= 1 (found {alpha!r})" raise ValueError(msg) return alpha def _prepare_rolling_by_window_args(window_size: timedelta | str) -> str: if isinstance(window_size, timedelta): window_size = parse_as_duration_string(window_size) return window_size
Expr
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_contextlib.py
{ "start": 46034, "end": 47692 }
class ____(__TestCase): def make_relative_path(self, *parts): return os.path.join( os.path.dirname(os.path.realpath(__file__)), *parts, ) def test_simple(self): old_cwd = os.getcwd() target = self.make_relative_path('data') self.assertNotEqual(old_cwd, target) with chdir(target): self.assertEqual(os.getcwd(), target) self.assertEqual(os.getcwd(), old_cwd) @unittest.skip("Missing archivetestdata") def test_reentrant(self): old_cwd = os.getcwd() target1 = self.make_relative_path('data') target2 = self.make_relative_path('archivetestdata') self.assertNotIn(old_cwd, (target1, target2)) chdir1, chdir2 = chdir(target1), chdir(target2) with chdir1: self.assertEqual(os.getcwd(), target1) with chdir2: self.assertEqual(os.getcwd(), target2) with chdir1: self.assertEqual(os.getcwd(), target1) self.assertEqual(os.getcwd(), target2) self.assertEqual(os.getcwd(), target1) self.assertEqual(os.getcwd(), old_cwd) def test_exception(self): old_cwd = os.getcwd() target = self.make_relative_path('data') self.assertNotEqual(old_cwd, target) try: with chdir(target): self.assertEqual(os.getcwd(), target) raise RuntimeError("boom") except RuntimeError as re: self.assertEqual(str(re), "boom") self.assertEqual(os.getcwd(), old_cwd) if __name__ == "__main__": run_tests()
TestChdir
python
tornadoweb__tornado
tornado/test/auth_test.py
{ "start": 22326, "end": 23311 }
class ____(AsyncHTTPTestCase): def get_app(self): return Application( [ # test endpoints ("/client/login", GoogleLoginHandler, dict(test=self)), # simulated google authorization server endpoints ("/google/oauth2/authorize", GoogleOAuth2AuthorizeHandler), ("/google/oauth2/token", GoogleOAuth2TokenHandler), ("/google/oauth2/userinfo", GoogleOAuth2UserinfoHandler), ], google_oauth={ "key": "fake_google_client_id", "secret": "fake_google_client_secret", }, ) def test_google_login(self): response = self.fetch("/client/login") self.assertDictEqual( { "name": "Foo", "email": "foo@example.com", "access_token": "fake-access-token", }, json_decode(response.body), )
GoogleOAuth2Test
python
astropy__astropy
astropy/utils/misc.py
{ "start": 1826, "end": 3608 }
class ____: """A noop writeable object.""" def write(self, s: str) -> None: pass @contextlib.contextmanager def silence() -> Generator[None, None, None]: """A context manager that silences sys.stdout and sys.stderr.""" old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = _DummyFile() sys.stderr = _DummyFile() yield sys.stdout = old_stdout sys.stderr = old_stderr @deprecated(since="7.0") def format_exception(msg, *args, **kwargs): """Fill in information about the exception that occurred. Given an exception message string, uses new-style formatting arguments ``{filename}``, ``{lineno}``, ``{func}`` and/or ``{text}`` to fill in information about the exception that occurred. For example: try: 1/0 except: raise ZeroDivisionError( format_except('A divide by zero occurred in {filename} at ' 'line {lineno} of function {func}.')) Any additional positional or keyword arguments passed to this function are also used to format the message. .. note:: This uses `sys.exc_info` to gather up the information needed to fill in the formatting arguments. Since `sys.exc_info` is not carried outside a handled exception, it's not wise to use this outside of an ``except`` clause - if it is, this will substitute '<unknown>' for the 4 formatting arguments. """ tb = traceback.extract_tb(sys.exc_info()[2], limit=1) if len(tb) > 0: filename, lineno, func, text = tb[0] else: filename = lineno = func = text = "<unknown>" return msg.format( *args, filename=filename, lineno=lineno, func=func, text=text, **kwargs )
_DummyFile
python
ansible__ansible
lib/ansible/_internal/_ssh/_ssh_agent.py
{ "start": 4883, "end": 4963 }
class ____(bytes): def to_blob(self) -> bytes: return self
constraints
python
airbytehq__airbyte
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
{ "start": 12268, "end": 12544 }
class ____(Installs): def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: return f"raw-data/export/app/{self.app_id}/installs-retarget/v5"
RetargetingInstalls
python
pytorch__pytorch
test/quantization/core/experimental/test_adaround_eager.py
{ "start": 535, "end": 4968 }
class ____(QuantizationTestCase): def feedforawrd_callback( self, model, data, ) -> None: model(data) def feedforawrd_callback_with_wrapper(self, model, data, wrapper) -> None: wrapper(model, data) def run_adaround(self, model, img_data, wrapper=None): adaround_optimizer = AdaptiveRoundingOptimizer( model, self.feedforawrd_callback if wrapper is None else self.feedforawrd_callback_with_wrapper, forward_wrapper, img_data, max_iter=100, batch_size=10, feed_forward_wrapper=wrapper, ) adarounded_model = adaround_optimizer.run_adaround() return adarounded_model def get_fake_quant(self, model): hard_fake_quant_model = copy.deepcopy(model) for _, module in hard_fake_quant_model.named_modules(): if isinstance(module, (torch.nn.Linear, torch.nn.Conv2d)): weight_observer = MinMaxObserver( quant_min=-128, quant_max=127, dtype=torch.qint8, qscheme=torch.per_tensor_symmetric, ) weight_observer(module.weight) scale, zero_point = weight_observer.calculate_qparams() fake_quant_module = torch.fake_quantize_per_tensor_affine( module.weight, scale=scale, zero_point=zero_point, quant_min=-128, quant_max=127, ) module.weight.data.copy_(fake_quant_module) return hard_fake_quant_model def get_feed_forward_wrapper(self): class FeedForwardWrapper(nn.Module): def __init__(self) -> None: super().__init__() def forward(self, model, sample): return model(sample) wrapper_module = FeedForwardWrapper() return wrapper_module def test_linear_chain(self): class LinearChain(nn.Module): def __init__(self) -> None: super().__init__() self.linear1 = nn.Linear(3, 4) self.linear2 = nn.Linear(4, 5) self.linear3 = nn.Linear(5, 6) def forward(self, x): x = self.linear1(x) x = self.linear2(x) x = self.linear3(x) return x float_model = LinearChain() img_data = [torch.rand(10, 3, dtype=torch.float) for _ in range(50)] adarounded_model = self.run_adaround( float_model, img_data, self.get_feed_forward_wrapper() ) fq_model = self.get_fake_quant(float_model) rand_input = torch.rand(10, 3) with torch.no_grad(): ada_out = adarounded_model(rand_input) fq_out = fq_model(rand_input) float_out = float_model(rand_input) ada_loss = F.mse_loss(ada_out, float_out) fq_loss = F.mse_loss(fq_out, float_out) self.assertTrue(ada_loss.item() < fq_loss.item()) def test_conv_chain(self): class ConvChain(nn.Module): def __init__(self) -> None: super().__init__() self.conv2d1 = nn.Conv2d(3, 4, 5, 5) self.conv2d2 = nn.Conv2d(4, 5, 5, 5) self.conv2d3 = nn.Conv2d(5, 6, 5, 5) def forward(self, x): x = self.conv2d1(x) x = self.conv2d2(x) x = self.conv2d3(x) return x float_model = ConvChain() img_data = [torch.rand(10, 3, 125, 125, dtype=torch.float) for _ in range(50)] adarounded_model = self.run_adaround(float_model, img_data) fq_model = self.get_fake_quant(float_model) rand_input = torch.rand(10, 3, 256, 256) with torch.no_grad(): ada_out = adarounded_model(rand_input) fq_out = fq_model(rand_input) float_out = float_model(rand_input) ada_loss = F.mse_loss(ada_out, float_out) fq_loss = F.mse_loss(fq_out, float_out) self.assertTrue(ada_loss.item() < fq_loss.item()) if __name__ == "__main__": raise RuntimeError( "This test is not currently used and should be " "enabled in discover_tests.py if required." )
TestAdaround
python
joke2k__faker
faker/providers/person/fr_FR/__init__.py
{ "start": 44, "end": 12902 }
class ____(PersonProvider): formats_female = ( "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}}", "{{first_name_female}} {{prefix}} {{last_name}}", "{{first_name_female}} {{last_name}}-{{last_name}}", "{{first_name_female}}-{{first_name_female}} {{last_name}}", "{{first_name_female}} {{last_name}} {{prefix}} {{last_name}}", ) formats_male = ( "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}}", "{{first_name_male}} {{prefix}} {{last_name}}", "{{first_name_male}} {{last_name}}-{{last_name}}", "{{first_name_male}}-{{first_name_male}} {{last_name}}", "{{first_name_male}} {{last_name}} {{prefix}} {{last_name}}", ) formats = formats_male + formats_female first_names_male = ( "Adrien", "Aimé", "Alain", "Alexandre", "Alfred", "Alphonse", "André", "Antoine", "Arthur", "Auguste", "Augustin", "Benjamin", "Benoît", "Bernard", "Bertrand", "Charles", "Christophe", "Daniel", "David", "Denis", "Édouard", "Émile", "Emmanuel", "Éric", "Étienne", "Eugène", "François", "Franck", "Frédéric", "Gabriel", "Georges", "Gérard", "Gilbert", "Gilles", "Grégoire", "Guillaume", "Guy", "William", "Henri", "Honoré", "Hugues", "Isaac", "Jacques", "Jean", "Jérôme", "Joseph", "Jules", "Julien", "Laurent", "Léon", "Louis", "Luc", "Lucas", "Marc", "Marcel", "Martin", "Matthieu", "Maurice", "Michel", "Nicolas", "Noël", "Olivier", "Patrick", "Paul", "Philippe", "Pierre", "Raymond", "Rémy", "René", "Richard", "Robert", "Roger", "Roland", "Sébastien", "Stéphane", "Théodore", "Théophile", "Thibaut", "Thibault", "Thierry", "Thomas", "Timothée", "Tristan", "Victor", "Vincent", "Xavier", "Yves", "Zacharie", ) first_names_female = ( "Adélaïde", "Adèle", "Adrienne", "Agathe", "Agnès", "Aimée", "Alexandrie", "Alix", "Alexandria", "Alex", "Alice", "Amélie", "Anaïs", "Anastasie", "Andrée", "Anne", "Anouk", "Antoinette", "Arnaude", "Astrid", "Audrey", "Aurélie", "Aurore", "Bernadette", "Brigitte", "Capucine", "Caroline", "Catherine", "Cécile", "Céline", "Célina", "Chantal", "Charlotte", "Christelle", "Christiane", "Christine", "Claire", "Claudine", "Clémence", "Colette", "Constance", "Corinne", "Danielle", "Denise", "Diane", "Dorothée", "Édith", "Éléonore", "Élisabeth", "Élise", "Élodie", "Émilie", "Emmanuelle", "Françoise", "Frédérique", "Gabrielle", "Geneviève", "Hélène", "Henriette", "Hortense", "Inès", "Isabelle", "Jacqueline", "Jeanne", "Jeannine", "Joséphine", "Josette", "Julie", "Juliette", "Laetitia", "Laure", "Laurence", "Lorraine", "Louise", "Luce", "Lucie", "Lucy", "Madeleine", "Manon", "Marcelle", "Margaux", "Margaud", "Margot", "Marguerite", "Margot", "Margaret", "Maggie", "Marianne", "Marie", "Marine", "Marthe", "Martine", "Maryse", "Mathilde", "Michèle", "Michelle", "Michelle", "Monique", "Nathalie", "Nath", "Nathalie", "Nicole", "Noémi", "Océane", "Odette", "Olivie", "Patricia", "Paulette", "Pauline", "Pénélope", "Philippine", "Renée", "Sabine", "Simone", "Sophie", "Stéphanie", "Susanne", "Suzanne", "Susan", "Suzanne", "Sylvie", "Thérèse", "Valentine", "Valérie", "Véronique", "Victoire", "Virginie", "Zoé", "Camille", "Claude", "Dominique", ) first_names = first_names_male + first_names_female last_names = ( "Martin", "Bernard", "Thomas", "Robert", "Petit", "Dubois", "Richard", "Garcia", "Durand", "Moreau", "Lefebvre", "Simon", "Laurent", "Michel", "Leroy", "Martinez", "David", "Fontaine", "Da Silva", "Morel", "Fournier", "Dupont", "Bertrand", "Lambert", "Rousseau", "Girard", "Roux", "Vincent", "Lefèvre", "Boyer", "Lopez", "Bonnet", "Andre", "François", "Mercier", "Muller", "Guérin", "Legrand", "Sanchez", "Garnier", "Chevalier", "Faure", "Perez", "Clément", "Fernandez", "Blanc", "Robin", "Morin", "Gauthier", "Pereira", "Perrin", "Roussel", "Henry", "Duval", "Gautier", "Nicolas", "Masson", "Marie", "Noël", "Ferreira", "Lemaire", "Mathieu", "Rivière", "Denis", "Marchand", "Rodriguez", "Dumont", "Payet", "Lucas", "Dufour", "Dos Santos", "Joly", "Blanchard", "Meunier", "Rodrigues", "Caron", "Gérard", "Fernandes", "Brunet", "Meyer", "Barbier", "Leroux", "Renard", "Goncalves", "Gaillard", "Brun", "Roy", "Picard", "Giraud", "Roger", "Schmitt", "Colin", "Arnaud", "Vidal", "Gonzalez", "Lemoine", "Roche", "Aubert", "Olivier", "Leclercq", "Pierre", "Philippe", "Bourgeois", "Renaud", "Martins", "Leclerc", "Guillaume", "Lacroix", "Lecomte", "Benoit", "Fabre", "Carpentier", "Vasseur", "Louis", "Hubert", "Jean", "Dumas", "Rolland", "Grondin", "Rey", "Huet", "Gomez", "Dupuis", "Guillot", "Berger", "Moulin", "Hoarau", "Menard", "Deschamps", "Fleury", "Adam", "Boucher", "Poirier", "Bertin", "Charles", "Aubry", "Da Costa", "Royer", "Dupuy", "Maillard", "Paris", "Baron", "Lopes", "Guyot", "Carre", "Jacquet", "Renault", "Hervé", "Charpentier", "Klein", "Cousin", "Collet", "Léger", "Ribeiro", "Hernandez", "Bailly", "Schneider", "Le Gall", "Ruiz", "Langlois", "Bouvier", "Gomes", "Prévost", "Julien", "Lebrun", "Breton", "Germain", "Millet", "Boulanger", "Rémy", "Le Roux", "Daniel", "Marques", "Maillot", "Leblanc", "Le Goff", "Barre", "Perrot", "Lévêque", "Marty", "Benard", "Monnier", "Hamon", "Pelletier", "Alves", "Étienne", "Marchal", "Poulain", "Tessier", "Lemaître", "Guichard", "Besson", "Mallet", "Hoareau", "Gillet", "Weber", "Jacob", "Collin", "Chevallier", "Perrier", "Michaud", "Carlier", "Delaunay", "Chauvin", "Alexandre", "Maréchal", "Antoine", "Lebon", "Cordier", "Lejeune", "Bouchet", "Pasquier", "Legros", "Delattre", "Humbert", "De Oliveira", "Briand", "Lamy", "Launay", "Gilbert", "Perret", "Lesage", "Gay", "Nguyen", "Navarro", "Besnard", "Pichon", "Hebert", "Cohen", "Pons", "Lebreton", "Sauvage", "De Sousa", "Pineau", "Albert", "Jacques", "Pinto", "Barthelemy", "Turpin", "Bigot", "Lelièvre", "Georges", "Reynaud", "Ollivier", "Martel", "Voisin", "Leduc", "Guillet", "Vallée", "Coulon", "Camus", "Marin", "Teixeira", "Costa", "Mahe", "Didier", "Charrier", "Gaudin", "Bodin", "Guillou", "Grégoire", "Gros", "Blanchet", "Buisson", "Blondel", "Paul", "Dijoux", "Barbe", "Hardy", "Laine", "Evrard", "Laporte", "Rossi", "Joubert", "Regnier", "Tanguy", "Gimenez", "Allard", "Devaux", "Morvan", "Lévy", "Dias", "Courtois", "Lenoir", "Berthelot", "Pascal", "Vaillant", "Guilbert", "Thibault", "Moreno", "Duhamel", "Colas", "Masse", "Baudry", "Bruneau", "Verdier", "Delorme", "Blin", "Guillon", "Mary", "Coste", "Pruvost", "Maury", "Allain", "Valentin", "Godard", "Joseph", "Brunel", "Marion", "Texier", "Seguin", "Raynaud", "Bourdon", "Raymond", "Bonneau", "Chauvet", "Maurice", "Legendre", "Loiseau", "Ferrand", "Toussaint", "Techer", "Lombard", "Lefort", "Couturier", "Bousquet", "Diaz", "Riou", "Clerc", "Weiss", "Imbert", "Jourdan", "Delahaye", "Gilles", "Guibert", "Bègue", "Descamps", "Delmas", "Peltier", "Dupré", "Chartier", "Martineau", "Laroche", "Leconte", "Maillet", "Parent", "Labbé", "Potier", "Bazin", "Normand", "Pottier", "Torres", "Lagarde", "Blot", "Jacquot", "Lemonnier", "Grenier", "Rocher", "Bonnin", "Boutin", "Fischer", "Munoz", "Neveu", "Lacombe", "Mendès", "Delannoy", "Auger", "Wagner", "Fouquet", "Mace", "Ramos", "Pages", "Petitjean", "Chauveau", "Foucher", "Peron", "Guyon", "Gallet", "Rousset", "Traore", "Bernier", "Vallet", "Letellier", "Bouvet", "Hamel", "Chrétien", "Faivre", "Boulay", "Thierry", "Samson", "Ledoux", "Salmon", "Gosselin", "Lecoq", "Pires", "Leleu", "Becker", "Diallo", "Merle", "Valette", ) prefixes = ("de", "de la", "Le", "du")
Provider
python
pytorch__pytorch
torch/_dynamo/variables/user_defined.py
{ "start": 79397, "end": 80306 }
class ____(UserDefinedObjectVariable): @staticmethod def is_matching_object(obj): mod = sys.modules.get("torchrec.sparse.jagged_tensor") return mod is not None and type(obj) is mod.KeyedJaggedTensor def __init__(self, value, **kwargs) -> None: from torchrec.sparse.jagged_tensor import KeyedJaggedTensor assert type(value) is KeyedJaggedTensor super().__init__(value, **kwargs) def var_getattr(self, tx: "InstructionTranslator", name): if ( torch._dynamo.config.force_unspec_int_unbacked_size_like_on_torchrec_kjt and self.source is not None and name in ("_length_per_key", "_offset_per_key") ): with TracingContext.patch(force_unspec_int_unbacked_size_like=True): return super().var_getattr(tx, name) return super().var_getattr(tx, name)
KeyedJaggedTensorVariable
python
huggingface__transformers
tests/models/yoso/test_modeling_yoso.py
{ "start": 12295, "end": 14210 }
class ____(unittest.TestCase): @slow def test_inference_no_head(self): model = YosoModel.from_pretrained("uw-madison/yoso-4096") input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) with torch.no_grad(): output = model(input_ids)[0] expected_shape = torch.Size((1, 6, 768)) self.assertEqual(output.shape, expected_shape) expected_slice = torch.tensor( [[[-0.0611, 0.1242, 0.0840], [0.0280, -0.0048, 0.1125], [0.0106, 0.0226, 0.0751]]] ) torch.testing.assert_close(output[:, :3, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_masked_lm(self): model = YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096") input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]]) with torch.no_grad(): output = model(input_ids)[0] vocab_size = 50265 expected_shape = torch.Size((1, 6, vocab_size)) self.assertEqual(output.shape, expected_shape) expected_slice = torch.tensor( [[[-2.1313, -3.7285, -2.2407], [-2.7047, -3.3314, -2.6408], [0.0629, -2.5166, -0.3356]]] ) torch.testing.assert_close(output[:, :3, :3], expected_slice, rtol=1e-4, atol=1e-4) @slow def test_inference_masked_lm_long_input(self): model = YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096") input_ids = torch.arange(4096).unsqueeze(0) with torch.no_grad(): output = model(input_ids)[0] vocab_size = 50265 expected_shape = torch.Size((1, 4096, vocab_size)) self.assertEqual(output.shape, expected_shape) expected_slice = torch.tensor( [[[-2.3914, -4.3742, -5.0956], [-4.0988, -4.2384, -7.0406], [-3.1427, -3.7192, -6.6800]]] ) torch.testing.assert_close(output[:, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
YosoModelIntegrationTest
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/dynamic_ragged_shape.py
{ "start": 80630, "end": 124129 }
class ____: """A _Broadcaster represents a transformation from one shape to another. It provides a transform for each axis of the source shape to the corresponding axis of the destination shape. """ def __init__(self, source_shape, target_shape, layer_broadcasters, dtype=None): """Create a broadcaster. Do not call directly. The source_shape, target_shape, and layer_broadcasters are converted to have the same dtype. Note: source_shape.rank and target_shape.rank must be known. Args: source_shape: the source DynamicRaggedShape target_shape: the target DynamicRaggedShape layer_broadcasters: List[_LayerBroadcaster] of length source_shape.rank. dtype: the preferred dtype of the broadcaster. Raises: TypeError: if the input types don't match. """ if not isinstance(source_shape, DynamicRaggedShape): raise TypeError("source_shape is not a DynamicRaggedShape") if not isinstance(target_shape, DynamicRaggedShape): raise TypeError("target_shape is not a DynamicRaggedShape") if not isinstance(layer_broadcasters, list): raise TypeError("layer_broadcasters not a list: " + str(layer_broadcasters)) for bc in layer_broadcasters: if not isinstance(bc, _LayerBroadcaster): raise TypeError("Not a LayerBroadcaster: " + str(bc)) dtype = _find_dtype(source_shape, dtype) dtype = _find_dtype(target_shape, dtype) dtype = _find_dtype_iterable(layer_broadcasters, dtype) dtype = _find_dtype(dtypes.int64, dtype) self._source_shape = source_shape.with_dtype(dtype) self._target_shape = target_shape.with_dtype(dtype) self._layer_broadcasters = [x.with_dtype(dtype) for x in layer_broadcasters] def __repr__(self): return ("{src_shape:" + str(self._source_shape) + ", target_shape:" + str(self._target_shape) + " layer_broadcasters: " + str(self._layer_broadcasters) + "}") def with_dtype(self, dtype): """Return a copy of this Broadcaster with a different dtype.""" return _Broadcaster(self._source_shape, self._target_shape, self._layer_broadcasters, dtype) @property def source_shape(self): return self._source_shape @property def target_shape(self): return self._target_shape @property def dtype(self): return self._source_shape.dtype def _target_inner_shape_int32(self): new_inner_shape = self.target_shape.inner_shape if new_inner_shape.dtype == dtypes.int64: new_inner_shape = math_ops.cast(new_inner_shape, dtype=dtypes.int32) return new_inner_shape # pylint:disable=protected-access def broadcast_flat_values(self, rt, inner_dimensions=True): """flat_values of a ragged tensor broadcast to target_shape. If inner_dimensions==True, then the result is a dense tensor with shape target_shape.inner_shape, the flat values of the broadcasted shape. If you add target_shape.row_partitions, you will get the full broadcasted shape. If inner_dimensions==False, the result is a dense tensor that satisfies certain properties: 1. broadcast_to(result, target_shape.inner_shape) will give the result if inner_dimensions==True. 2. Either (a) (result.rank < target_shape.inner_rank) or (b) (result.shape[0] == target_shape.inner_shape[0]). 3. result.rank = min(target_shape.inner_rank, rt.rank) 4. For i < target_shape.inner_rank - 1, and i < rt.rank, and if rt.shape[-i]!=1, then result.shape[-i]=target_shape[-i]. Args: rt: a ragged or dense tensor. inner_dimensions: if true, broadcast the inner dimensions as well. Returns: a dense tensor """ if ragged_tensor.is_ragged(rt): rt = rt.flat_values # If rt was a regular tensor, it is its own flat_values. if self.target_shape.rank == 0: return rt inner_rank = self.target_shape.inner_rank if inner_rank > self._source_shape.rank: # The dense rank is larger than the whole shape. So, we make the shape # dense. if self.source_shape.num_row_partitions > 0: rt = array_ops.reshape( rt, self.source_shape._alt_inner_shape(self.source_shape.rank)) # rt.rank == self._source_shape.rank < inner_rank # Here, property 2a holds. if inner_dimensions: return array_ops.broadcast_to(rt, self._target_inner_shape_int32()) return rt else: if self._source_shape.inner_rank != inner_rank: rt = array_ops.reshape(rt, self._source_shape._alt_inner_shape(inner_rank)) # pylint:disable=protected-access # After the reshape, rt is flat_values with inner_rank. flat_broadcaster = self._layer_broadcasters[-inner_rank] rt = flat_broadcaster.broadcast_tensor(rt) # Here, property 2b holds. if inner_dimensions: rt = array_ops.broadcast_to(rt, self._target_inner_shape_int32()) return rt def broadcast(self, rt): """Broadcast a tensor of source_shape to target_shape.""" flat_values = self.broadcast_flat_values(rt) return self.target_shape._add_row_partitions(flat_values) # pylint:disable=protected-access def _get_layer_broadcasters_from_rps(zero_broadcaster, source_rps, target_rps): """Get LayerBroadcasters from RowPartitions. *--zero_broadcaster->* | | source_rps[0] target_rps[0] | | V V *---result[1]------->* | | source_rps[1] target_rps[1] | | V V *---result[2]------->* . . . *---result[k-1]----->* | | source_rps[k] target_rps[k] | | V V *---result[k]------->* Note: result[0] = zero_broadcaster Args: zero_broadcaster: a broadcaster between the source and target row partitions' rows, and equal to result[0]. source_rps: source row partitions. target_rps: target row partitions (same length as source_rps). Returns: result: a list of LayerBroadcasters. """ if not isinstance(zero_broadcaster, _LayerBroadcaster): raise TypeError("Not a _LayerBroadcaster: " + str(zero_broadcaster)) assert len(source_rps) == len(target_rps) if not source_rps: return [zero_broadcaster] next_broadcaster = zero_broadcaster.next_layer(source_rps[0], target_rps[0]) tail_broadcasters = _get_layer_broadcasters_from_rps(next_broadcaster, source_rps[1:], target_rps[1:]) return [zero_broadcaster] + tail_broadcasters def _get_broadcaster(source_shape, target_shape): """Get a _Broadcaster from source_shape to target_shape.""" if source_shape.dtype != target_shape.dtype: raise ValueError("The source and target row_split dtypes should be equal") if (source_shape.rank is None or target_shape.rank is None): raise ValueError("Rank of source and target must be statically known") elif source_shape.rank > target_shape.rank: raise ValueError("Cannot broadcast to a shape with smaller rank") elif source_shape.rank == 0: return _Broadcaster(source_shape, target_shape, []) elif target_shape.rank == 1: assert source_shape.rank == 1 layer = _LayerBroadcaster.first_layer(source_shape.inner_shape[0], target_shape.inner_shape[0]) return _Broadcaster(source_shape, target_shape, [layer]) assert source_shape.rank <= target_shape.rank assert target_shape.rank >= 2 assert source_shape.rank >= 1 source_rps = source_shape._as_row_partitions() # pylint: disable=protected-access target_rps = target_shape._as_row_partitions() # pylint: disable=protected-access assert len(target_rps) >= 1 assert len(source_rps) <= len(target_rps) source_nrows = source_shape[0] if len(source_rps) < len(target_rps): # Note: this includes the case where len(source_rps)==0. # Here we begin at -1, one dimension before source_rps[0]. # neg_one_source_rp | neg_one_target_rp=target_rps[-(len(source_rps)+1)] # source_rps[0] | target_rps[-len(source_rps)] # source_rps[1] | target_rps[1-len(source_rps)] # ... | ... # source_rps[-1] | target_rps[-1] neg_one_source_rp = RowPartition.from_uniform_row_length( uniform_row_length=source_nrows, nrows=1, nvals=source_nrows) neg_one_target_rp = target_rps[-(len(source_rps) + 1)] neg_one_broadcaster = _LayerBroadcaster.get_singleton_broadcaster( neg_one_target_rp.nrows()) zeroth_broadcaster = neg_one_broadcaster.next_layer(neg_one_source_rp, neg_one_target_rp) target_rps_tail = target_rps[-len(source_rps):] if len( source_rps) >= 1 else [] layers = _get_layer_broadcasters_from_rps(zeroth_broadcaster, source_rps, target_rps_tail) return _Broadcaster(source_shape, target_shape, layers) else: assert len(target_rps) == len(source_rps) zeroth_broadcaster = _LayerBroadcaster.first_layer(source_rps[0].nrows(), target_rps[0].nrows()) layers = _get_layer_broadcasters_from_rps(zeroth_broadcaster, source_rps, target_rps) return _Broadcaster(source_shape, target_shape, layers) def _get_identity_broadcaster(shape): """Gets a Broadcaster for two identical shapes.""" if shape.rank is None: raise ValueError("Shape must have a defined rank") layers = [ _LayerBroadcaster.get_identity_broadcaster( shape._num_slices_in_dimension(i)) for i in range(shape.rank) # pylint: disable=protected-access ] return _Broadcaster(shape, shape, layers) def _broadcast_dynamic_shape_one_layer(a, b): """Broadcast two vectors, given their shapes. Args: a: the number of rows in a. b: the number of rows in b. Returns: (layer_a, layer_b, target_shape) layer_a is a _LayerBroadcaster from a to the target_shape. layer_b is a _LayerBroadcaster from b to the target_shape. target_shape is the target_shape Raises: InvalidArgumentError if the shapes are not consistent. """ a_0 = a[0] b_0 = b[0] def broadcast_from_a(): # Assumes a_0 == 1 a_layer = array_ops.zeros(b_0, dtype=b_0.dtype) b_layer = math_ops.range(b_0) target = b return [a_layer, b_layer, target] a_static = tensor_util.constant_value(a) if a_static is not None and a_static[0] == 1: [a_gi, b_gi, target] = broadcast_from_a() a_layer = _LayerBroadcaster.from_gather_index(a_gi) b_layer = _LayerBroadcaster.from_gather_index(b_gi) return [a_layer, b_layer, target] def broadcast_from_b(): # Assumes b_0 == 1 a_layer = math_ops.range(a_0) b_layer = array_ops.zeros(a_0, dtype=a_0.dtype) target = a return [a_layer, b_layer, target] b_static = tensor_util.constant_value(b) if b_static is not None and b_static[0] == 1: [a_gi, b_gi, target] = broadcast_from_b() a_layer = _LayerBroadcaster.from_gather_index(a_gi) b_layer = _LayerBroadcaster.from_gather_index(b_gi) return [a_layer, b_layer, target] def broadcast_noop(): # Assumes a_0 == 1 a_layer = math_ops.range(a_0) b_layer = math_ops.range(b_0) target = b return [a_layer, b_layer, target] can_broadcast_from_a = math_ops.equal(a_0, 1) can_broadcast_from_b = math_ops.equal(b_0, 1) def broadcast_not_from_a(): return cond.cond( can_broadcast_from_b, true_fn=broadcast_from_b, false_fn=broadcast_noop) nrows_equal = math_ops.equal(a_0, b_0) can_broadcast = math_ops.logical_or( can_broadcast_from_a, math_ops.logical_or(can_broadcast_from_b, nrows_equal)) check_can_broadcast = check_ops.assert_equal( can_broadcast, True, message="Cannot broadcast") results = cond.cond( can_broadcast_from_a, true_fn=broadcast_from_a, false_fn=broadcast_not_from_a) results = [ control_flow_ops.with_dependencies([check_can_broadcast], x) for x in results ] [a_gi, b_gi, target] = results a_layer = _LayerBroadcaster.from_gather_index(a_gi) b_layer = _LayerBroadcaster.from_gather_index(b_gi) return [a_layer, b_layer, target] def _broadcast_dynamic_shape_first_layer(a_0, b_0): """Broadcast the first layer of two dynamic shapes given the dimensions. Args: a_0: the number of rows in a. b_0: the number of rows in b. Returns: (use_a, layer_a, layer_b) where use_a is true if the target provably equals a, false otherwise. layer_a is a _LayerBroadcaster from a to the target. layer_b is a _LayerBroadcaster from b to the target. """ def broadcast_from_a(): # Assumes a_0 == 1 a_layer = array_ops.zeros(b_0, dtype=b_0.dtype) b_layer = math_ops.range(b_0) return [a_layer, b_layer] static_a_0 = tensor_util.constant_value(a_0) static_b_0 = tensor_util.constant_value(b_0) if static_a_0 is not None: if static_a_0 == static_b_0: id_broadcaster = _LayerBroadcaster.get_identity_broadcaster( static_a_0, dtype=a_0.dtype) return [id_broadcaster, id_broadcaster] elif static_a_0 == 1: return [ _LayerBroadcaster.get_singleton_broadcaster(b_0), _LayerBroadcaster.get_identity_broadcaster(b_0) ] if static_b_0 == 1: return [ _LayerBroadcaster.get_identity_broadcaster(a_0), _LayerBroadcaster.get_singleton_broadcaster(a_0) ] def broadcast_from_b(): # Assumes b_0 == 1 a_layer = math_ops.range(a_0) b_layer = array_ops.zeros(a_0, dtype=a_0.dtype) return [a_layer, b_layer] def broadcast_noop(): # Assumes a_0 == b_0 a_layer = math_ops.range(a_0) b_layer = math_ops.range(b_0) return [a_layer, b_layer] can_broadcast_from_a = math_ops.equal(a_0, constant_op.constant(1, a_0.dtype)) can_broadcast_from_b = math_ops.equal(b_0, constant_op.constant(1, b_0.dtype)) def broadcast_not_from_a(): return cond.cond( can_broadcast_from_b, true_fn=broadcast_from_b, false_fn=broadcast_noop) # Ideally, this would only block control flow on broadcast_noop, but # the control flow doesn't seem to work. can_broadcast = math_ops.logical_or( math_ops.logical_or(can_broadcast_from_a, can_broadcast_from_b), math_ops.equal(a_0, b_0)) result = cond.cond( can_broadcast_from_a, true_fn=broadcast_from_a, false_fn=broadcast_not_from_a) return [ _LayerBroadcaster.from_gather_index( control_flow_ops.with_dependencies( [check_ops.assert_equal(can_broadcast, True)], x)) for x in result ] def _broadcast_half( ac_0: _LayerBroadcaster, a_1: RowPartition) -> Tuple[_LayerBroadcaster, RowPartition]: """Does a NOOP broadcast of a_1. *-ac_0-->* | | a_1 c_1 | | V V *-ac_1-->* Note that by definition this cannot fail: there is always a well-defined NOOP broadcast. This is usually intended as half of broadcasting two shapes together. Args: ac_0: previous LayerBroadcaster a_1: previous RowPartition Returns: [ac_1, c_1] where ac_1 is the next LayerBroadcaster, and c_1 is the broadcast RowPartition """ c_1 = ac_0.broadcast_row_partition(a_1) old_value_rowids = array_ops.gather(ac_0.gather_index, c_1.value_rowids()) old_row_starts = array_ops.gather(a_1.row_splits(), old_value_rowids) gather_index = old_row_starts + c_1.offsets_in_rows() return [_LayerBroadcaster.from_gather_index(gather_index), c_1] def _broadcast_dynamic_shape_next_layer_half_ragged( ac_0: _LayerBroadcaster, bc_0: _LayerBroadcaster, a_1: RowPartition, b_1: RowPartition ) -> Tuple[RowPartition, _LayerBroadcaster, _LayerBroadcaster]: r"""Broadcast target and next layer broadcaster of two dynamic shapes. a_1 is uniform, and b_1 is ragged. *--ac_0-->*<--bc_0--* | | | a_1 c_1 b_1 | | | V V V *--ac_1-->*<--bc_1--* Args: ac_0: _LayerBroadcaster from a to c in the previous layer. bc_0: _LayerBroadcaster from b to c in the previous layer. a_1: a uniform RowPartition for the next layer of a. b_1: a ragged RowPartition for the next layer of b. Returns: (c_1, ac_1, bc_1) c_1: a RowPartition for the next layer of the dynamic shape. ac_1: _LayerBroadcaster from a to c in the next layer. bc_1: _LayerBroadcaster from b to c in the next layer. """ if not isinstance(ac_0, _LayerBroadcaster): raise TypeError("ac_0 should be a _LayerBroadcaster") if not isinstance(bc_0, _LayerBroadcaster): raise TypeError("bc_0 should be a _LayerBroadcaster") if not isinstance(a_1, RowPartition): raise TypeError("a_1 should be a RowPartition") if not isinstance(b_1, RowPartition): raise TypeError("b_1 should be a RowPartition") assert a_1.is_uniform() assert not b_1.is_uniform() static_a_1 = tensor_util.constant_value(a_1.uniform_row_length()) if static_a_1 == 1: [bc_1, c_1b] = _broadcast_half(bc_0, b_1) ac_1_gather_index = array_ops.gather(ac_0.gather_index, c_1b.value_rowids()) c_1 = RowPartition.from_row_splits(c_1b.row_splits()) ac_1 = _LayerBroadcaster.from_gather_index(ac_1_gather_index) bc_1 = _LayerBroadcaster.from_gather_index(bc_1.gather_index) return [c_1, ac_1, bc_1] def broadcast_noop(): # The sides must be "equal". [ac_1, c_1a] = _broadcast_half(ac_0, a_1) [bc_1, c_1b] = _broadcast_half(bc_0, b_1) checks = [check_ops.assert_equal(c_1a.row_splits(), c_1b.row_splits())] return [ control_flow_ops.with_dependencies(checks, x) for x in [a_1.row_splits(), ac_1.gather_index, bc_1.gather_index] ] def broadcast_a(): [bc_1, c_1b] = _broadcast_half(bc_0, b_1) ac_1_gather_index = array_ops.gather(ac_0.gather_index, c_1b.value_rowids()) return [ c_1b.row_splits(), ac_1_gather_index, bc_1.gather_index, ] can_broadcast_a = math_ops.equal(a_1.uniform_row_length(), 1) [c_1_row_splits, ac_1_gather_index, bc_1_gather_index] = cond.cond( can_broadcast_a, true_fn=broadcast_a, false_fn=broadcast_noop) c_1 = RowPartition.from_row_splits(c_1_row_splits) ac_1 = _LayerBroadcaster.from_gather_index(ac_1_gather_index) bc_1 = _LayerBroadcaster.from_gather_index(bc_1_gather_index) return [c_1, ac_1, bc_1] def _broadcast_dynamic_shape_next_layer_both_uniform( ac_0: _LayerBroadcaster, bc_0: _LayerBroadcaster, a_1: RowPartition, b_1: RowPartition ) -> Tuple[RowPartition, _LayerBroadcaster, _LayerBroadcaster]: r"""Broadcast target and next layer broadcaster of two uniform dynamic shapes. *--ac_0-->*<--bc_0--* | | | a_1 c_1 b_1 | | | V V V *--ac_1-->*<--bc_1--* Args: ac_0: _LayerBroadcaster from a to c in the previous layer. bc_0: _LayerBroadcaster from b to c in the previous layer. a_1: a RowPartition for the next layer of a. b_1: a RowPartition for the next layer of b. Returns: (c_1, ac_1, bc_1) c_1: a RowPartition for the next layer of the dynamic shape. ac_1: _LayerBroadcaster from a to c in the next layer. bc_1: _LayerBroadcaster from b to c in the next layer. """ if not isinstance(ac_0, _LayerBroadcaster): raise TypeError("ac_0 should be a _LayerBroadcaster") if not isinstance(bc_0, _LayerBroadcaster): raise TypeError("bc_0 should be a _LayerBroadcaster") if not isinstance(a_1, RowPartition): raise TypeError("a_1 should be a RowPartition") if not isinstance(b_1, RowPartition): raise TypeError("b_1 should be a RowPartition") assert a_1.is_uniform() assert b_1.is_uniform() static_a_1 = tensor_util.constant_value(a_1.uniform_row_length()) static_b_1 = tensor_util.constant_value(b_1.uniform_row_length()) if static_a_1 is not None: if static_a_1 == static_b_1: # Here, this dimension is the same, but we may have to broadcast previous # dimensions. [ac_1, _] = _broadcast_half(ac_0, a_1) [bc_1, _] = _broadcast_half(bc_0, b_1) c_1 = RowPartition.from_uniform_row_length( static_a_1, nrows=ac_0.dest_nrows()) return [c_1, ac_1, bc_1] elif static_a_1 == 1: [bc_1, c_1b] = _broadcast_half(bc_0, b_1) ac_1 = _LayerBroadcaster.from_gather_index( array_ops.gather(ac_0.gather_index, c_1b.value_rowids())) c_1 = RowPartition.from_uniform_row_length( b_1.uniform_row_length(), nrows=bc_0.dest_nrows()) return [c_1, ac_1, bc_1] if static_b_1 == 1: [ac_1, c_1a] = _broadcast_half(ac_0, a_1) bc_1 = _LayerBroadcaster.from_gather_index( array_ops.gather(bc_0.gather_index, c_1a.value_rowids())) c_1 = RowPartition.from_uniform_row_length( a_1.uniform_row_length(), nrows=ac_0.dest_nrows()) return [c_1, ac_1, bc_1] def broadcast_noop(): # Assumes a_1.uniform_row_length() == b_1.uniform_row_length() # Both sides broadcast to a single shape. [ac_1, _] = _broadcast_half(ac_0, a_1) [bc_1, _] = _broadcast_half(bc_0, b_1) return [a_1.uniform_row_length(), ac_1.gather_index, bc_1.gather_index] def broadcast_a(): [bc_1, c_1b] = _broadcast_half(bc_0, b_1) ac_1_gather_index = array_ops.gather(ac_0.gather_index, c_1b.value_rowids()) return [ b_1.uniform_row_length(), ac_1_gather_index, bc_1.gather_index, ] def broadcast_b(): [ac_1, c_1a] = _broadcast_half(ac_0, a_1) bc_1_gather_index = array_ops.gather(bc_0.gather_index, c_1a.value_rowids()) return [a_1.uniform_row_length(), ac_1.gather_index, bc_1_gather_index] can_broadcast_b = math_ops.equal(b_1.uniform_row_length(), 1) def no_broadcast_a(): return cond.cond( can_broadcast_b, true_fn=broadcast_b, false_fn=broadcast_noop) can_broadcast_a = math_ops.equal(a_1.uniform_row_length(), 1) broadcast_asserts = [ check_ops.assert_equal( math_ops.logical_or( math_ops.logical_or(can_broadcast_a, can_broadcast_b), math_ops.equal(a_1.uniform_row_length(), b_1.uniform_row_length())), True) ] result = cond.cond( can_broadcast_a, true_fn=broadcast_a, false_fn=no_broadcast_a) [c_1_uniform_row_length, ac_1_gather_index, bc_1_gather_index] = [ control_flow_ops.with_dependencies(broadcast_asserts, x) for x in result ] c_1 = RowPartition.from_uniform_row_length( c_1_uniform_row_length, nvals=c_1_uniform_row_length * ac_0.dest_nrows(), nrows=ac_0.dest_nrows()) ac_1 = _LayerBroadcaster.from_gather_index(ac_1_gather_index) bc_1 = _LayerBroadcaster.from_gather_index(bc_1_gather_index) return [c_1, ac_1, bc_1] def _broadcast_dynamic_shape_next_layer( ac_0: _LayerBroadcaster, bc_0: _LayerBroadcaster, a_1: RowPartition, b_1: RowPartition ) -> Tuple[RowPartition, _LayerBroadcaster, _LayerBroadcaster]: r"""Broadcast target and next layer broadcaster of two dynamic shapes. *--ac_0-->*<--bc_0--* | | | a_1 c_1 b_1 | | | V V V *--ac_1-->*<--bc_1--* Args: ac_0: _LayerBroadcaster from a to c in the previous layer. bc_0: _LayerBroadcaster from b to c in the previous layer. a_1: a RowPartition for the next layer of a. b_1: a RowPartition for the next layer of b. Returns: (c_1, ac_1, bc_1) c_1: a RowPartition for the next layer of the dynamic shape. ac_1: _LayerBroadcaster from a to c in the next layer. bc_1: _LayerBroadcaster from b to c in the next layer. """ if not isinstance(ac_0, _LayerBroadcaster): raise TypeError("ac_0 should be a _LayerBroadcaster") if not isinstance(bc_0, _LayerBroadcaster): raise TypeError("bc_0 should be a _LayerBroadcaster") if not isinstance(a_1, RowPartition): raise TypeError("a_1 should be a RowPartition") if not isinstance(b_1, RowPartition): raise TypeError("b_1 should be a RowPartition") if a_1.is_uniform(): if b_1.is_uniform(): return _broadcast_dynamic_shape_next_layer_both_uniform( ac_0, bc_0, a_1, b_1) else: return _broadcast_dynamic_shape_next_layer_half_ragged( ac_0, bc_0, a_1, b_1) else: if b_1.is_uniform(): [c_1, bc_1, ac_1] = _broadcast_dynamic_shape_next_layer_half_ragged( # pylint: disable=arguments-out-of-order bc_0, ac_0, b_1, a_1) return (c_1, ac_1, bc_1) else: # If neither shape is uniform, we cannot broadcast the dimension. [ac_1, c_1a] = _broadcast_half(ac_0, a_1) [bc_1, c_1b] = _broadcast_half(bc_0, b_1) check_valid = [ check_ops.assert_equal(c_1a.row_splits(), c_1b.row_splits()) ] return ( c_1a._with_dependencies(check_valid), # pylint: disable=protected-access ac_1.with_dependencies(check_valid), bc_1.with_dependencies(check_valid)) def _broadcast_dynamic_shape_from_rps( a_zero: _LayerBroadcaster, b_zero: _LayerBroadcaster, a_rps: Sequence[RowPartition], b_rps: Sequence[RowPartition] ) -> Tuple[Sequence[RowPartition], Sequence[_LayerBroadcaster], Sequence[_LayerBroadcaster]]: """Create BroadcastLayers from two shapes to a target shape. *--a_zero->*<-b_zero-* | | | a_rps[0] c_rps[0] b_rps[0] | | | V V V *--ac[1]-->*<-bc[1]--* | | | a_rps[1] c_rps[0] b_rps[1] | | | V V V *--ac[2]-->*<-bc[2]--* Note: ac[0]=a_zero, and bc[0]=b_zero. Args: a_zero: broadcaster from rows of a_rps[0] to target shape. b_zero: broadcaster from rows of b_rps[0] to target shape. a_rps: RowPartitions of first shape. b_rps: RowPartitions of second shape, equal in length to a_rps. Returns: (c_rps, ac, bc) where: c_rps: RowPartitions of target shape. ac: layers broadcasting from the first shape. bc: layers broadcasting from the second shape. """ assert len(a_rps) == len(b_rps) if a_rps: (c_1, ac_1, bc_1) = _broadcast_dynamic_shape_next_layer(a_zero, b_zero, a_rps[0], b_rps[0]) (c_suffix, a_layers, b_layers) = _broadcast_dynamic_shape_from_rps(ac_1, bc_1, a_rps[1:], b_rps[1:]) return ([c_1] + c_suffix, [ac_1] + a_layers, [bc_1] + b_layers) else: return ([], [], []) def _get_broadcast_num_row_partitions(a: DynamicRaggedShape, b: DynamicRaggedShape): """Returns broadcast_dynamic_shape(a, b).num_row_partitions.""" # Assumes rank and num_row_partitions are not None. if (a.num_row_partitions == 0 and b.num_row_partitions == 0): return 0 expanded_num_row_partitions_a = a.num_row_partitions + max(0, b.rank - a.rank) expanded_num_row_partitions_b = b.num_row_partitions + max(0, a.rank - b.rank) if a.num_row_partitions == 0: return expanded_num_row_partitions_b if b.num_row_partitions == 0: return expanded_num_row_partitions_a return max(expanded_num_row_partitions_a, expanded_num_row_partitions_b) # pylint: disable=protected-access def _broadcast_dynamic_shape_extended_complete( a: DynamicRaggedShape, b: DynamicRaggedShape, b_rps: Sequence[RowPartition], c_suffix: Sequence[RowPartition], ac: Sequence[_LayerBroadcaster], bc_suffix: Sequence[_LayerBroadcaster] ) -> Tuple[DynamicRaggedShape, _Broadcaster, _Broadcaster]: """Helper for broadcast_dynamic_shape_extended.""" c_prefix = b_rps[:-len(c_suffix)] bc_prefix_length = b.rank - len(bc_suffix) bc_prefix = [ _LayerBroadcaster.get_identity_broadcaster(b._num_slices_in_dimension(i)) for i in range(bc_prefix_length) ] c_num_row_partitions = _get_broadcast_num_row_partitions(a, b) c_raw = DynamicRaggedShape.from_row_partitions(c_prefix + tuple(c_suffix)) c = c_raw._with_num_row_partitions(c_num_row_partitions) return (c, _Broadcaster(a, c, ac), _Broadcaster(b, c, bc_prefix + bc_suffix)) def _broadcast_dynamic_shape_extended_helper( a: DynamicRaggedShape, b: DynamicRaggedShape ) -> Tuple[DynamicRaggedShape, _Broadcaster, _Broadcaster]: """Helper for broadcast_dynamic_shape_extended. Here, we force: a.rank <= b.rank 2 <= b.rank 1 <= a.rank Args: a: a DynamicRaggedShape b: a DynamicRaggedShape Returns: A triple of a shape and two broadcasters. """ assert a.rank <= b.rank assert 2 <= b.rank assert 1 <= a.rank a_rps = a._as_row_partitions() # pylint: disable=protected-access b_rps = b._as_row_partitions() # pylint: disable=protected-access if len(a_rps) < len(b_rps): # Note: this includes the case where len(a_rps)==0. # Here we begin at -1, one dimension before a_rps[0]. # neg_one_a_rp | b_rps[-(len(a_rps)+1)] # a_rps[0] | b_rps[-len(a_rps)] # a_rps[1] | b_rps[1-len(a_rps)] # ... | ... # a_rps[-1] | b_rps[-1] a_nrows = a[0] a_nrows_static = tensor_util.constant_value(a_nrows) if a_nrows_static is not None: a_nrows = a_nrows_static neg_one_a_rp = RowPartition.from_uniform_row_length( uniform_row_length=a_nrows, nrows=1, nvals=a_nrows) neg_one_b_rp = b_rps[-(len(a_rps) + 1)] (neg_one_ac, neg_one_bc) = _broadcast_dynamic_shape_first_layer( constant_op.constant(1, dtype=b_rps[0].dtype), neg_one_b_rp.nrows()) # The first part of the solution. (c_zero, ac_zero, bc_zero) = _broadcast_dynamic_shape_next_layer(neg_one_ac, neg_one_bc, neg_one_a_rp, neg_one_b_rp) b_rps_tail = b_rps[-len(a_rps):] if len(a_rps) >= 1 else [] (c_suffix, ac_layers, bc_layers) = _broadcast_dynamic_shape_from_rps(ac_zero, bc_zero, a_rps, b_rps_tail) return _broadcast_dynamic_shape_extended_complete( a=a, b=b, b_rps=b_rps, c_suffix=[c_zero] + c_suffix, ac=[ac_zero] + ac_layers, bc_suffix=[neg_one_bc, bc_zero] + bc_layers) else: assert len(a_rps) == len(b_rps) (ac_zero, bc_zero) = _broadcast_dynamic_shape_first_layer(a_rps[0].nrows(), b_rps[0].nrows()) (c_rps, a_layers, b_layers) = _broadcast_dynamic_shape_from_rps(ac_zero, bc_zero, a_rps, b_rps) return _broadcast_dynamic_shape_extended_complete( a=a, b=b, b_rps=b_rps, c_suffix=c_rps, ac=[ac_zero] + a_layers, bc_suffix=[bc_zero] + b_layers) def _fix_start_index(index, rank, num_row_partitions): """Slice indexes are always silently truncated.""" if index < 0: if rank is None: raise ValueError( "Rank must be known to use __getitem__ on a negative index.") index = rank + index if index < 0: index = 0 if (num_row_partitions > 0 and index <= num_row_partitions + 1): # The rank is always >= num_row_partitions + 1 if num_row_partitions > 0. return index if index == 0: return index if rank is None: raise ValueError("Rank must be known to use __getitem__ on a large index.") if index >= rank: index = rank return index def _fix_stop_index(index, rank): """Slice indexes are always silently truncated.""" if index is None: if rank is None: raise ValueError("Rank must be known to use __getitem__ without a stop.") index = rank if index < 0: if rank is None: raise ValueError( "Rank must be known to use __getitem__ on a negative index.") index = rank + index if index < 0: index = 0 if rank is not None: index = min(rank, index) return index def _first_layer_gather_index(nrows_source, nrows_target): """Return the first layer gather_index. Args: nrows_source: the number of rows in the source. nrows_target: the number of rows in the target. Returns: A tensor, usable as a gather_index for a _LayerBroadcaster. """ def gi_broadcast_first(): return array_ops.zeros(nrows_target, dtype=nrows_target.dtype) def gi_no_broadcast_first(): gather_index = math_ops.range(nrows_target, dtype=nrows_target.dtype) return gather_index do_broadcast = math_ops.equal(nrows_source, constant_op.constant(1, nrows_source.dtype)) nrows_equal = math_ops.equal(nrows_source, nrows_target) can_broadcast = check_ops.assert_equal( math_ops.logical_or(do_broadcast, nrows_equal), True, message="Cannot broadcast") gather_index = cond.cond( do_broadcast, true_fn=gi_broadcast_first, false_fn=gi_no_broadcast_first) return control_flow_ops.with_dependencies([can_broadcast], gather_index) def _next_layer_gather_index(bc, original_rp, broadcast_rp): r"""Create the next layer gather_index whether or not a broadcast happens. *----------bc-------->* | | original_rp broadcast_rp | | \|/ \|/ *--next_broadcaster-->* Args: bc: the old broadcaster. original_rp: the original row partition. broadcast_rp: the target row partition. Returns: the gather_index for next_broadcaster. Raises: InvalidArgumentError if the shapes are incompatible. """ old_value_rowids = array_ops.gather(bc.gather_index, broadcast_rp.value_rowids()) def gi_no_broadcast(): # TODO(martinz): decide if row_splits or row_starts should be used here. old_row_starts = array_ops.gather(original_rp.row_splits(), old_value_rowids) expected_row_lengths = array_ops.gather( params=original_rp.row_lengths(), indices=bc.gather_index) actual_row_lengths = broadcast_rp.row_lengths() check_valid = check_ops.assert_equal( expected_row_lengths, actual_row_lengths, message="Cannot broadcast") gather_index = old_row_starts + broadcast_rp.offsets_in_rows() return control_flow_ops.with_dependencies([check_valid], gather_index) def gi_broadcast(): # Several optimizations can occur here. # old_row_starts == old_value_rowids, because: # if you are broadcasting, then the source has uniform row length of 1, # implying original_rp.row_splits == tf.range(original_rp.nvals + 1) # When broadcasting, there is no need to add offsets to the # source, because the source has size 1. # Also, this is always valid, because we enforce source and destination # have uniform_row_length. return old_value_rowids if not original_rp.is_uniform(): return gi_no_broadcast() do_broadcast = math_ops.equal(original_rp.uniform_row_length(), constant_op.constant(1, original_rp.dtype)) gather_index = cond.cond( do_broadcast, true_fn=gi_broadcast, false_fn=gi_no_broadcast) return gather_index def _flat_values_shape(rt): if isinstance(rt, ragged_tensor.RaggedTensor): return array_ops.shape(rt.flat_values) return rt.flat_values.shape def _to_row_partitions_and_nvals_from_lengths( lengths: Sequence[Union[int, Sequence[int]]], dtype=None) -> Tuple[Sequence[RowPartition], int]: """Allow ragged and uniform shapes to be specified. For example, [2, [2,1], 2] represents a shape like: [[[0, 0], [0, 0]], [[0, 0]]] Args: lengths: a list of integers and lists of integers. dtype: dtype of the shape (tf.int32 or tf.int64) Returns: a sequence of RowPartitions, and the number of values of the last partition. """ size_so_far = lengths[0] result = [] for current_lengths in lengths[1:]: if isinstance(current_lengths, int): nrows = size_so_far nvals = current_lengths * nrows size_so_far = nvals result.append( RowPartition.from_uniform_row_length( current_lengths, nvals, nrows=nrows, dtype_hint=dtype)) else: if size_so_far != len(current_lengths): raise ValueError("Shape not consistent.") result.append( RowPartition.from_row_lengths(current_lengths, dtype_hint=dtype)) size_so_far = sum(current_lengths) return (result, size_so_far) def _element_to_string(x): """element to a string within a list.""" if x is Ellipsis: return "..." if isinstance(x, str): return "'" + x + "'" return str(x) def _list_tail_with_ellipsis(arr): """Print the tail of a list where the list might have an ellipsis.""" if not arr: return "]" else: return ", " + _element_to_string(arr[0]) + _list_tail_with_ellipsis(arr[1:]) def _list_with_ellipsis_to_str(arr): """Print a list that might have ellipsis.""" if not arr: return "[]" return "[" + _element_to_string(arr[0]) + _list_tail_with_ellipsis(arr[1:]) def _is_int_or_tuple_of_ints(x): if isinstance(x, int): return True if not isinstance(x, tuple): return False for y in x: if not isinstance(y, int): return False return True def _alt_inner_shape_from_tensor_shape(shape, dtype, new_inner_rank): """Helper for _alt_inner_shape, used directly in _with_num_row_partitions.""" if new_inner_rank == 1: return constant_op.constant([shape.num_elements()], dtype=dtype) new_inner_rank_tail_length = new_inner_rank - 1 inner_shape_tail = shape[-new_inner_rank_tail_length:].as_list() first_dim = shape[:-new_inner_rank_tail_length].num_elements() return constant_op.constant([first_dim] + inner_shape_tail, dtype=dtype) def _safe_floor_div(dividend: tensor_shape.Dimension, divisor: tensor_shape.Dimension) -> tensor_shape.Dimension: if tensor_shape.dimension_value(divisor) == 0: return None return dividend // divisor # TODO(b/218932570) def _reduce_prod_patch(x): if x.dtype == dtypes.int64: return math_ops.cast( math_ops.reduce_prod(math_ops.cast(x, dtypes.int32)), dtypes.int64) return math_ops.reduce_prod(x) # Type alias for shape encoded as a DynamicRaggedShape or a Tensor. DenseOrRaggedShape = Union[DynamicRaggedShape, core.TensorLike] def _merge_row_partitions( row_partitions: Sequence[RowPartition]) -> RowPartition: # TODO(martinz): handle uniform splits. # TODO(martinz): consider using value_row_ids if present. # Note: this probably won't be called with len(row_partitions)==1, so no # need to optimize. row_splits = row_partitions[0].row_splits() for rp in row_partitions[1:]: row_splits = array_ops.gather(rp.row_splits(), row_splits) return RowPartition.from_row_splits(row_splits) def _merge_inner_shape( inner_shape: tensor_lib.Tensor, static_inner_shape: tensor_shape.TensorShape, outer_axis: int, inner_axis: int) -> Tuple[tensor_lib.Tensor, tensor_shape.TensorShape]: """Merge the inner shape of a DynamicRaggedShape.""" prefix = inner_shape[:outer_axis] suffix = inner_shape[inner_axis + 1:] internal = inner_shape[outer_axis:inner_axis + 1] internal_value = [_reduce_prod_patch(internal)] new_internal = array_ops.concat([prefix, internal_value, suffix], axis=0) prefix_static = static_inner_shape[:outer_axis] suffix_static = static_inner_shape[inner_axis + 1:] internal_static = static_inner_shape[outer_axis:inner_axis + 1] internal_value_static = tensor_shape.TensorShape( [internal_static.num_elements()]) new_internal_static = prefix_static + internal_value_static + suffix_static return (new_internal, new_internal_static) def _batch_rp_spec(rp_spec: RowPartitionSpec, batch_size: Optional[int]) -> RowPartitionSpec: """Batches a RowPartitionSpec. Given a RowPartitionSpec and a batch_size, create a RowPartitionSpec that will be the spec for the concatenation of batch_size RowPartitions. A RowPartition can be considered a transformation from a list of a given length to a list of lists. Assume rp_a is a map from list_a to nlist_a, And rp_b is a map from list_b to nlist_b. concat(rp_a, rp_b) is a transform of concat(list_a, list_b) to concat(nlist_a, nlist_b). If batch_size is None, then have the spec be able to handle an arbitrary number of RowPartitions. Args: rp_spec: a RowPartitionSpec for all the RowPartitions to be concatenated. batch_size: the number of rp_specs to be concatenated. Returns: a batched RowPartitionSpec. """ if batch_size is None: return RowPartitionSpec( uniform_row_length=rp_spec.uniform_row_length, dtype=rp_spec.dtype) nrows = None if rp_spec.nrows is None else rp_spec.nrows * batch_size nvals = None if rp_spec.nvals is None else rp_spec.nvals * batch_size return RowPartitionSpec( nrows=nrows, nvals=nvals, uniform_row_length=rp_spec.uniform_row_length, dtype=rp_spec.dtype) def _batch_rp_spec_head(old_head: RowPartitionSpec, batch_size: Optional[int]) -> RowPartitionSpec: """Creates a RowPartitionSpec representing the new dimension created.""" nvals = None if (old_head.nrows is None or batch_size is None) else batch_size * old_head.nrows return RowPartitionSpec( nrows=batch_size, nvals=nvals, uniform_row_length=old_head.nrows, dtype=old_head.dtype) def _batch_static_inner_shape( old_shape: tensor_shape.TensorShape, batch_size: Optional[int]) -> tensor_shape.TensorShape: """Returns a copy of old_shape with axis=0 multiplied by batch_size. Only use if this is the inner_shape of a DynamicRaggedShape.Spec with one or more row partitions. Args: old_shape: the original inner_shape. batch_size: the batch size. Returns: a new shape. """ head_dim = tensor_shape.dimension_at_index(old_shape, 0) * batch_size return head_dim + old_shape[1:] def _batch_tensor_shape(old_shape: tensor_shape.TensorShape, batch_size: int) -> tensor_shape.TensorShape: return tensor_shape.TensorShape([batch_size]) + old_shape def _unbatch_static_inner_shape( old_shape: tensor_shape.TensorShape, batch_size: Optional[int]) -> tensor_shape.TensorShape: """Unbatch a static_inner_shape when num_row_partitions > 0.""" head_dim = tensor_shape.dimension_at_index(old_shape, 0) // batch_size return head_dim + old_shape[1:] # Copied from ragged_array_ops.py def ones(shape: DynamicRaggedShape, dtype=dtypes.float32, name: Optional[str] = None) -> ragged_tensor.RaggedOrDense: """Returns ones shaped like x.""" flat_values = array_ops.ones(shape.inner_shape, dtype=dtype, name=name) return ragged_tensor.RaggedTensor._from_nested_row_partitions( # pylint: disable=protected-access flat_values, shape.row_partitions)
_Broadcaster
python
pytorch__pytorch
torch/distributed/tensor/_redistribute.py
{ "start": 886, "end": 2251 }
class ____(NamedTuple): mesh_dim: int src_dst_placements: tuple[Placement, Placement] # logical_shape on this mesh dimension logical_shape: list[int] # Global cache for DTensorRedistributePlanner instances _planner_cache: dict[ tuple[weakref.ReferenceType, int], "DTensorRedistributePlanner" ] = {} def get_redistribute_planner( device_mesh: DeviceMesh, tensor_dimension: int ) -> "DTensorRedistributePlanner": """ Factory function to get or create a DTensorRedistributePlanner instance. This function provides transparent caching of planner instances based on device_mesh and tensor_dimension. Multiple calls with the same parameters will return the same cached instance for better performance. Args: device_mesh: The device mesh for the planner tensor_dimension: Number of tensor dimensions Returns: A DTensorRedistributePlanner instance (potentially cached) """ cache_key = (weakref.ref(device_mesh), tensor_dimension) if cache_key not in _planner_cache: planner = DTensorRedistributePlanner(device_mesh, tensor_dimension) _planner_cache[cache_key] = planner return _planner_cache[cache_key] def clear_redistribute_planner_cache() -> None: """Clear the cache of DTensorRedistributePlanner instances.""" _planner_cache.clear()
_TransformInfo