{"instance_id": "django__django-16938", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py\nindex 36048601af..e69de29bb2 100644\n--- a/django/core/serializers/python.py\n+++ b/django/core/serializers/python.py\n@@ -1,190 +0,0 @@\n-\"\"\"\n-A Python \"serializer\". Doesn't do much serializing per se -- just converts to\n-and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for\n-other serializers.\n-\"\"\"\n-\n-from django.apps import apps\n-from django.core.serializers import base\n-from django.db import DEFAULT_DB_ALIAS, models\n-from django.utils.encoding import is_protected_type\n-\n-\n-class Serializer(base.Serializer):\n-    \"\"\"\n-    Serialize a QuerySet to basic Python objects.\n-    \"\"\"\n-\n-    internal_use_only = True\n-\n-    def start_serialization(self):\n-        self._current = None\n-        self.objects = []\n-\n-    def end_serialization(self):\n-        pass\n-\n-    def start_object(self, obj):\n-        self._current = {}\n-\n-    def end_object(self, obj):\n-        self.objects.append(self.get_dump_object(obj))\n-        self._current = None\n-\n-    def get_dump_object(self, obj):\n-        data = {\"model\": str(obj._meta)}\n-        if not self.use_natural_primary_keys or not hasattr(obj, \"natural_key\"):\n-            data[\"pk\"] = self._value_from_field(obj, obj._meta.pk)\n-        data[\"fields\"] = self._current\n-        return data\n-\n-    def _value_from_field(self, obj, field):\n-        value = field.value_from_object(obj)\n-        # Protected types (i.e., primitives like None, numbers, dates,\n-        # and Decimals) are passed through as is. All other values are\n-        # converted to string first.\n-        return value if is_protected_type(value) else field.value_to_string(obj)\n-\n-    def handle_field(self, obj, field):\n-        self._current[field.name] = self._value_from_field(obj, field)\n-\n-    def handle_fk_field(self, obj, field):\n-        if self.use_natural_foreign_keys and hasattr(\n-            field.remote_field.model, \"natural_key\"\n-        ):\n-            related = getattr(obj, field.name)\n-            if related:\n-                value = related.natural_key()\n-            else:\n-                value = None\n-        else:\n-            value = self._value_from_field(obj, field)\n-        self._current[field.name] = value\n-\n-    def handle_m2m_field(self, obj, field):\n-        if field.remote_field.through._meta.auto_created:\n-            if self.use_natural_foreign_keys and hasattr(\n-                field.remote_field.model, \"natural_key\"\n-            ):\n-\n-                def m2m_value(value):\n-                    return value.natural_key()\n-\n-                def queryset_iterator(obj, field):\n-                    return getattr(obj, field.name).iterator()\n-\n-            else:\n-\n-                def m2m_value(value):\n-                    return self._value_from_field(value, value._meta.pk)\n-\n-                def queryset_iterator(obj, field):\n-                    return getattr(obj, field.name).only(\"pk\").iterator()\n-\n-            m2m_iter = getattr(obj, \"_prefetched_objects_cache\", {}).get(\n-                field.name,\n-                queryset_iterator(obj, field),\n-            )\n-            self._current[field.name] = [m2m_value(related) for related in m2m_iter]\n-\n-    def getvalue(self):\n-        return self.objects\n-\n-\n-def Deserializer(\n-    object_list, *, using=DEFAULT_DB_ALIAS, ignorenonexistent=False, **options\n-):\n-    \"\"\"\n-    Deserialize simple Python objects back into Django ORM instances.\n-\n-    It's expected that you pass the Python objects themselves (instead of a\n-    stream or a string) to the constructor\n-    \"\"\"\n-    handle_forward_references = options.pop(\"handle_forward_references\", False)\n-    field_names_cache = {}  # Model: <list of field_names>\n-\n-    for d in object_list:\n-        # Look up the model and starting build a dict of data for it.\n-        try:\n-            Model = _get_model(d[\"model\"])\n-        except base.DeserializationError:\n-            if ignorenonexistent:\n-                continue\n-            else:\n-                raise\n-        data = {}\n-        if \"pk\" in d:\n-            try:\n-                data[Model._meta.pk.attname] = Model._meta.pk.to_python(d.get(\"pk\"))\n-            except Exception as e:\n-                raise base.DeserializationError.WithData(\n-                    e, d[\"model\"], d.get(\"pk\"), None\n-                )\n-        m2m_data = {}\n-        deferred_fields = {}\n-\n-        if Model not in field_names_cache:\n-            field_names_cache[Model] = {f.name for f in Model._meta.get_fields()}\n-        field_names = field_names_cache[Model]\n-\n-        # Handle each field\n-        for field_name, field_value in d[\"fields\"].items():\n-            if ignorenonexistent and field_name not in field_names:\n-                # skip fields no longer on model\n-                continue\n-\n-            field = Model._meta.get_field(field_name)\n-\n-            # Handle M2M relations\n-            if field.remote_field and isinstance(\n-                field.remote_field, models.ManyToManyRel\n-            ):\n-                try:\n-                    values = base.deserialize_m2m_values(\n-                        field, field_value, using, handle_forward_references\n-                    )\n-                except base.M2MDeserializationError as e:\n-                    raise base.DeserializationError.WithData(\n-                        e.original_exc, d[\"model\"], d.get(\"pk\"), e.pk\n-                    )\n-                if values == base.DEFER_FIELD:\n-                    deferred_fields[field] = field_value\n-                else:\n-                    m2m_data[field.name] = values\n-            # Handle FK fields\n-            elif field.remote_field and isinstance(\n-                field.remote_field, models.ManyToOneRel\n-            ):\n-                try:\n-                    value = base.deserialize_fk_value(\n-                        field, field_value, using, handle_forward_references\n-                    )\n-                except Exception as e:\n-                    raise base.DeserializationError.WithData(\n-                        e, d[\"model\"], d.get(\"pk\"), field_value\n-                    )\n-                if value == base.DEFER_FIELD:\n-                    deferred_fields[field] = field_value\n-                else:\n-                    data[field.attname] = value\n-            # Handle all other fields\n-            else:\n-                try:\n-                    data[field.name] = field.to_python(field_value)\n-                except Exception as e:\n-                    raise base.DeserializationError.WithData(\n-                        e, d[\"model\"], d.get(\"pk\"), field_value\n-                    )\n-\n-        obj = base.build_instance(Model, data, using)\n-        yield base.DeserializedObject(obj, m2m_data, deferred_fields)\n-\n-\n-def _get_model(model_identifier):\n-    \"\"\"Look up a model from an \"app_label.model_name\" string.\"\"\"\n-    try:\n-        return apps.get_model(model_identifier)\n-    except (LookupError, TypeError):\n-        raise base.DeserializationError(\n-            \"Invalid model identifier: '%s'\" % model_identifier\n-        )\n", "model": "claude-sonnet-5-5", "steps": 26, "finished": false, "patch_lines": 195, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 195, "steps": 26}], "ms": 177677}
{"instance_id": "mwaskom__seaborn-3069", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/seaborn/_core/plot.py b/seaborn/_core/plot.py\nindex 4f0290a4..e69de29b 100644\n--- a/seaborn/_core/plot.py\n+++ b/seaborn/_core/plot.py\n@@ -1,1649 +0,0 @@\n-\"\"\"The classes for specifying and compiling a declarative visualization.\"\"\"\n-from __future__ import annotations\n-\n-import io\n-import os\n-import re\n-import sys\n-import inspect\n-import itertools\n-import textwrap\n-from contextlib import contextmanager\n-from collections import abc\n-from collections.abc import Callable, Generator\n-from typing import Any, List, Optional, cast\n-\n-from cycler import cycler\n-import pandas as pd\n-from pandas import DataFrame, Series, Index\n-import matplotlib as mpl\n-from matplotlib.axes import Axes\n-from matplotlib.artist import Artist\n-from matplotlib.figure import Figure\n-\n-from seaborn._marks.base import Mark\n-from seaborn._stats.base import Stat\n-from seaborn._core.data import PlotData\n-from seaborn._core.moves import Move\n-from seaborn._core.scales import Scale\n-from seaborn._core.subplots import Subplots\n-from seaborn._core.groupby import GroupBy\n-from seaborn._core.properties import PROPERTIES, Property\n-from seaborn._core.typing import (\n-    DataSource,\n-    VariableSpec,\n-    VariableSpecList,\n-    OrderSpec,\n-    Default,\n-)\n-from seaborn._core.rules import categorical_order\n-from seaborn._compat import set_scale_obj, set_layout_engine\n-from seaborn.rcmod import axes_style, plotting_context\n-from seaborn.palettes import color_palette\n-from seaborn.external.version import Version\n-\n-from typing import TYPE_CHECKING\n-if TYPE_CHECKING:\n-    from matplotlib.figure import SubFigure\n-\n-\n-if sys.version_info >= (3, 8):\n-    from typing import TypedDict\n-else:\n-    from typing_extensions import TypedDict\n-\n-\n-default = Default()\n-\n-\n-# ---- Definitions for internal specs --------------------------------- #\n-\n-\n-class Layer(TypedDict, total=False):\n-\n-    mark: Mark  # TODO allow list?\n-    stat: Stat | None  # TODO allow list?\n-    move: Move | list[Move] | None\n-    data: PlotData\n-    source: DataSource\n-    vars: dict[str, VariableSpec]\n-    orient: str\n-    legend: bool\n-\n-\n-class FacetSpec(TypedDict, total=False):\n-\n-    variables: dict[str, VariableSpec]\n-    structure: dict[str, list[str]]\n-    wrap: int | None\n-\n-\n-class PairSpec(TypedDict, total=False):\n-\n-    variables: dict[str, VariableSpec]\n-    structure: dict[str, list[str]]\n-    cross: bool\n-    wrap: int | None\n-\n-\n-# --- Local helpers ----------------------------------------------------------------\n-\n-\n-@contextmanager\n-def theme_context(params: dict[str, Any]) -> Generator:\n-    \"\"\"Temporarily modify specifc matplotlib rcParams.\"\"\"\n-    orig_params = {k: mpl.rcParams[k] for k in params}\n-    color_codes = \"bgrmyck\"\n-    nice_colors = [*color_palette(\"deep6\"), (.15, .15, .15)]\n-    orig_colors = [mpl.colors.colorConverter.colors[x] for x in color_codes]\n-    # TODO how to allow this to reflect the color cycle when relevant?\n-    try:\n-        mpl.rcParams.update(params)\n-        for (code, color) in zip(color_codes, nice_colors):\n-            mpl.colors.colorConverter.colors[code] = color\n-            mpl.colors.colorConverter.cache[code] = color\n-        yield\n-    finally:\n-        mpl.rcParams.update(orig_params)\n-        for (code, color) in zip(color_codes, orig_colors):\n-            mpl.colors.colorConverter.colors[code] = color\n-            mpl.colors.colorConverter.cache[code] = color\n-\n-\n-def build_plot_signature(cls):\n-    \"\"\"\n-    Decorator function for giving Plot a useful signature.\n-\n-    Currently this mostly saves us some duplicated typing, but we would\n-    like eventually to have a way of registering new semantic properties,\n-    at which point dynamic signature generation would become more important.\n-\n-    \"\"\"\n-    sig = inspect.signature(cls)\n-    params = [\n-        inspect.Parameter(\"args\", inspect.Parameter.VAR_POSITIONAL),\n-        inspect.Parameter(\"data\", inspect.Parameter.KEYWORD_ONLY, default=None)\n-    ]\n-    params.extend([\n-        inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=None)\n-        for name in PROPERTIES\n-    ])\n-    new_sig = sig.replace(parameters=params)\n-    cls.__signature__ = new_sig\n-\n-    known_properties = textwrap.fill(\n-        \", \".join([f\"|{p}|\" for p in PROPERTIES]),\n-        width=78, subsequent_indent=\" \" * 8,\n-    )\n-\n-    if cls.__doc__ is not None:  # support python -OO mode\n-        cls.__doc__ = cls.__doc__.format(known_properties=known_properties)\n-\n-    return cls\n-\n-\n-# ---- The main interface for declarative plotting -------------------- #\n-\n-\n-@build_plot_signature\n-class Plot:\n-    \"\"\"\n-    An interface for declaratively specifying statistical graphics.\n-\n-    Plots are constructed by initializing this class and adding one or more\n-    layers, comprising a `Mark` and optional `Stat` or `Move`.  Additionally,\n-    faceting variables or variable pairings may be defined to divide the space\n-    into multiple subplots. The mappings from data values to visual properties\n-    can be parametrized using scales, although the plot will try to infer good\n-    defaults when scales are not explicitly defined.\n-\n-    The constructor accepts a data source (a :class:`pandas.DataFrame` or\n-    dictionary with columnar values) and variable assignments. Variables can be\n-    passed as keys to the data source or directly as data vectors.  If multiple\n-    data-containing objects are provided, they will be index-aligned.\n-\n-    The data source and variables defined in the constructor will be used for\n-    all layers in the plot, unless overridden or disabled when adding a layer.\n-\n-    The following variables can be defined in the constructor:\n-        {known_properties}\n-\n-    The `data`, `x`, and `y` variables can be passed as positional arguments or\n-    using keywords. Whether the first positional argument is interpreted as a\n-    data source or `x` variable depends on its type.\n-\n-    The methods of this class return a copy of the instance; use chaining to\n-    build up a plot through multiple calls. Methods can be called in any order.\n-\n-    Most methods only add information to the plot spec; no actual processing\n-    happens until the plot is shown or saved. It is also possible to compile\n-    the plot without rendering it to access the lower-level representation.\n-\n-    \"\"\"\n-    _data: PlotData\n-    _layers: list[Layer]\n-\n-    _scales: dict[str, Scale]\n-    _shares: dict[str, bool | str]\n-    _limits: dict[str, tuple[Any, Any]]\n-    _labels: dict[str, str | Callable[[str], str]]\n-    _theme: dict[str, Any]\n-\n-    _facet_spec: FacetSpec\n-    _pair_spec: PairSpec\n-\n-    _figure_spec: dict[str, Any]\n-    _subplot_spec: dict[str, Any]\n-    _layout_spec: dict[str, Any]\n-\n-    def __init__(\n-        self,\n-        *args: DataSource | VariableSpec,\n-        data: DataSource = None,\n-        **variables: VariableSpec,\n-    ):\n-\n-        if args:\n-            data, variables = self._resolve_positionals(args, data, variables)\n-\n-        unknown = [x for x in variables if x not in PROPERTIES]\n-        if unknown:\n-            err = f\"Plot() got unexpected keyword argument(s): {', '.join(unknown)}\"\n-            raise TypeError(err)\n-\n-        self._data = PlotData(data, variables)\n-\n-        self._layers = []\n-\n-        self._scales = {}\n-        self._shares = {}\n-        self._limits = {}\n-        self._labels = {}\n-        self._theme = {}\n-\n-        self._facet_spec = {}\n-        self._pair_spec = {}\n-\n-        self._figure_spec = {}\n-        self._subplot_spec = {}\n-        self._layout_spec = {}\n-\n-        self._target = None\n-\n-    def _resolve_positionals(\n-        self,\n-        args: tuple[DataSource | VariableSpec, ...],\n-        data: DataSource,\n-        variables: dict[str, VariableSpec],\n-    ) -> tuple[DataSource, dict[str, VariableSpec]]:\n-        \"\"\"Handle positional arguments, which may contain data / x / y.\"\"\"\n-        if len(args) > 3:\n-            err = \"Plot() accepts no more than 3 positional arguments (data, x, y).\"\n-            raise TypeError(err)\n-\n-        # TODO need some clearer way to differentiate data / vector here\n-        # (There might be an abstract DataFrame class to use here?)\n-        if isinstance(args[0], (abc.Mapping, pd.DataFrame)):\n-            if data is not None:\n-                raise TypeError(\"`data` given by both name and position.\")\n-            data, args = args[0], args[1:]\n-\n-        if len(args) == 2:\n-            x, y = args\n-        elif len(args) == 1:\n-            x, y = *args, None\n-        else:\n-            x = y = None\n-\n-        for name, var in zip(\"yx\", (y, x)):\n-            if var is not None:\n-                if name in variables:\n-                    raise TypeError(f\"`{name}` given by both name and position.\")\n-                # Keep coordinates at the front of the variables dict\n-                # Cast type because we know this isn't a DataSource at this point\n-                variables = {name: cast(VariableSpec, var), **variables}\n-\n-        return data, variables\n-\n-    def __add__(self, other):\n-\n-        if isinstance(other, Mark) or isinstance(other, Stat):\n-            raise TypeError(\"Sorry, this isn't ggplot! Perhaps try Plot.add?\")\n-\n-        other_type = other.__class__.__name__\n-        raise TypeError(f\"Unsupported operand type(s) for +: 'Plot' and '{other_type}\")\n-\n-    def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n-\n-        return self.plot()._repr_png_()\n-\n-    # TODO _repr_svg_?\n-\n-    def _clone(self) -> Plot:\n-        \"\"\"Generate a new object with the same information as the current spec.\"\"\"\n-        new = Plot()\n-\n-        # TODO any way to enforce that data does not get mutated?\n-        new._data = self._data\n-\n-        new._layers.extend(self._layers)\n-\n-        new._scales.update(self._scales)\n-        new._shares.update(self._shares)\n-        new._limits.update(self._limits)\n-        new._labels.update(self._labels)\n-        new._theme.update(self._theme)\n-\n-        new._facet_spec.update(self._facet_spec)\n-        new._pair_spec.update(self._pair_spec)\n-\n-        new._figure_spec.update(self._figure_spec)\n-        new._subplot_spec.update(self._subplot_spec)\n-        new._layout_spec.update(self._layout_spec)\n-\n-        new._target = self._target\n-\n-        return new\n-\n-    def _theme_with_defaults(self) -> dict[str, Any]:\n-\n-        style_groups = [\n-            \"axes\", \"figure\", \"font\", \"grid\", \"hatch\", \"legend\", \"lines\",\n-            \"mathtext\", \"markers\", \"patch\", \"savefig\", \"scatter\",\n-            \"xaxis\", \"xtick\", \"yaxis\", \"ytick\",\n-        ]\n-        base = {\n-            k: mpl.rcParamsDefault[k] for k in mpl.rcParams\n-            if any(k.startswith(p) for p in style_groups)\n-        }\n-        theme = {\n-            **base,\n-            **axes_style(\"darkgrid\"),\n-            **plotting_context(\"notebook\"),\n-            \"axes.prop_cycle\": cycler(\"color\", color_palette(\"deep\")),\n-        }\n-        theme.update(self._theme)\n-        return theme\n-\n-    @property\n-    def _variables(self) -> list[str]:\n-\n-        variables = (\n-            list(self._data.frame)\n-            + list(self._pair_spec.get(\"variables\", []))\n-            + list(self._facet_spec.get(\"variables\", []))\n-        )\n-        for layer in self._layers:\n-            variables.extend(v for v in layer[\"vars\"] if v not in variables)\n-\n-        # Coerce to str in return to appease mypy; we know these will only\n-        # ever be strings but I don't think we can type a DataFrame that way yet\n-        return [str(v) for v in variables]\n-\n-    def on(self, target: Axes | SubFigure | Figure) -> Plot:\n-        \"\"\"\n-        Provide existing Matplotlib figure or axes for drawing the plot.\n-\n-        When using this method, you will also need to explicitly call a method that\n-        triggers compilation, such as :meth:`Plot.show` or :meth:`Plot.save`. If you\n-        want to postprocess using matplotlib, you'd need to call :meth:`Plot.plot`\n-        first to compile the plot without rendering it.\n-\n-        Parameters\n-        ----------\n-        target : Axes, SubFigure, or Figure\n-            Matplotlib object to use. Passing :class:`matplotlib.axes.Axes` will add\n-            artists without otherwise modifying the figure. Otherwise, subplots will be\n-            created within the space of the given :class:`matplotlib.figure.Figure` or\n-            :class:`matplotlib.figure.SubFigure`.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.on.rst\n-\n-        \"\"\"\n-        accepted_types: tuple  # Allow tuple of various length\n-        if hasattr(mpl.figure, \"SubFigure\"):  # Added in mpl 3.4\n-            accepted_types = (\n-                mpl.axes.Axes, mpl.figure.SubFigure, mpl.figure.Figure\n-            )\n-            accepted_types_str = (\n-                f\"{mpl.axes.Axes}, {mpl.figure.SubFigure}, or {mpl.figure.Figure}\"\n-            )\n-        else:\n-            accepted_types = mpl.axes.Axes, mpl.figure.Figure\n-            accepted_types_str = f\"{mpl.axes.Axes} or {mpl.figure.Figure}\"\n-\n-        if not isinstance(target, accepted_types):\n-            err = (\n-                f\"The `Plot.on` target must be an instance of {accepted_types_str}. \"\n-                f\"You passed an instance of {target.__class__} instead.\"\n-            )\n-            raise TypeError(err)\n-\n-        new = self._clone()\n-        new._target = target\n-\n-        return new\n-\n-    def add(\n-        self,\n-        mark: Mark,\n-        *transforms: Stat | Mark,\n-        orient: str | None = None,\n-        legend: bool = True,\n-        data: DataSource = None,\n-        **variables: VariableSpec,\n-    ) -> Plot:\n-        \"\"\"\n-        Specify a layer of the visualization in terms of mark and data transform(s).\n-\n-        This is the main method for specifying how the data should be visualized.\n-        It can be called multiple times with different arguments to define\n-        a plot with multiple layers.\n-\n-        Parameters\n-        ----------\n-        mark : :class:`Mark`\n-            The visual representation of the data to use in this layer.\n-        transforms : :class:`Stat` or :class:`Move`\n-            Objects representing transforms to be applied before plotting the data.\n-            Currently, at most one :class:`Stat` can be used, and it\n-            must be passed first. This constraint will be relaxed in the future.\n-        orient : \"x\", \"y\", \"v\", or \"h\"\n-            The orientation of the mark, which also affects how transforms are computed.\n-            Typically corresponds to the axis that defines groups for aggregation.\n-            The \"v\" (vertical) and \"h\" (horizontal) options are synonyms for \"x\" / \"y\",\n-            but may be more intuitive with some marks. When not provided, an\n-            orientation will be inferred from characteristics of the data and scales.\n-        legend : bool\n-            Option to suppress the mark/mappings for this layer from the legend.\n-        data : DataFrame or dict\n-            Data source to override the global source provided in the constructor.\n-        variables : data vectors or identifiers\n-            Additional layer-specific variables, including variables that will be\n-            passed directly to the transforms without scaling.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.add.rst\n-\n-        \"\"\"\n-        if not isinstance(mark, Mark):\n-            msg = f\"mark must be a Mark instance, not {type(mark)!r}.\"\n-            raise TypeError(msg)\n-\n-        # TODO This API for transforms was a late decision, and previously Plot.add\n-        # accepted 0 or 1 Stat instances and 0, 1, or a list of Move instances.\n-        # It will take some work to refactor the internals so that Stat and Move are\n-        # treated identically, and until then well need to \"unpack\" the transforms\n-        # here and enforce limitations on the order / types.\n-\n-        stat: Optional[Stat]\n-        move: Optional[List[Move]]\n-        error = False\n-        if not transforms:\n-            stat, move = None, None\n-        elif isinstance(transforms[0], Stat):\n-            stat = transforms[0]\n-            move = [m for m in transforms[1:] if isinstance(m, Move)]\n-            error = len(move) != len(transforms) - 1\n-        else:\n-            stat = None\n-            move = [m for m in transforms if isinstance(m, Move)]\n-            error = len(move) != len(transforms)\n-\n-        if error:\n-            msg = \" \".join([\n-                \"Transforms must have at most one Stat type (in the first position),\",\n-                \"and all others must be a Move type. Given transform type(s):\",\n-                \", \".join(str(type(t).__name__) for t in transforms) + \".\"\n-            ])\n-            raise TypeError(msg)\n-\n-        new = self._clone()\n-        new._layers.append({\n-            \"mark\": mark,\n-            \"stat\": stat,\n-            \"move\": move,\n-            # TODO it doesn't work to supply scalars to variables, but it should\n-            \"vars\": variables,\n-            \"source\": data,\n-            \"legend\": legend,\n-            \"orient\": {\"v\": \"x\", \"h\": \"y\"}.get(orient, orient),  # type: ignore\n-        })\n-\n-        return new\n-\n-    def pair(\n-        self,\n-        x: VariableSpecList = None,\n-        y: VariableSpecList = None,\n-        wrap: int | None = None,\n-        cross: bool = True,\n-    ) -> Plot:\n-        \"\"\"\n-        Produce subplots by pairing multiple `x` and/or `y` variables.\n-\n-        Parameters\n-        ----------\n-        x, y : sequence(s) of data vectors or identifiers\n-            Variables that will define the grid of subplots.\n-        wrap : int\n-            When using only `x` or `y`, \"wrap\" subplots across a two-dimensional grid\n-            with this many columns (when using `x`) or rows (when using `y`).\n-        cross : bool\n-            When False, zip the `x` and `y` lists such that the first subplot gets the\n-            first pair, the second gets the second pair, etc. Otherwise, create a\n-            two-dimensional grid from the cartesian product of the lists.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.pair.rst\n-\n-        \"\"\"\n-        # TODO Add transpose= arg, which would then draw pair(y=[...]) across rows\n-        # This may also be possible by setting `wrap=1`, but is that too unobvious?\n-        # TODO PairGrid features not currently implemented: diagonals, corner\n-\n-        pair_spec: PairSpec = {}\n-\n-        axes = {\"x\": [] if x is None else x, \"y\": [] if y is None else y}\n-        for axis, arg in axes.items():\n-            if isinstance(arg, (str, int)):\n-                err = f\"You must pass a sequence of variable keys to `{axis}`\"\n-                raise TypeError(err)\n-\n-        pair_spec[\"variables\"] = {}\n-        pair_spec[\"structure\"] = {}\n-\n-        for axis in \"xy\":\n-            keys = []\n-            for i, col in enumerate(axes[axis]):\n-                key = f\"{axis}{i}\"\n-                keys.append(key)\n-                pair_spec[\"variables\"][key] = col\n-\n-            if keys:\n-                pair_spec[\"structure\"][axis] = keys\n-\n-        if not cross and len(axes[\"x\"]) != len(axes[\"y\"]):\n-            err = \"Lengths of the `x` and `y` lists must match with cross=False\"\n-            raise ValueError(err)\n-\n-        pair_spec[\"cross\"] = cross\n-        pair_spec[\"wrap\"] = wrap\n-\n-        new = self._clone()\n-        new._pair_spec.update(pair_spec)\n-        return new\n-\n-    def facet(\n-        self,\n-        col: VariableSpec = None,\n-        row: VariableSpec = None,\n-        order: OrderSpec | dict[str, OrderSpec] = None,\n-        wrap: int | None = None,\n-    ) -> Plot:\n-        \"\"\"\n-        Produce subplots with conditional subsets of the data.\n-\n-        Parameters\n-        ----------\n-        col, row : data vectors or identifiers\n-            Variables used to define subsets along the columns and/or rows of the grid.\n-            Can be references to the global data source passed in the constructor.\n-        order : list of strings, or dict with dimensional keys\n-            Define the order of the faceting variables.\n-        wrap : int\n-            When using only `col` or `row`, wrap subplots across a two-dimensional\n-            grid with this many subplots on the faceting dimension.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.facet.rst\n-\n-        \"\"\"\n-        variables: dict[str, VariableSpec] = {}\n-        if col is not None:\n-            variables[\"col\"] = col\n-        if row is not None:\n-            variables[\"row\"] = row\n-\n-        structure = {}\n-        if isinstance(order, dict):\n-            for dim in [\"col\", \"row\"]:\n-                dim_order = order.get(dim)\n-                if dim_order is not None:\n-                    structure[dim] = list(dim_order)\n-        elif order is not None:\n-            if col is not None and row is not None:\n-                err = \" \".join([\n-                    \"When faceting on both col= and row=, passing `order` as a list\"\n-                    \"is ambiguous. Use a dict with 'col' and/or 'row' keys instead.\"\n-                ])\n-                raise RuntimeError(err)\n-            elif col is not None:\n-                structure[\"col\"] = list(order)\n-            elif row is not None:\n-                structure[\"row\"] = list(order)\n-\n-        spec: FacetSpec = {\n-            \"variables\": variables,\n-            \"structure\": structure,\n-            \"wrap\": wrap,\n-        }\n-\n-        new = self._clone()\n-        new._facet_spec.update(spec)\n-\n-        return new\n-\n-    # TODO def twin()?\n-\n-    def scale(self, **scales: Scale) -> Plot:\n-        \"\"\"\n-        Specify mappings from data units to visual properties.\n-\n-        Keywords correspond to variables defined in the plot, including coordinate\n-        variables (`x`, `y`) and semantic variables (`color`, `pointsize`, etc.).\n-\n-        A number of \"magic\" arguments are accepted, including:\n-            - The name of a transform (e.g., `\"log\"`, `\"sqrt\"`)\n-            - The name of a palette (e.g., `\"viridis\"`, `\"muted\"`)\n-            - A tuple of values, defining the output range (e.g. `(1, 5)`)\n-            - A dict, implying a :class:`Nominal` scale (e.g. `{\"a\": .2, \"b\": .5}`)\n-            - A list of values, implying a :class:`Nominal` scale (e.g. `[\"b\", \"r\"]`)\n-\n-        For more explicit control, pass a scale spec object such as :class:`Continuous`\n-        or :class:`Nominal`. Or use `None` to use an \"identity\" scale, which treats data\n-        values as literally encoding visual properties.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.scale.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-        new._scales.update(scales)\n-        return new\n-\n-    def share(self, **shares: bool | str) -> Plot:\n-        \"\"\"\n-        Control sharing of axis limits and ticks across subplots.\n-\n-        Keywords correspond to variables defined in the plot, and values can be\n-        boolean (to share across all subplots), or one of \"row\" or \"col\" (to share\n-        more selectively across one dimension of a grid).\n-\n-        Behavior for non-coordinate variables is currently undefined.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.share.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-        new._shares.update(shares)\n-        return new\n-\n-    def limit(self, **limits: tuple[Any, Any]) -> Plot:\n-        \"\"\"\n-        Control the range of visible data.\n-\n-        Keywords correspond to variables defined in the plot, and values are a\n-        `(min, max)` tuple (where either can be `None` to leave unset).\n-\n-        Limits apply only to the axis; data outside the visible range are\n-        still used for any stat transforms and added to the plot.\n-\n-        Behavior for non-coordinate variables is currently undefined.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.limit.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-        new._limits.update(limits)\n-        return new\n-\n-    def label(self, *, title=None, **variables: str | Callable[[str], str]) -> Plot:\n-        \"\"\"\n-        Control the labels and titles for axes, legends, and subplots.\n-\n-        Additional keywords correspond to variables defined in the plot.\n-        Values can be one of the following types:\n-\n-        - string (used literally; pass \"\" to clear the default label)\n-        - function (called on the default label)\n-\n-        For coordinate variables, the value sets the axis label.\n-        For semantic variables, the value sets the legend title.\n-        For faceting variables, `title=` modifies the subplot-specific label,\n-        while `col=` and/or `row=` add a label for the faceting variable.\n-        When using a single subplot, `title=` sets its title.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.label.rst\n-\n-\n-        \"\"\"\n-        new = self._clone()\n-        if title is not None:\n-            new._labels[\"title\"] = title\n-        new._labels.update(variables)\n-        return new\n-\n-    def layout(\n-        self,\n-        *,\n-        size: tuple[float, float] | Default = default,\n-        engine: str | None | Default = default,\n-    ) -> Plot:\n-        \"\"\"\n-        Control the figure size and layout.\n-\n-        .. note::\n-\n-            Default figure sizes and the API for specifying the figure size are subject\n-            to change in future \"experimental\" releases of the objects API. The default\n-            layout engine may also change.\n-\n-        Parameters\n-        ----------\n-        size : (width, height)\n-            Size of the resulting figure, in inches. Size is inclusive of legend when\n-            using pyplot, but not otherwise.\n-        engine : {{\"tight\", \"constrained\", None}}\n-            Name of method for automatically adjusting the layout to remove overlap.\n-            The default depends on whether :meth:`Plot.on` is used.\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.layout.rst\n-\n-        \"\"\"\n-        # TODO add an \"auto\" mode for figsize that roughly scales with the rcParams\n-        # figsize (so that works), but expands to prevent subplots from being squished\n-        # Also should we have height=, aspect=, exclusive with figsize? Or working\n-        # with figsize when only one is defined?\n-\n-        new = self._clone()\n-\n-        if size is not default:\n-            new._figure_spec[\"figsize\"] = size\n-        if engine is not default:\n-            new._layout_spec[\"engine\"] = engine\n-\n-        return new\n-\n-    # TODO def legend (ugh)\n-\n-    def theme(self, *args: dict[str, Any]) -> Plot:\n-        \"\"\"\n-        Control the default appearance of elements in the plot.\n-\n-        .. note::\n-\n-            The API for customizing plot appearance is not yet finalized.\n-            Currently, the only valid argument is a dict of matplotlib rc parameters.\n-            (This dict must be passed as a positional argument.)\n-\n-            It is likely that this method will be enhanced in future releases.\n-\n-        Matplotlib rc parameters are documented on the following page:\n-        https://matplotlib.org/stable/tutorials/introductory/customizing.html\n-\n-        Examples\n-        --------\n-        .. include:: ../docstrings/objects.Plot.theme.rst\n-\n-        \"\"\"\n-        new = self._clone()\n-\n-        # We can skip this whole block on Python 3.8+ with positional-only syntax\n-        nargs = len(args)\n-        if nargs != 1:\n-            err = f\"theme() takes 1 positional argument, but {nargs} were given\"\n-            raise TypeError(err)\n-\n-        rc = args[0]\n-        new._theme.update(rc)\n-\n-        return new\n-\n-    def save(self, loc, **kwargs) -> Plot:\n-        \"\"\"\n-        Compile the plot and write it to a buffer or file on disk.\n-\n-        Parameters\n-        ----------\n-        loc : str, path, or buffer\n-            Location on disk to save the figure, or a buffer to write into.\n-        kwargs\n-            Other keyword arguments are passed through to\n-            :meth:`matplotlib.figure.Figure.savefig`.\n-\n-        \"\"\"\n-        # TODO expose important keyword arguments in our signature?\n-        with theme_context(self._theme_with_defaults()):\n-            self._plot().save(loc, **kwargs)\n-        return self\n-\n-    def show(self, **kwargs) -> None:\n-        \"\"\"\n-        Compile the plot and display it by hooking into pyplot.\n-\n-        Calling this method is not necessary to render a plot in notebook context,\n-        but it may be in other environments (e.g., in a terminal). After compiling the\n-        plot, it calls :func:`matplotlib.pyplot.show` (passing any keyword parameters).\n-\n-        Unlike other :class:`Plot` methods, there is no return value. This should be\n-        the last method you call when specifying a plot.\n-\n-        \"\"\"\n-        # TODO make pyplot configurable at the class level, and when not using,\n-        # import IPython.display and call on self to populate cell output?\n-\n-        # Keep an eye on whether matplotlib implements \"attaching\" an existing\n-        # figure to pyplot: https://github.com/matplotlib/matplotlib/pull/14024\n-\n-        self.plot(pyplot=True).show(**kwargs)\n-\n-    def plot(self, pyplot: bool = False) -> Plotter:\n-        \"\"\"\n-        Compile the plot spec and return the Plotter object.\n-        \"\"\"\n-        with theme_context(self._theme_with_defaults()):\n-            return self._plot(pyplot)\n-\n-    def _plot(self, pyplot: bool = False) -> Plotter:\n-\n-        # TODO if we have _target object, pyplot should be determined by whether it\n-        # is hooked into the pyplot state machine (how do we check?)\n-\n-        plotter = Plotter(pyplot=pyplot, theme=self._theme_with_defaults())\n-\n-        # Process the variable assignments and initialize the figure\n-        common, layers = plotter._extract_data(self)\n-        plotter._setup_figure(self, common, layers)\n-\n-        # Process the scale spec for coordinate variables and transform their data\n-        coord_vars = [v for v in self._variables if re.match(r\"^x|y\", v)]\n-        plotter._setup_scales(self, common, layers, coord_vars)\n-\n-        # Apply statistical transform(s)\n-        plotter._compute_stats(self, layers)\n-\n-        # Process scale spec for semantic variables and coordinates computed by stat\n-        plotter._setup_scales(self, common, layers)\n-\n-        # TODO Remove these after updating other methods\n-        # ---- Maybe have debug= param that attaches these when True?\n-        plotter._data = common\n-        plotter._layers = layers\n-\n-        # Process the data for each layer and add matplotlib artists\n-        for layer in layers:\n-            plotter._plot_layer(self, layer)\n-\n-        # Add various figure decorations\n-        plotter._make_legend(self)\n-        plotter._finalize_figure(self)\n-\n-        return plotter\n-\n-\n-# ---- The plot compilation engine ---------------------------------------------- #\n-\n-\n-class Plotter:\n-    \"\"\"\n-    Engine for compiling a :class:`Plot` spec into a Matplotlib figure.\n-\n-    This class is not intended to be instantiated directly by users.\n-\n-    \"\"\"\n-    # TODO decide if we ever want these (Plot.plot(debug=True))?\n-    _data: PlotData\n-    _layers: list[Layer]\n-    _figure: Figure\n-\n-    def __init__(self, pyplot: bool, theme: dict[str, Any]):\n-\n-        self._pyplot = pyplot\n-        self._theme = theme\n-        self._legend_contents: list[tuple[\n-            tuple[str, str | int], list[Artist], list[str],\n-        ]] = []\n-        self._scales: dict[str, Scale] = {}\n-\n-    def save(self, loc, **kwargs) -> Plotter:  # TODO type args\n-        kwargs.setdefault(\"dpi\", 96)\n-        try:\n-            loc = os.path.expanduser(loc)\n-        except TypeError:\n-            # loc may be a buffer in which case that would not work\n-            pass\n-        self._figure.savefig(loc, **kwargs)\n-        return self\n-\n-    def show(self, **kwargs) -> None:\n-        \"\"\"\n-        Display the plot by hooking into pyplot.\n-\n-        This method calls :func:`matplotlib.pyplot.show` with any keyword parameters.\n-\n-        \"\"\"\n-        # TODO if we did not create the Plotter with pyplot, is it possible to do this?\n-        # If not we should clearly raise.\n-        import matplotlib.pyplot as plt\n-        with theme_context(self._theme):\n-            plt.show(**kwargs)\n-\n-    # TODO API for accessing the underlying matplotlib objects\n-    # TODO what else is useful in the public API for this class?\n-\n-    def _repr_png_(self) -> tuple[bytes, dict[str, float]]:\n-\n-        # TODO better to do this through a Jupyter hook? e.g.\n-        # ipy = IPython.core.formatters.get_ipython()\n-        # fmt = ipy.display_formatter.formatters[\"text/html\"]\n-        # fmt.for_type(Plot, ...)\n-        # Would like to have a svg option too, not sure how to make that flexible\n-\n-        # TODO use matplotlib backend directly instead of going through savefig?\n-\n-        # TODO perhaps have self.show() flip a switch to disable this, so that\n-        # user does not end up with two versions of the figure in the output\n-\n-        # TODO use bbox_inches=\"tight\" like the inline backend?\n-        # pro: better results,  con: (sometimes) confusing results\n-        # Better solution would be to default (with option to change)\n-        # to using constrained/tight layout.\n-\n-        # TODO need to decide what the right default behavior here is:\n-        # - Use dpi=72 to match default InlineBackend figure size?\n-        # - Accept a generic \"scaling\" somewhere and scale DPI from that,\n-        #   either with 1x -> 72 or 1x -> 96 and the default scaling be .75?\n-        # - Listen to rcParams? InlineBackend behavior makes that so complicated :(\n-        # - Do we ever want to *not* use retina mode at this point?\n-\n-        from PIL import Image\n-\n-        dpi = 96\n-        buffer = io.BytesIO()\n-\n-        with theme_context(self._theme):\n-            self._figure.savefig(buffer, dpi=dpi * 2, format=\"png\", bbox_inches=\"tight\")\n-        data = buffer.getvalue()\n-\n-        scaling = .85 / 2\n-        w, h = Image.open(buffer).size\n-        metadata = {\"width\": w * scaling, \"height\": h * scaling}\n-        return data, metadata\n-\n-    def _extract_data(self, p: Plot) -> tuple[PlotData, list[Layer]]:\n-\n-        common_data = (\n-            p._data\n-            .join(None, p._facet_spec.get(\"variables\"))\n-            .join(None, p._pair_spec.get(\"variables\"))\n-        )\n-\n-        layers: list[Layer] = []\n-        for layer in p._layers:\n-            spec = layer.copy()\n-            spec[\"data\"] = common_data.join(layer.get(\"source\"), layer.get(\"vars\"))\n-            layers.append(spec)\n-\n-        return common_data, layers\n-\n-    def _resolve_label(self, p: Plot, var: str, auto_label: str | None) -> str:\n-\n-        label: str\n-        if var in p._labels:\n-            manual_label = p._labels[var]\n-            if callable(manual_label) and auto_label is not None:\n-                label = manual_label(auto_label)\n-            else:\n-                label = cast(str, manual_label)\n-        elif auto_label is None:\n-            label = \"\"\n-        else:\n-            label = auto_label\n-        return label\n-\n-    def _setup_figure(self, p: Plot, common: PlotData, layers: list[Layer]) -> None:\n-\n-        # --- Parsing the faceting/pairing parameterization to specify figure grid\n-\n-        subplot_spec = p._subplot_spec.copy()\n-        facet_spec = p._facet_spec.copy()\n-        pair_spec = p._pair_spec.copy()\n-\n-        for axis in \"xy\":\n-            if axis in p._shares:\n-                subplot_spec[f\"share{axis}\"] = p._shares[axis]\n-\n-        for dim in [\"col\", \"row\"]:\n-            if dim in common.frame and dim not in facet_spec[\"structure\"]:\n-                order = categorical_order(common.frame[dim])\n-                facet_spec[\"structure\"][dim] = order\n-\n-        self._subplots = subplots = Subplots(subplot_spec, facet_spec, pair_spec)\n-\n-        # --- Figure initialization\n-        self._figure = subplots.init_figure(\n-            pair_spec, self._pyplot, p._figure_spec, p._target,\n-        )\n-\n-        # --- Figure annotation\n-        for sub in subplots:\n-            ax = sub[\"ax\"]\n-            for axis in \"xy\":\n-                axis_key = sub[axis]\n-\n-                # ~~ Axis labels\n-\n-                # TODO Should we make it possible to use only one x/y label for\n-                # all rows/columns in a faceted plot? Maybe using sub{axis}label,\n-                # although the alignments of the labels from that method leaves\n-                # something to be desired (in terms of how it defines 'centered').\n-                names = [\n-                    common.names.get(axis_key),\n-                    *(layer[\"data\"].names.get(axis_key) for layer in layers)\n-                ]\n-                auto_label = next((name for name in names if name is not None), None)\n-                label = self._resolve_label(p, axis_key, auto_label)\n-                ax.set(**{f\"{axis}label\": label})\n-\n-                # ~~ Decoration visibility\n-\n-                # TODO there should be some override (in Plot.layout?) so that\n-                # axis / tick labels can be shown on interior shared axes if desired\n-\n-                axis_obj = getattr(ax, f\"{axis}axis\")\n-                visible_side = {\"x\": \"bottom\", \"y\": \"left\"}.get(axis)\n-                show_axis_label = (\n-                    sub[visible_side]\n-                    or not p._pair_spec.get(\"cross\", True)\n-                    or (\n-                        axis in p._pair_spec.get(\"structure\", {})\n-                        and bool(p._pair_spec.get(\"wrap\"))\n-                    )\n-                )\n-                axis_obj.get_label().set_visible(show_axis_label)\n-\n-                show_tick_labels = (\n-                    show_axis_label\n-                    or subplot_spec.get(f\"share{axis}\") not in (\n-                        True, \"all\", {\"x\": \"col\", \"y\": \"row\"}[axis]\n-                    )\n-                )\n-                for group in (\"major\", \"minor\"):\n-                    for t in getattr(axis_obj, f\"get_{group}ticklabels\")():\n-                        t.set_visible(show_tick_labels)\n-\n-            # TODO we want right-side titles for row facets in most cases?\n-            # Let's have what we currently call \"margin titles\" but properly using the\n-            # ax.set_title interface (see my gist)\n-            title_parts = []\n-            for dim in [\"col\", \"row\"]:\n-                if sub[dim] is not None:\n-                    val = self._resolve_label(p, \"title\", f\"{sub[dim]}\")\n-                    if dim in p._labels:\n-                        key = self._resolve_label(p, dim, common.names.get(dim))\n-                        val = f\"{key} {val}\"\n-                    title_parts.append(val)\n-\n-            has_col = sub[\"col\"] is not None\n-            has_row = sub[\"row\"] is not None\n-            show_title = (\n-                has_col and has_row\n-                or (has_col or has_row) and p._facet_spec.get(\"wrap\")\n-                or (has_col and sub[\"top\"])\n-                # TODO or has_row and sub[\"right\"] and <right titles>\n-                or has_row  # TODO and not <right titles>\n-            )\n-            if title_parts:\n-                title = \" | \".join(title_parts)\n-                title_text = ax.set_title(title)\n-                title_text.set_visible(show_title)\n-            elif not (has_col or has_row):\n-                title = self._resolve_label(p, \"title\", None)\n-                title_text = ax.set_title(title)\n-\n-    def _compute_stats(self, spec: Plot, layers: list[Layer]) -> None:\n-\n-        grouping_vars = [v for v in PROPERTIES if v not in \"xy\"]\n-        grouping_vars += [\"col\", \"row\", \"group\"]\n-\n-        pair_vars = spec._pair_spec.get(\"structure\", {})\n-\n-        for layer in layers:\n-\n-            data = layer[\"data\"]\n-            mark = layer[\"mark\"]\n-            stat = layer[\"stat\"]\n-\n-            if stat is None:\n-                continue\n-\n-            iter_axes = itertools.product(*[\n-                pair_vars.get(axis, [axis]) for axis in \"xy\"\n-            ])\n-\n-            old = data.frame\n-\n-            if pair_vars:\n-                data.frames = {}\n-                data.frame = data.frame.iloc[:0]  # TODO to simplify typing\n-\n-            for coord_vars in iter_axes:\n-\n-                pairings = \"xy\", coord_vars\n-\n-                df = old.copy()\n-                scales = self._scales.copy()\n-\n-                for axis, var in zip(*pairings):\n-                    if axis != var:\n-                        df = df.rename(columns={var: axis})\n-                        drop_cols = [x for x in df if re.match(rf\"{axis}\\d+\", str(x))]\n-                        df = df.drop(drop_cols, axis=1)\n-                        scales[axis] = scales[var]\n-\n-                orient = layer[\"orient\"] or mark._infer_orient(scales)\n-\n-                if stat.group_by_orient:\n-                    grouper = [orient, *grouping_vars]\n-                else:\n-                    grouper = grouping_vars\n-                groupby = GroupBy(grouper)\n-                res = stat(df, groupby, orient, scales)\n-\n-                if pair_vars:\n-                    data.frames[coord_vars] = res\n-                else:\n-                    data.frame = res\n-\n-    def _get_scale(\n-        self, spec: Plot, var: str, prop: Property, values: Series\n-    ) -> Scale:\n-\n-        if var in spec._scales:\n-            arg = spec._scales[var]\n-            if arg is None or isinstance(arg, Scale):\n-                scale = arg\n-            else:\n-                scale = prop.infer_scale(arg, values)\n-        else:\n-            scale = prop.default_scale(values)\n-\n-        return scale\n-\n-    def _get_subplot_data(self, df, var, view, share_state):\n-\n-        if share_state in [True, \"all\"]:\n-            # The all-shared case is easiest, every subplot sees all the data\n-            seed_values = df[var]\n-        else:\n-            # Otherwise, we need to setup separate scales for different subplots\n-            if share_state in [False, \"none\"]:\n-                # Fully independent axes are also easy: use each subplot's data\n-                idx = self._get_subplot_index(df, view)\n-            elif share_state in df:\n-                # Sharing within row/col is more complicated\n-                use_rows = df[share_state] == view[share_state]\n-                idx = df.index[use_rows]\n-            else:\n-                # This configuration doesn't make much sense, but it's fine\n-                idx = df.index\n-\n-            seed_values = df.loc[idx, var]\n-\n-        return seed_values\n-\n-    def _setup_scales(\n-        self, p: Plot,\n-        common: PlotData,\n-        layers: list[Layer],\n-        variables: list[str] | None = None,\n-    ) -> None:\n-\n-        if variables is None:\n-            # Add variables that have data but not a scale, which happens\n-            # because this method can be called multiple time, to handle\n-            # variables added during the Stat transform.\n-            variables = []\n-            for layer in layers:\n-                variables.extend(layer[\"data\"].frame.columns)\n-                for df in layer[\"data\"].frames.values():\n-                    variables.extend(str(v) for v in df if v not in variables)\n-            variables = [v for v in variables if v not in self._scales]\n-\n-        for var in variables:\n-\n-            # Determine whether this is a coordinate variable\n-            # (i.e., x/y, paired x/y, or derivative such as xmax)\n-            m = re.match(r\"^(?P<coord>(?P<axis>x|y)\\d*).*\", var)\n-            if m is None:\n-                coord = axis = None\n-            else:\n-                coord = m[\"coord\"]\n-                axis = m[\"axis\"]\n-\n-            # Get keys that handle things like x0, xmax, properly where relevant\n-            prop_key = var if axis is None else axis\n-            scale_key = var if coord is None else coord\n-\n-            if prop_key not in PROPERTIES:\n-                continue\n-\n-            # Concatenate layers, using only the relevant coordinate and faceting vars,\n-            # This is unnecessarily wasteful, as layer data will often be redundant.\n-            # But figuring out the minimal amount we need is more complicated.\n-            cols = [var, \"col\", \"row\"]\n-            parts = [common.frame.filter(cols)]\n-            for layer in layers:\n-                parts.append(layer[\"data\"].frame.filter(cols))\n-                for df in layer[\"data\"].frames.values():\n-                    parts.append(df.filter(cols))\n-            var_df = pd.concat(parts, ignore_index=True)\n-\n-            prop = PROPERTIES[prop_key]\n-            scale = self._get_scale(p, scale_key, prop, var_df[var])\n-\n-            if scale_key not in p._variables:\n-                # TODO this implies that the variable was added by the stat\n-                # It allows downstream orientation inference to work properly.\n-                # But it feels rather hacky, so ideally revisit.\n-                scale._priority = 0  # type: ignore\n-\n-            if axis is None:\n-                # We could think about having a broader concept of (un)shared properties\n-                # In general, not something you want to do (different scales in facets)\n-                # But could make sense e.g. with paired plots. Build later.\n-                share_state = None\n-                subplots = []\n-            else:\n-                share_state = self._subplots.subplot_spec[f\"share{axis}\"]\n-                subplots = [view for view in self._subplots if view[axis] == coord]\n-\n-            # Shared categorical axes are broken on matplotlib<3.4.0.\n-            # https://github.com/matplotlib/matplotlib/pull/18308\n-            # This only affects us when sharing *paired* axes. This is a novel/niche\n-            # behavior, so we will raise rather than hack together a workaround.\n-            if axis is not None and Version(mpl.__version__) < Version(\"3.4.0\"):\n-                from seaborn._core.scales import Nominal\n-                paired_axis = axis in p._pair_spec.get(\"structure\", {})\n-                cat_scale = isinstance(scale, Nominal)\n-                ok_dim = {\"x\": \"col\", \"y\": \"row\"}[axis]\n-                shared_axes = share_state not in [False, \"none\", ok_dim]\n-                if paired_axis and cat_scale and shared_axes:\n-                    err = \"Sharing paired categorical axes requires matplotlib>=3.4.0\"\n-                    raise RuntimeError(err)\n-\n-            if scale is None:\n-                self._scales[var] = Scale._identity()\n-            else:\n-                self._scales[var] = scale._setup(var_df[var], prop)\n-\n-            # Everything below here applies only to coordinate variables\n-            # We additionally skip it when we're working with a value\n-            # that is derived from a coordinate we've already processed.\n-            # e.g., the Stat consumed y and added ymin/ymax. In that case,\n-            # we've already setup the y scale and ymin/max are in scale space.\n-            if axis is None or (var != coord and coord in p._variables):\n-                continue\n-\n-            # Set up an empty series to receive the transformed values.\n-            # We need this to handle piecemeal transforms of categories -> floats.\n-            transformed_data = []\n-            for layer in layers:\n-                index = layer[\"data\"].frame.index\n-                empty_series = pd.Series(dtype=float, index=index, name=var)\n-                transformed_data.append(empty_series)\n-\n-            for view in subplots:\n-\n-                axis_obj = getattr(view[\"ax\"], f\"{axis}axis\")\n-                seed_values = self._get_subplot_data(var_df, var, view, share_state)\n-                view_scale = scale._setup(seed_values, prop, axis=axis_obj)\n-                set_scale_obj(view[\"ax\"], axis, view_scale._matplotlib_scale)\n-\n-                for layer, new_series in zip(layers, transformed_data):\n-                    layer_df = layer[\"data\"].frame\n-                    if var in layer_df:\n-                        idx = self._get_subplot_index(layer_df, view)\n-                        new_series.loc[idx] = view_scale(layer_df.loc[idx, var])\n-\n-            # Now the transformed data series are complete, set update the layer data\n-            for layer, new_series in zip(layers, transformed_data):\n-                layer_df = layer[\"data\"].frame\n-                if var in layer_df:\n-                    layer_df[var] = new_series\n-\n-    def _plot_layer(self, p: Plot, layer: Layer) -> None:\n-\n-        data = layer[\"data\"]\n-        mark = layer[\"mark\"]\n-        move = layer[\"move\"]\n-\n-        default_grouping_vars = [\"col\", \"row\", \"group\"]  # TODO where best to define?\n-        grouping_properties = [v for v in PROPERTIES if v[0] not in \"xy\"]\n-\n-        pair_variables = p._pair_spec.get(\"structure\", {})\n-\n-        for subplots, df, scales in self._generate_pairings(data, pair_variables):\n-\n-            orient = layer[\"orient\"] or mark._infer_orient(scales)\n-\n-            def get_order(var):\n-                # Ignore order for x/y: they have been scaled to numeric indices,\n-                # so any original order is no longer valid. Default ordering rules\n-                # sorted unique numbers will correctly reconstruct intended order\n-                # TODO This is tricky, make sure we add some tests for this\n-                if var not in \"xy\" and var in scales:\n-                    return getattr(scales[var], \"order\", None)\n-\n-            if \"width\" in mark._mappable_props:\n-                width = mark._resolve(df, \"width\", None)\n-            else:\n-                width = 0.8 if \"width\" not in df else df[\"width\"]  # TODO what default?\n-            if orient in df:\n-                df[\"width\"] = width * scales[orient]._spacing(df[orient])\n-\n-            if \"baseline\" in mark._mappable_props:\n-                # TODO what marks should have this?\n-                # If we can set baseline with, e.g., Bar(), then the\n-                # \"other\" (e.g. y for x oriented bars) parameterization\n-                # is somewhat ambiguous.\n-                baseline = mark._resolve(df, \"baseline\", None)\n-            else:\n-                # TODO unlike width, we might not want to add baseline to data\n-                # if the mark doesn't use it. Practically, there is a concern about\n-                # Mark abstraction like Area / Ribbon\n-                baseline = 0 if \"baseline\" not in df else df[\"baseline\"]\n-            df[\"baseline\"] = baseline\n-\n-            if move is not None:\n-                moves = move if isinstance(move, list) else [move]\n-                for move_step in moves:\n-                    move_by = getattr(move_step, \"by\", None)\n-                    if move_by is None:\n-                        move_by = grouping_properties\n-                    move_groupers = [*move_by, *default_grouping_vars]\n-                    if move_step.group_by_orient:\n-                        move_groupers.insert(0, orient)\n-                    order = {var: get_order(var) for var in move_groupers}\n-                    groupby = GroupBy(order)\n-                    df = move_step(df, groupby, orient, scales)\n-\n-            df = self._unscale_coords(subplots, df, orient)\n-\n-            grouping_vars = mark._grouping_props + default_grouping_vars\n-            split_generator = self._setup_split_generator(grouping_vars, df, subplots)\n-\n-            mark._plot(split_generator, scales, orient)\n-\n-        # TODO is this the right place for this?\n-        for view in self._subplots:\n-            view[\"ax\"].autoscale_view()\n-\n-        if layer[\"legend\"]:\n-            self._update_legend_contents(p, mark, data, scales)\n-\n-    def _unscale_coords(\n-        self, subplots: list[dict], df: DataFrame, orient: str,\n-    ) -> DataFrame:\n-        # TODO do we still have numbers in the variable name at this point?\n-        coord_cols = [c for c in df if re.match(r\"^[xy]\\D*$\", str(c))]\n-        drop_cols = [*coord_cols, \"width\"] if \"width\" in df else coord_cols\n-        out_df = (\n-            df\n-            .drop(drop_cols, axis=1)\n-            .reindex(df.columns, axis=1)  # So unscaled columns retain their place\n-            .copy(deep=False)\n-        )\n-\n-        for view in subplots:\n-            view_df = self._filter_subplot_data(df, view)\n-            axes_df = view_df[coord_cols]\n-            for var, values in axes_df.items():\n-\n-                axis = getattr(view[\"ax\"], f\"{str(var)[0]}axis\")\n-                # TODO see https://github.com/matplotlib/matplotlib/issues/22713\n-                transform = axis.get_transform().inverted().transform\n-                inverted = transform(values)\n-                out_df.loc[values.index, str(var)] = inverted\n-\n-                if var == orient and \"width\" in view_df:\n-                    width = view_df[\"width\"]\n-                    out_df.loc[values.index, \"width\"] = (\n-                        transform(values + width / 2) - transform(values - width / 2)\n-                    )\n-\n-        return out_df\n-\n-    def _generate_pairings(\n-        self, data: PlotData, pair_variables: dict,\n-    ) -> Generator[\n-        tuple[list[dict], DataFrame, dict[str, Scale]], None, None\n-    ]:\n-        # TODO retype return with subplot_spec or similar\n-\n-        iter_axes = itertools.product(*[\n-            pair_variables.get(axis, [axis]) for axis in \"xy\"\n-        ])\n-\n-        for x, y in iter_axes:\n-\n-            subplots = []\n-            for view in self._subplots:\n-                if (view[\"x\"] == x) and (view[\"y\"] == y):\n-                    subplots.append(view)\n-\n-            if data.frame.empty and data.frames:\n-                out_df = data.frames[(x, y)].copy()\n-            elif not pair_variables:\n-                out_df = data.frame.copy()\n-            else:\n-                if data.frame.empty and data.frames:\n-                    out_df = data.frames[(x, y)].copy()\n-                else:\n-                    out_df = data.frame.copy()\n-\n-            scales = self._scales.copy()\n-            if x in out_df:\n-                scales[\"x\"] = self._scales[x]\n-            if y in out_df:\n-                scales[\"y\"] = self._scales[y]\n-\n-            for axis, var in zip(\"xy\", (x, y)):\n-                if axis != var:\n-                    out_df = out_df.rename(columns={var: axis})\n-                    cols = [col for col in out_df if re.match(rf\"{axis}\\d+\", str(col))]\n-                    out_df = out_df.drop(cols, axis=1)\n-\n-            yield subplots, out_df, scales\n-\n-    def _get_subplot_index(self, df: DataFrame, subplot: dict) -> Index:\n-\n-        dims = df.columns.intersection([\"col\", \"row\"])\n-        if dims.empty:\n-            return df.index\n-\n-        keep_rows = pd.Series(True, df.index, dtype=bool)\n-        for dim in dims:\n-            keep_rows &= df[dim] == subplot[dim]\n-        return df.index[keep_rows]\n-\n-    def _filter_subplot_data(self, df: DataFrame, subplot: dict) -> DataFrame:\n-        # TODO note redundancies with preceding function ... needs refactoring\n-        dims = df.columns.intersection([\"col\", \"row\"])\n-        if dims.empty:\n-            return df\n-\n-        keep_rows = pd.Series(True, df.index, dtype=bool)\n-        for dim in dims:\n-            keep_rows &= df[dim] == subplot[dim]\n-        return df[keep_rows]\n-\n-    def _setup_split_generator(\n-        self, grouping_vars: list[str], df: DataFrame, subplots: list[dict[str, Any]],\n-    ) -> Callable[[], Generator]:\n-\n-        allow_empty = False  # TODO will need to recreate previous categorical plots\n-\n-        grouping_keys = []\n-        grouping_vars = [\n-            v for v in grouping_vars if v in df and v not in [\"col\", \"row\"]\n-        ]\n-        for var in grouping_vars:\n-            order = getattr(self._scales[var], \"order\", None)\n-            if order is None:\n-                order = categorical_order(df[var])\n-            grouping_keys.append(order)\n-\n-        def split_generator(keep_na=False) -> Generator:\n-\n-            for view in subplots:\n-\n-                axes_df = self._filter_subplot_data(df, view)\n-\n-                with pd.option_context(\"mode.use_inf_as_null\", True):\n-                    if keep_na:\n-                        # The simpler thing to do would be x.dropna().reindex(x.index).\n-                        # But that doesn't work with the way that the subset iteration\n-                        # is written below, which assumes data for grouping vars.\n-                        # Matplotlib (usually?) masks nan data, so this should \"work\".\n-                        # Downstream code can also drop these rows, at some speed cost.\n-                        present = axes_df.notna().all(axis=1)\n-                        nulled = {}\n-                        for axis in \"xy\":\n-                            if axis in axes_df:\n-                                nulled[axis] = axes_df[axis].where(present)\n-                        axes_df = axes_df.assign(**nulled)\n-                    else:\n-                        axes_df = axes_df.dropna()\n-\n-                subplot_keys = {}\n-                for dim in [\"col\", \"row\"]:\n-                    if view[dim] is not None:\n-                        subplot_keys[dim] = view[dim]\n-\n-                if not grouping_vars or not any(grouping_keys):\n-                    yield subplot_keys, axes_df.copy(), view[\"ax\"]\n-                    continue\n-\n-                grouped_df = axes_df.groupby(grouping_vars, sort=False, as_index=False)\n-\n-                for key in itertools.product(*grouping_keys):\n-\n-                    # Pandas fails with singleton tuple inputs\n-                    pd_key = key[0] if len(key) == 1 else key\n-\n-                    try:\n-                        df_subset = grouped_df.get_group(pd_key)\n-                    except KeyError:\n-                        # TODO (from initial work on categorical plots refactor)\n-                        # We are adding this to allow backwards compatability\n-                        # with the empty artists that old categorical plots would\n-                        # add (before 0.12), which we may decide to break, in which\n-                        # case this option could be removed\n-                        df_subset = axes_df.loc[[]]\n-\n-                    if df_subset.empty and not allow_empty:\n-                        continue\n-\n-                    sub_vars = dict(zip(grouping_vars, key))\n-                    sub_vars.update(subplot_keys)\n-\n-                    # TODO need copy(deep=...) policy (here, above, anywhere else?)\n-                    yield sub_vars, df_subset.copy(), view[\"ax\"]\n-\n-        return split_generator\n-\n-    def _update_legend_contents(\n-        self,\n-        p: Plot,\n-        mark: Mark,\n-        data: PlotData,\n-        scales: dict[str, Scale],\n-    ) -> None:\n-        \"\"\"Add legend artists / labels for one layer in the plot.\"\"\"\n-        if data.frame.empty and data.frames:\n-            legend_vars: list[str] = []\n-            for frame in data.frames.values():\n-                frame_vars = frame.columns.intersection(list(scales))\n-                legend_vars.extend(v for v in frame_vars if v not in legend_vars)\n-        else:\n-            legend_vars = list(data.frame.columns.intersection(list(scales)))\n-\n-        # First pass: Identify the values that will be shown for each variable\n-        schema: list[tuple[\n-            tuple[str, str | int], list[str], tuple[list, list[str]]\n-        ]] = []\n-        schema = []\n-        for var in legend_vars:\n-            var_legend = scales[var]._legend\n-            if var_legend is not None:\n-                values, labels = var_legend\n-                for (_, part_id), part_vars, _ in schema:\n-                    if data.ids[var] == part_id:\n-                        # Allow multiple plot semantics to represent same data variable\n-                        part_vars.append(var)\n-                        break\n-                else:\n-                    title = self._resolve_label(p, var, data.names[var])\n-                    entry = (title, data.ids[var]), [var], (values, labels)\n-                    schema.append(entry)\n-\n-        # Second pass, generate an artist corresponding to each value\n-        contents: list[tuple[tuple[str, str | int], Any, list[str]]] = []\n-        for key, variables, (values, labels) in schema:\n-            artists = []\n-            for val in values:\n-                artist = mark._legend_artist(variables, val, scales)\n-                if artist is not None:\n-                    artists.append(artist)\n-            if artists:\n-                contents.append((key, artists, labels))\n-\n-        self._legend_contents.extend(contents)\n-\n-    def _make_legend(self, p: Plot) -> None:\n-        \"\"\"Create the legend artist(s) and add onto the figure.\"\"\"\n-        # Combine artists representing same information across layers\n-        # Input list has an entry for each distinct variable in each layer\n-        # Output dict has an entry for each distinct variable\n-        merged_contents: dict[\n-            tuple[str, str | int], tuple[list[Artist], list[str]],\n-        ] = {}\n-        for key, new_artists, labels in self._legend_contents:\n-            # Key is (name, id); we need the id to resolve variable uniqueness,\n-            # but will need the name in the next step to title the legend\n-            if key in merged_contents:\n-                # Copy so inplace updates don't propagate back to legend_contents\n-                existing_artists = merged_contents[key][0]\n-                for i, artist in enumerate(existing_artists):\n-                    # Matplotlib accepts a tuple of artists and will overlay them\n-                    if isinstance(artist, tuple):\n-                        artist += new_artists[i],\n-                    else:\n-                        existing_artists[i] = artist, new_artists[i]\n-            else:\n-                merged_contents[key] = new_artists.copy(), labels\n-\n-        # TODO explain\n-        loc = \"center right\" if self._pyplot else \"center left\"\n-\n-        base_legend = None\n-        for (name, _), (handles, labels) in merged_contents.items():\n-\n-            legend = mpl.legend.Legend(\n-                self._figure,\n-                handles,\n-                labels,\n-                title=name,\n-                loc=loc,\n-                bbox_to_anchor=(.98, .55),\n-            )\n-\n-            if base_legend:\n-                # Matplotlib has no public API for this so it is a bit of a hack.\n-                # Ideally we'd define our own legend class with more flexibility,\n-                # but that is a lot of work!\n-                base_legend_box = base_legend.get_children()[0]\n-                this_legend_box = legend.get_children()[0]\n-                base_legend_box.get_children().extend(this_legend_box.get_children())\n-            else:\n-                base_legend = legend\n-                self._figure.legends.append(legend)\n-\n-    def _finalize_figure(self, p: Plot) -> None:\n-\n-        for sub in self._subplots:\n-            ax = sub[\"ax\"]\n-            for axis in \"xy\":\n-                axis_key = sub[axis]\n-\n-                # Axis limits\n-                if axis_key in p._limits:\n-                    convert_units = getattr(ax, f\"{axis}axis\").convert_units\n-                    a, b = p._limits[axis_key]\n-                    lo = a if a is None else convert_units(a)\n-                    hi = b if b is None else convert_units(b)\n-                    if isinstance(a, str):\n-                        lo = cast(float, lo) - 0.5\n-                    if isinstance(b, str):\n-                        hi = cast(float, hi) + 0.5\n-                    ax.set(**{f\"{axis}lim\": (lo, hi)})\n-\n-        engine_default = None if p._target is not None else \"tight\"\n-        layout_engine = p._layout_spec.get(\"engine\", engine_default)\n-        set_layout_engine(self._figure, layout_engine)\n", "model": "claude-sonnet-5-5", "steps": 26, "finished": false, "patch_lines": 1654, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 1654, "steps": 26}], "ms": 171027}
{"instance_id": "pylint-dev__pylint-7277", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/pylint/__init__.py b/pylint/__init__.py\nindex 9f3dd74e6..9e8b7ee9e 100644\n--- a/pylint/__init__.py\n+++ b/pylint/__init__.py\n@@ -86,7 +86,7 @@ def modify_sys_path() -> None:\n     stdlib or pylint's own modules.\n     CPython issue: https://bugs.python.org/issue33053\n \n-    - Remove the first entry. This will always be either \"\" or the working directory\n+    - Remove the first entry if it is either \"\", \".\" or the working directory\n     - Remove the working directory from the second and third entries\n       if PYTHONPATH includes a \":\" at the beginning or the end.\n       https://github.com/PyCQA/pylint/issues/3636\n@@ -96,9 +96,10 @@ def modify_sys_path() -> None:\n       if pylint is installed in an editable configuration (as the last item).\n       https://github.com/PyCQA/pylint/issues/4161\n     \"\"\"\n-    sys.path.pop(0)\n-    env_pythonpath = os.environ.get(\"PYTHONPATH\", \"\")\n     cwd = os.getcwd()\n+    if sys.path[0] in (\"\", \".\", cwd):\n+        sys.path.pop(0)\n+    env_pythonpath = os.environ.get(\"PYTHONPATH\", \"\")\n     if env_pythonpath.startswith(\":\") and env_pythonpath not in (f\":{cwd}\", \":.\"):\n         sys.path.pop(0)\n     elif env_pythonpath.endswith(\":\") and env_pythonpath not in (f\"{cwd}:\", \".:\"):\n", "model": "claude-sonnet-5-5", "steps": 6, "finished": true, "patch_lines": 26, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 26, "steps": 6}], "ms": 15712}
{"instance_id": "scikit-learn__scikit-learn-14710", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py b/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\nindex ad6a5a8ca3..311c8dd065 100644\n--- a/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\n+++ b/sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\n@@ -1,1044 +1 @@\n-\"\"\"Fast Gradient Boosting decision trees for classification and regression.\"\"\"\n-# Author: Nicolas Hug\n-\n-from abc import ABC, abstractmethod\n-from functools import partial\n-\n-import numpy as np\n-from timeit import default_timer as time\n-from ...base import (BaseEstimator, RegressorMixin, ClassifierMixin,\n-                     is_classifier)\n-from ...utils import check_X_y, check_random_state, check_array, resample\n-from ...utils.validation import check_is_fitted\n-from ...utils.multiclass import check_classification_targets\n-from ...metrics import check_scoring\n-from ...model_selection import train_test_split\n-from ...preprocessing import LabelEncoder\n-from ._gradient_boosting import _update_raw_predictions\n-from .common import Y_DTYPE, X_DTYPE, X_BINNED_DTYPE\n-\n-from .binning import _BinMapper\n-from .grower import TreeGrower\n-from .loss import _LOSSES\n-\n-\n-class BaseHistGradientBoosting(BaseEstimator, ABC):\n-    \"\"\"Base class for histogram-based gradient boosting estimators.\"\"\"\n-\n-    @abstractmethod\n-    def __init__(self, loss, learning_rate, max_iter, max_leaf_nodes,\n-                 max_depth, min_samples_leaf, l2_regularization, max_bins,\n-                 warm_start, scoring, validation_fraction, n_iter_no_change,\n-                 tol, verbose, random_state):\n-        self.loss = loss\n-        self.learning_rate = learning_rate\n-        self.max_iter = max_iter\n-        self.max_leaf_nodes = max_leaf_nodes\n-        self.max_depth = max_depth\n-        self.min_samples_leaf = min_samples_leaf\n-        self.l2_regularization = l2_regularization\n-        self.max_bins = max_bins\n-        self.warm_start = warm_start\n-        self.scoring = scoring\n-        self.validation_fraction = validation_fraction\n-        self.n_iter_no_change = n_iter_no_change\n-        self.tol = tol\n-        self.verbose = verbose\n-        self.random_state = random_state\n-\n-    def _validate_parameters(self):\n-        \"\"\"Validate parameters passed to __init__.\n-\n-        The parameters that are directly passed to the grower are checked in\n-        TreeGrower.\"\"\"\n-\n-        if self.loss not in self._VALID_LOSSES:\n-            raise ValueError(\n-                \"Loss {} is not supported for {}. Accepted losses: \"\n-                \"{}.\".format(self.loss, self.__class__.__name__,\n-                             ', '.join(self._VALID_LOSSES)))\n-\n-        if self.learning_rate <= 0:\n-            raise ValueError('learning_rate={} must '\n-                             'be strictly positive'.format(self.learning_rate))\n-        if self.max_iter < 1:\n-            raise ValueError('max_iter={} must not be smaller '\n-                             'than 1.'.format(self.max_iter))\n-        if self.n_iter_no_change is not None and self.n_iter_no_change < 0:\n-            raise ValueError('n_iter_no_change={} must be '\n-                             'positive.'.format(self.n_iter_no_change))\n-        if (self.validation_fraction is not None and\n-                self.validation_fraction <= 0):\n-            raise ValueError(\n-                'validation_fraction={} must be strictly '\n-                'positive, or None.'.format(self.validation_fraction))\n-        if self.tol is not None and self.tol < 0:\n-            raise ValueError('tol={} '\n-                             'must not be smaller than 0.'.format(self.tol))\n-\n-        if not (2 <= self.max_bins <= 255):\n-            raise ValueError('max_bins={} should be no smaller than 2 '\n-                             'and no larger than 255.'.format(self.max_bins))\n-\n-    def fit(self, X, y):\n-        \"\"\"Fit the gradient boosting model.\n-\n-        Parameters\n-        ----------\n-        X : array-like, shape=(n_samples, n_features)\n-            The input samples.\n-\n-        y : array-like, shape=(n_samples,)\n-            Target values.\n-\n-        Returns\n-        -------\n-        self : object\n-        \"\"\"\n-        fit_start_time = time()\n-        acc_find_split_time = 0.  # time spent finding the best splits\n-        acc_apply_split_time = 0.  # time spent splitting nodes\n-        acc_compute_hist_time = 0.  # time spent computing histograms\n-        # time spent predicting X for gradient and hessians update\n-        acc_prediction_time = 0.\n-        X, y = check_X_y(X, y, dtype=[X_DTYPE], force_all_finite=False)\n-        y = self._encode_y(y)\n-\n-        # The rng state must be preserved if warm_start is True\n-        if (self.warm_start and hasattr(self, '_rng')):\n-            rng = self._rng\n-        else:\n-            rng = check_random_state(self.random_state)\n-            self._rng = rng\n-\n-        self._validate_parameters()\n-        self.n_features_ = X.shape[1]  # used for validation in predict()\n-\n-        # we need this stateful variable to tell raw_predict() that it was\n-        # called from fit() (this current method), and that the data it has\n-        # received is pre-binned.\n-        # predicting is faster on pre-binned data, so we want early stopping\n-        # predictions to be made on pre-binned data. Unfortunately the scorer_\n-        # can only call predict() or predict_proba(), not raw_predict(), and\n-        # there's no way to tell the scorer that it needs to predict binned\n-        # data.\n-        self._in_fit = True\n-\n-        self.loss_ = self._get_loss()\n-\n-        self.do_early_stopping_ = (self.n_iter_no_change is not None and\n-                                   self.n_iter_no_change > 0)\n-\n-        # create validation data if needed\n-        self._use_validation_data = self.validation_fraction is not None\n-        if self.do_early_stopping_ and self._use_validation_data:\n-            # stratify for classification\n-            stratify = y if hasattr(self.loss_, 'predict_proba') else None\n-\n-            # Save the state of the RNG for the training and validation split.\n-            # This is needed in order to have the same split when using\n-            # warm starting.\n-            if not (self._is_fitted() and self.warm_start):\n-                self._train_val_split_seed = rng.randint(1024)\n-\n-            X_train, X_val, y_train, y_val = train_test_split(\n-                X, y, test_size=self.validation_fraction, stratify=stratify,\n-                random_state=self._train_val_split_seed)\n-        else:\n-            X_train, y_train = X, y\n-            X_val, y_val = None, None\n-\n-        has_missing_values = np.isnan(X_train).any(axis=0).astype(np.uint8)\n-\n-        # Bin the data\n-        # For ease of use of the API, the user-facing GBDT classes accept the\n-        # parameter max_bins, which doesn't take into account the bin for\n-        # missing values (which is always allocated). However, since max_bins\n-        # isn't the true maximal number of bins, all other private classes\n-        # (binmapper, histbuilder...) accept n_bins instead, which is the\n-        # actual total number of bins. Everywhere in the code, the\n-        # convention is that n_bins == max_bins + 1\n-        n_bins = self.max_bins + 1  # + 1 for missing values\n-        self.bin_mapper_ = _BinMapper(n_bins=n_bins, random_state=rng)\n-        X_binned_train = self._bin_data(X_train, rng, is_training_data=True)\n-        if X_val is not None:\n-            X_binned_val = self._bin_data(X_val, rng, is_training_data=False)\n-        else:\n-            X_binned_val = None\n-\n-        if self.verbose:\n-            print(\"Fitting gradient boosted rounds:\")\n-\n-        n_samples = X_binned_train.shape[0]\n-\n-        # First time calling fit, or no warm start\n-        if not (self._is_fitted() and self.warm_start):\n-            # Clear random state and score attributes\n-            self._clear_state()\n-\n-            # initialize raw_predictions: those are the accumulated values\n-            # predicted by the trees for the training data. raw_predictions has\n-            # shape (n_trees_per_iteration, n_samples) where\n-            # n_trees_per_iterations is n_classes in multiclass classification,\n-            # else 1.\n-            self._baseline_prediction = self.loss_.get_baseline_prediction(\n-                y_train, self.n_trees_per_iteration_\n-            )\n-            raw_predictions = np.zeros(\n-                shape=(self.n_trees_per_iteration_, n_samples),\n-                dtype=self._baseline_prediction.dtype\n-            )\n-            raw_predictions += self._baseline_prediction\n-\n-            # initialize gradients and hessians (empty arrays).\n-            # shape = (n_trees_per_iteration, n_samples).\n-            gradients, hessians = self.loss_.init_gradients_and_hessians(\n-                n_samples=n_samples,\n-                prediction_dim=self.n_trees_per_iteration_\n-            )\n-\n-            # predictors is a matrix (list of lists) of TreePredictor objects\n-            # with shape (n_iter_, n_trees_per_iteration)\n-            self._predictors = predictors = []\n-\n-            # Initialize structures and attributes related to early stopping\n-            self.scorer_ = None  # set if scoring != loss\n-            raw_predictions_val = None  # set if scoring == loss and use val\n-            self.train_score_ = []\n-            self.validation_score_ = []\n-\n-            if self.do_early_stopping_:\n-                # populate train_score and validation_score with the\n-                # predictions of the initial model (before the first tree)\n-\n-                if self.scoring == 'loss':\n-                    # we're going to compute scoring w.r.t the loss. As losses\n-                    # take raw predictions as input (unlike the scorers), we\n-                    # can optimize a bit and avoid repeating computing the\n-                    # predictions of the previous trees. We'll re-use\n-                    # raw_predictions (as it's needed for training anyway) for\n-                    # evaluating the training loss, and create\n-                    # raw_predictions_val for storing the raw predictions of\n-                    # the validation data.\n-\n-                    if self._use_validation_data:\n-                        raw_predictions_val = np.zeros(\n-                            shape=(self.n_trees_per_iteration_,\n-                                   X_binned_val.shape[0]),\n-                            dtype=self._baseline_prediction.dtype\n-                        )\n-\n-                        raw_predictions_val += self._baseline_prediction\n-\n-                    self._check_early_stopping_loss(raw_predictions, y_train,\n-                                                    raw_predictions_val, y_val)\n-                else:\n-                    self.scorer_ = check_scoring(self, self.scoring)\n-                    # scorer_ is a callable with signature (est, X, y) and\n-                    # calls est.predict() or est.predict_proba() depending on\n-                    # its nature.\n-                    # Unfortunately, each call to scorer_() will compute\n-                    # the predictions of all the trees. So we use a subset of\n-                    # the training set to compute train scores.\n-\n-                    # Save the seed for the small trainset generator\n-                    self._small_trainset_seed = rng.randint(1024)\n-\n-                    # Compute the subsample set\n-                    (X_binned_small_train,\n-                     y_small_train) = self._get_small_trainset(\n-                        X_binned_train, y_train, self._small_trainset_seed)\n-\n-                    self._check_early_stopping_scorer(\n-                        X_binned_small_train, y_small_train,\n-                        X_binned_val, y_val,\n-                    )\n-            begin_at_stage = 0\n-\n-        # warm start: this is not the first time fit was called\n-        else:\n-            # Check that the maximum number of iterations is not smaller\n-            # than the number of iterations from the previous fit\n-            if self.max_iter < self.n_iter_:\n-                raise ValueError(\n-                    'max_iter=%d must be larger than or equal to '\n-                    'n_iter_=%d when warm_start==True'\n-                    % (self.max_iter, self.n_iter_)\n-                )\n-\n-            # Convert array attributes to lists\n-            self.train_score_ = self.train_score_.tolist()\n-            self.validation_score_ = self.validation_score_.tolist()\n-\n-            # Compute raw predictions\n-            raw_predictions = self._raw_predict(X_binned_train)\n-\n-            if self.do_early_stopping_ and self.scoring != 'loss':\n-                # Compute the subsample set\n-                X_binned_small_train, y_small_train = self._get_small_trainset(\n-                    X_binned_train, y_train, self._small_trainset_seed)\n-\n-            # Initialize the gradients and hessians\n-            gradients, hessians = self.loss_.init_gradients_and_hessians(\n-                n_samples=n_samples,\n-                prediction_dim=self.n_trees_per_iteration_\n-            )\n-\n-            # Get the predictors from the previous fit\n-            predictors = self._predictors\n-\n-            begin_at_stage = self.n_iter_\n-\n-        for iteration in range(begin_at_stage, self.max_iter):\n-\n-            if self.verbose:\n-                iteration_start_time = time()\n-                print(\"[{}/{}] \".format(iteration + 1, self.max_iter),\n-                      end='', flush=True)\n-\n-            # Update gradients and hessians, inplace\n-            self.loss_.update_gradients_and_hessians(gradients, hessians,\n-                                                     y_train, raw_predictions)\n-\n-            # Append a list since there may be more than 1 predictor per iter\n-            predictors.append([])\n-\n-            # Build `n_trees_per_iteration` trees.\n-            for k in range(self.n_trees_per_iteration_):\n-\n-                grower = TreeGrower(\n-                    X_binned_train, gradients[k, :], hessians[k, :],\n-                    n_bins=n_bins,\n-                    n_bins_non_missing=self.bin_mapper_.n_bins_non_missing_,\n-                    has_missing_values=has_missing_values,\n-                    max_leaf_nodes=self.max_leaf_nodes,\n-                    max_depth=self.max_depth,\n-                    min_samples_leaf=self.min_samples_leaf,\n-                    l2_regularization=self.l2_regularization,\n-                    shrinkage=self.learning_rate)\n-                grower.grow()\n-\n-                acc_apply_split_time += grower.total_apply_split_time\n-                acc_find_split_time += grower.total_find_split_time\n-                acc_compute_hist_time += grower.total_compute_hist_time\n-\n-                predictor = grower.make_predictor(\n-                    bin_thresholds=self.bin_mapper_.bin_thresholds_\n-                )\n-                predictors[-1].append(predictor)\n-\n-                # Update raw_predictions with the predictions of the newly\n-                # created tree.\n-                tic_pred = time()\n-                _update_raw_predictions(raw_predictions[k, :], grower)\n-                toc_pred = time()\n-                acc_prediction_time += toc_pred - tic_pred\n-\n-            should_early_stop = False\n-            if self.do_early_stopping_:\n-                if self.scoring == 'loss':\n-                    # Update raw_predictions_val with the newest tree(s)\n-                    if self._use_validation_data:\n-                        for k, pred in enumerate(self._predictors[-1]):\n-                            raw_predictions_val[k, :] += (\n-                                pred.predict_binned(\n-                                    X_binned_val,\n-                                    self.bin_mapper_.missing_values_bin_idx_\n-                                )\n-                            )\n-\n-                    should_early_stop = self._check_early_stopping_loss(\n-                        raw_predictions, y_train,\n-                        raw_predictions_val, y_val\n-                    )\n-\n-                else:\n-                    should_early_stop = self._check_early_stopping_scorer(\n-                        X_binned_small_train, y_small_train,\n-                        X_binned_val, y_val,\n-                    )\n-\n-            if self.verbose:\n-                self._print_iteration_stats(iteration_start_time)\n-\n-            # maybe we could also early stop if all the trees are stumps?\n-            if should_early_stop:\n-                break\n-\n-        if self.verbose:\n-            duration = time() - fit_start_time\n-            n_total_leaves = sum(\n-                predictor.get_n_leaf_nodes()\n-                for predictors_at_ith_iteration in self._predictors\n-                for predictor in predictors_at_ith_iteration\n-            )\n-            n_predictors = sum(\n-                len(predictors_at_ith_iteration)\n-                for predictors_at_ith_iteration in self._predictors)\n-            print(\"Fit {} trees in {:.3f} s, ({} total leaves)\".format(\n-                n_predictors, duration, n_total_leaves))\n-            print(\"{:<32} {:.3f}s\".format('Time spent computing histograms:',\n-                                          acc_compute_hist_time))\n-            print(\"{:<32} {:.3f}s\".format('Time spent finding best splits:',\n-                                          acc_find_split_time))\n-            print(\"{:<32} {:.3f}s\".format('Time spent applying splits:',\n-                                          acc_apply_split_time))\n-            print(\"{:<32} {:.3f}s\".format('Time spent predicting:',\n-                                          acc_prediction_time))\n-\n-        self.train_score_ = np.asarray(self.train_score_)\n-        self.validation_score_ = np.asarray(self.validation_score_)\n-        del self._in_fit  # hard delete so we're sure it can't be used anymore\n-        return self\n-\n-    def _is_fitted(self):\n-        return len(getattr(self, '_predictors', [])) > 0\n-\n-    def _clear_state(self):\n-        \"\"\"Clear the state of the gradient boosting model.\"\"\"\n-        for var in ('train_score_', 'validation_score_', '_rng'):\n-            if hasattr(self, var):\n-                delattr(self, var)\n-\n-    def _get_small_trainset(self, X_binned_train, y_train, seed):\n-        \"\"\"Compute the indices of the subsample set and return this set.\n-\n-        For efficiency, we need to subsample the training set to compute scores\n-        with scorers.\n-        \"\"\"\n-        subsample_size = 10000\n-        if X_binned_train.shape[0] > subsample_size:\n-            indices = np.arange(X_binned_train.shape[0])\n-            stratify = y_train if is_classifier(self) else None\n-            indices = resample(indices, n_samples=subsample_size,\n-                               replace=False, random_state=seed,\n-                               stratify=stratify)\n-            X_binned_small_train = X_binned_train[indices]\n-            y_small_train = y_train[indices]\n-            X_binned_small_train = np.ascontiguousarray(X_binned_small_train)\n-            return X_binned_small_train, y_small_train\n-        else:\n-            return X_binned_train, y_train\n-\n-    def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,\n-                                     X_binned_val, y_val):\n-        \"\"\"Check if fitting should be early-stopped based on scorer.\n-\n-        Scores are computed on validation data or on training data.\n-        \"\"\"\n-        self.train_score_.append(\n-            self.scorer_(self, X_binned_small_train, y_small_train)\n-        )\n-\n-        if self._use_validation_data:\n-            self.validation_score_.append(\n-                self.scorer_(self, X_binned_val, y_val)\n-            )\n-            return self._should_stop(self.validation_score_)\n-        else:\n-            return self._should_stop(self.train_score_)\n-\n-    def _check_early_stopping_loss(self,\n-                                   raw_predictions,\n-                                   y_train,\n-                                   raw_predictions_val,\n-                                   y_val):\n-        \"\"\"Check if fitting should be early-stopped based on loss.\n-\n-        Scores are computed on validation data or on training data.\n-        \"\"\"\n-\n-        self.train_score_.append(\n-            -self.loss_(y_train, raw_predictions)\n-        )\n-\n-        if self._use_validation_data:\n-            self.validation_score_.append(\n-                -self.loss_(y_val, raw_predictions_val)\n-            )\n-            return self._should_stop(self.validation_score_)\n-        else:\n-            return self._should_stop(self.train_score_)\n-\n-    def _should_stop(self, scores):\n-        \"\"\"\n-        Return True (do early stopping) if the last n scores aren't better\n-        than the (n-1)th-to-last score, up to some tolerance.\n-        \"\"\"\n-        reference_position = self.n_iter_no_change + 1\n-        if len(scores) < reference_position:\n-            return False\n-\n-        # A higher score is always better. Higher tol means that it will be\n-        # harder for subsequent iteration to be considered an improvement upon\n-        # the reference score, and therefore it is more likely to early stop\n-        # because of the lack of significant improvement.\n-        tol = 0 if self.tol is None else self.tol\n-        reference_score = scores[-reference_position] + tol\n-        recent_scores = scores[-reference_position + 1:]\n-        recent_improvements = [score > reference_score\n-                               for score in recent_scores]\n-        return not any(recent_improvements)\n-\n-    def _bin_data(self, X, rng, is_training_data):\n-        \"\"\"Bin data X.\n-\n-        If is_training_data, then set the bin_mapper_ attribute.\n-        Else, the binned data is converted to a C-contiguous array.\n-        \"\"\"\n-\n-        description = 'training' if is_training_data else 'validation'\n-        if self.verbose:\n-            print(\"Binning {:.3f} GB of {} data: \".format(\n-                X.nbytes / 1e9, description), end=\"\", flush=True)\n-        tic = time()\n-        if is_training_data:\n-            X_binned = self.bin_mapper_.fit_transform(X)  # F-aligned array\n-        else:\n-            X_binned = self.bin_mapper_.transform(X)  # F-aligned array\n-            # We convert the array to C-contiguous since predicting is faster\n-            # with this layout (training is faster on F-arrays though)\n-            X_binned = np.ascontiguousarray(X_binned)\n-        toc = time()\n-        if self.verbose:\n-            duration = toc - tic\n-            print(\"{:.3f} s\".format(duration))\n-\n-        return X_binned\n-\n-    def _print_iteration_stats(self, iteration_start_time):\n-        \"\"\"Print info about the current fitting iteration.\"\"\"\n-        log_msg = ''\n-\n-        predictors_of_ith_iteration = [\n-            predictors_list for predictors_list in self._predictors[-1]\n-            if predictors_list\n-        ]\n-        n_trees = len(predictors_of_ith_iteration)\n-        max_depth = max(predictor.get_max_depth()\n-                        for predictor in predictors_of_ith_iteration)\n-        n_leaves = sum(predictor.get_n_leaf_nodes()\n-                       for predictor in predictors_of_ith_iteration)\n-\n-        if n_trees == 1:\n-            log_msg += (\"{} tree, {} leaves, \".format(n_trees, n_leaves))\n-        else:\n-            log_msg += (\"{} trees, {} leaves \".format(n_trees, n_leaves))\n-            log_msg += (\"({} on avg), \".format(int(n_leaves / n_trees)))\n-\n-        log_msg += \"max depth = {}, \".format(max_depth)\n-\n-        if self.do_early_stopping_:\n-            if self.scoring == 'loss':\n-                factor = -1  # score_ arrays contain the negative loss\n-                name = 'loss'\n-            else:\n-                factor = 1\n-                name = 'score'\n-            log_msg += \"train {}: {:.5f}, \".format(name, factor *\n-                                                   self.train_score_[-1])\n-            if self._use_validation_data:\n-                log_msg += \"val {}: {:.5f}, \".format(\n-                    name, factor * self.validation_score_[-1])\n-\n-        iteration_time = time() - iteration_start_time\n-        log_msg += \"in {:0.3f}s\".format(iteration_time)\n-\n-        print(log_msg)\n-\n-    def _raw_predict(self, X):\n-        \"\"\"Return the sum of the leaves values over all predictors.\n-\n-        Parameters\n-        ----------\n-        X : array-like, shape=(n_samples, n_features)\n-            The input samples.\n-\n-        Returns\n-        -------\n-        raw_predictions : array, shape (n_samples * n_trees_per_iteration,)\n-            The raw predicted values.\n-        \"\"\"\n-        X = check_array(X, dtype=[X_DTYPE, X_BINNED_DTYPE],\n-                        force_all_finite=False)\n-        check_is_fitted(self)\n-        if X.shape[1] != self.n_features_:\n-            raise ValueError(\n-                'X has {} features but this estimator was trained with '\n-                '{} features.'.format(X.shape[1], self.n_features_)\n-            )\n-        is_binned = getattr(self, '_in_fit', False)\n-        n_samples = X.shape[0]\n-        raw_predictions = np.zeros(\n-            shape=(self.n_trees_per_iteration_, n_samples),\n-            dtype=self._baseline_prediction.dtype\n-        )\n-        raw_predictions += self._baseline_prediction\n-        for predictors_of_ith_iteration in self._predictors:\n-            for k, predictor in enumerate(predictors_of_ith_iteration):\n-                if is_binned:\n-                    predict = partial(\n-                        predictor.predict_binned,\n-                        missing_values_bin_idx=self.bin_mapper_.missing_values_bin_idx_  # noqa\n-                    )\n-                else:\n-                    predict = predictor.predict\n-                raw_predictions[k, :] += predict(X)\n-\n-        return raw_predictions\n-\n-    def _compute_partial_dependence_recursion(self, grid, target_features):\n-        \"\"\"Fast partial dependence computation.\n-\n-        Parameters\n-        ----------\n-        grid : ndarray, shape (n_samples, n_target_features)\n-            The grid points on which the partial dependence should be\n-            evaluated.\n-        target_features : ndarray, shape (n_target_features)\n-            The set of target features for which the partial dependence\n-            should be evaluated.\n-\n-        Returns\n-        -------\n-        averaged_predictions : ndarray, shape \\\n-                (n_trees_per_iteration, n_samples)\n-            The value of the partial dependence function on each grid point.\n-        \"\"\"\n-        grid = np.asarray(grid, dtype=X_DTYPE, order='C')\n-        averaged_predictions = np.zeros(\n-            (self.n_trees_per_iteration_, grid.shape[0]), dtype=Y_DTYPE)\n-\n-        for predictors_of_ith_iteration in self._predictors:\n-            for k, predictor in enumerate(predictors_of_ith_iteration):\n-                predictor.compute_partial_dependence(grid, target_features,\n-                                                     averaged_predictions[k])\n-        # Note that the learning rate is already accounted for in the leaves\n-        # values.\n-\n-        return averaged_predictions\n-\n-    def _more_tags(self):\n-        return {'allow_nan': True}\n-\n-    @abstractmethod\n-    def _get_loss(self):\n-        pass\n-\n-    @abstractmethod\n-    def _encode_y(self, y=None):\n-        pass\n-\n-    @property\n-    def n_iter_(self):\n-        check_is_fitted(self)\n-        return len(self._predictors)\n-\n-\n-class HistGradientBoostingRegressor(BaseHistGradientBoosting, RegressorMixin):\n-    \"\"\"Histogram-based Gradient Boosting Regression Tree.\n-\n-    This estimator is much faster than\n-    :class:`GradientBoostingRegressor<sklearn.ensemble.GradientBoostingRegressor>`\n-    for big datasets (n_samples >= 10 000).\n-\n-    This estimator has native support for missing values (NaNs). During\n-    training, the tree grower learns at each split point whether samples\n-    with missing values should go to the left or right child, based on the\n-    potential gain. When predicting, samples with missing values are\n-    assigned to the left or right child consequently. If no missing values\n-    were encountered for a given feature during training, then samples with\n-    missing values are mapped to whichever child has the most samples.\n-\n-    This implementation is inspired by\n-    `LightGBM <https://github.com/Microsoft/LightGBM>`_.\n-\n-    .. note::\n-\n-      This estimator is still **experimental** for now: the predictions\n-      and the API might change without any deprecation cycle. To use it,\n-      you need to explicitly import ``enable_hist_gradient_boosting``::\n-\n-        >>> # explicitly require this experimental feature\n-        >>> from sklearn.experimental import enable_hist_gradient_boosting  # noqa\n-        >>> # now you can import normally from ensemble\n-        >>> from sklearn.ensemble import HistGradientBoostingClassifier\n-\n-    Read more in the :ref:`User Guide <histogram_based_gradient_boosting>`.\n-\n-    Parameters\n-    ----------\n-    loss : {'least_squares'}, optional (default='least_squares')\n-        The loss function to use in the boosting process. Note that the\n-        \"least squares\" loss actually implements an \"half least squares loss\"\n-        to simplify the computation of the gradient.\n-    learning_rate : float, optional (default=0.1)\n-        The learning rate, also known as *shrinkage*. This is used as a\n-        multiplicative factor for the leaves values. Use ``1`` for no\n-        shrinkage.\n-    max_iter : int, optional (default=100)\n-        The maximum number of iterations of the boosting process, i.e. the\n-        maximum number of trees.\n-    max_leaf_nodes : int or None, optional (default=31)\n-        The maximum number of leaves for each tree. Must be strictly greater\n-        than 1. If None, there is no maximum limit.\n-    max_depth : int or None, optional (default=None)\n-        The maximum depth of each tree. The depth of a tree is the number of\n-        nodes to go from the root to the deepest leaf. Must be strictly greater\n-        than 1. Depth isn't constrained by default.\n-    min_samples_leaf : int, optional (default=20)\n-        The minimum number of samples per leaf. For small datasets with less\n-        than a few hundred samples, it is recommended to lower this value\n-        since only very shallow trees would be built.\n-    l2_regularization : float, optional (default=0)\n-        The L2 regularization parameter. Use ``0`` for no regularization\n-        (default).\n-    max_bins : int, optional (default=255)\n-        The maximum number of bins to use for non-missing values. Before\n-        training, each feature of the input array `X` is binned into\n-        integer-valued bins, which allows for a much faster training stage.\n-        Features with a small number of unique values may use less than\n-        ``max_bins`` bins. In addition to the ``max_bins`` bins, one more bin\n-        is always reserved for missing values. Must be no larger than 255.\n-    warm_start : bool, optional (default=False)\n-        When set to ``True``, reuse the solution of the previous call to fit\n-        and add more estimators to the ensemble. For results to be valid, the\n-        estimator should be re-trained on the same data only.\n-        See :term:`the Glossary <warm_start>`.\n-    scoring : str or callable or None, optional (default=None)\n-        Scoring parameter to use for early stopping. It can be a single\n-        string (see :ref:`scoring_parameter`) or a callable (see\n-        :ref:`scoring`). If None, the estimator's default scorer is used. If\n-        ``scoring='loss'``, early stopping is checked w.r.t the loss value.\n-        Only used if ``n_iter_no_change`` is not None.\n-    validation_fraction : int or float or None, optional (default=0.1)\n-        Proportion (or absolute size) of training data to set aside as\n-        validation data for early stopping. If None, early stopping is done on\n-        the training data. Only used if ``n_iter_no_change`` is not None.\n-    n_iter_no_change : int or None, optional (default=None)\n-        Used to determine when to \"early stop\". The fitting process is\n-        stopped when none of the last ``n_iter_no_change`` scores are better\n-        than the ``n_iter_no_change - 1`` -th-to-last one, up to some\n-        tolerance. If None or 0, no early-stopping is done.\n-    tol : float or None, optional (default=1e-7)\n-        The absolute tolerance to use when comparing scores during early\n-        stopping. The higher the tolerance, the more likely we are to early\n-        stop: higher tolerance means that it will be harder for subsequent\n-        iterations to be considered an improvement upon the reference score.\n-    verbose: int, optional (default=0)\n-        The verbosity level. If not zero, print some information about the\n-        fitting process.\n-    random_state : int, np.random.RandomStateInstance or None, \\\n-        optional (default=None)\n-        Pseudo-random number generator to control the subsampling in the\n-        binning process, and the train/validation data split if early stopping\n-        is enabled. See :term:`random_state`.\n-\n-    Attributes\n-    ----------\n-    n_iter_ : int\n-        The number of iterations as selected by early stopping (if\n-        n_iter_no_change is not None). Otherwise it corresponds to max_iter.\n-    n_trees_per_iteration_ : int\n-        The number of tree that are built at each iteration. For regressors,\n-        this is always 1.\n-    train_score_ : ndarray, shape (n_iter_ + 1,)\n-        The scores at each iteration on the training data. The first entry\n-        is the score of the ensemble before the first iteration. Scores are\n-        computed according to the ``scoring`` parameter. If ``scoring`` is\n-        not 'loss', scores are computed on a subset of at most 10 000\n-        samples. Empty if no early stopping.\n-    validation_score_ : ndarray, shape (n_iter_ + 1,)\n-        The scores at each iteration on the held-out validation data. The\n-        first entry is the score of the ensemble before the first iteration.\n-        Scores are computed according to the ``scoring`` parameter. Empty if\n-        no early stopping or if ``validation_fraction`` is None.\n-\n-    Examples\n-    --------\n-    >>> # To use this experimental feature, we need to explicitly ask for it:\n-    >>> from sklearn.experimental import enable_hist_gradient_boosting  # noqa\n-    >>> from sklearn.ensemble import HistGradientBoostingRegressor\n-    >>> from sklearn.datasets import load_boston\n-    >>> X, y = load_boston(return_X_y=True)\n-    >>> est = HistGradientBoostingRegressor().fit(X, y)\n-    >>> est.score(X, y)\n-    0.98...\n-    \"\"\"\n-\n-    _VALID_LOSSES = ('least_squares',)\n-\n-    def __init__(self, loss='least_squares', learning_rate=0.1,\n-                 max_iter=100, max_leaf_nodes=31, max_depth=None,\n-                 min_samples_leaf=20, l2_regularization=0., max_bins=255,\n-                 warm_start=False, scoring=None, validation_fraction=0.1,\n-                 n_iter_no_change=None, tol=1e-7, verbose=0,\n-                 random_state=None):\n-        super(HistGradientBoostingRegressor, self).__init__(\n-            loss=loss, learning_rate=learning_rate, max_iter=max_iter,\n-            max_leaf_nodes=max_leaf_nodes, max_depth=max_depth,\n-            min_samples_leaf=min_samples_leaf,\n-            l2_regularization=l2_regularization, max_bins=max_bins,\n-            warm_start=warm_start, scoring=scoring,\n-            validation_fraction=validation_fraction,\n-            n_iter_no_change=n_iter_no_change, tol=tol, verbose=verbose,\n-            random_state=random_state)\n-\n-    def predict(self, X):\n-        \"\"\"Predict values for X.\n-\n-        Parameters\n-        ----------\n-        X : array-like, shape (n_samples, n_features)\n-            The input samples.\n-\n-        Returns\n-        -------\n-        y : ndarray, shape (n_samples,)\n-            The predicted values.\n-        \"\"\"\n-        # Return raw predictions after converting shape\n-        # (n_samples, 1) to (n_samples,)\n-        return self._raw_predict(X).ravel()\n-\n-    def _encode_y(self, y):\n-        # Just convert y to the expected dtype\n-        self.n_trees_per_iteration_ = 1\n-        y = y.astype(Y_DTYPE, copy=False)\n-        return y\n-\n-    def _get_loss(self):\n-        return _LOSSES[self.loss]()\n-\n-\n-class HistGradientBoostingClassifier(BaseHistGradientBoosting,\n-                                     ClassifierMixin):\n-    \"\"\"Histogram-based Gradient Boosting Classification Tree.\n-\n-    This estimator is much faster than\n-    :class:`GradientBoostingClassifier<sklearn.ensemble.GradientBoostingClassifier>`\n-    for big datasets (n_samples >= 10 000).\n-\n-    This estimator has native support for missing values (NaNs). During\n-    training, the tree grower learns at each split point whether samples\n-    with missing values should go to the left or right child, based on the\n-    potential gain. When predicting, samples with missing values are\n-    assigned to the left or right child consequently. If no missing values\n-    were encountered for a given feature during training, then samples with\n-    missing values are mapped to whichever child has the most samples.\n-\n-    This implementation is inspired by\n-    `LightGBM <https://github.com/Microsoft/LightGBM>`_.\n-\n-    .. note::\n-\n-      This estimator is still **experimental** for now: the predictions\n-      and the API might change without any deprecation cycle. To use it,\n-      you need to explicitly import ``enable_hist_gradient_boosting``::\n-\n-        >>> # explicitly require this experimental feature\n-        >>> from sklearn.experimental import enable_hist_gradient_boosting  # noqa\n-        >>> # now you can import normally from ensemble\n-        >>> from sklearn.ensemble import HistGradientBoostingClassifier\n-\n-    Read more in the :ref:`User Guide <histogram_based_gradient_boosting>`.\n-\n-    Parameters\n-    ----------\n-    loss : {'auto', 'binary_crossentropy', 'categorical_crossentropy'}, \\\n-            optional (default='auto')\n-        The loss function to use in the boosting process. 'binary_crossentropy'\n-        (also known as logistic loss) is used for binary classification and\n-        generalizes to 'categorical_crossentropy' for multiclass\n-        classification. 'auto' will automatically choose either loss depending\n-        on the nature of the problem.\n-    learning_rate : float, optional (default=0.1)\n-        The learning rate, also known as *shrinkage*. This is used as a\n-        multiplicative factor for the leaves values. Use ``1`` for no\n-        shrinkage.\n-    max_iter : int, optional (default=100)\n-        The maximum number of iterations of the boosting process, i.e. the\n-        maximum number of trees for binary classification. For multiclass\n-        classification, `n_classes` trees per iteration are built.\n-    max_leaf_nodes : int or None, optional (default=31)\n-        The maximum number of leaves for each tree. Must be strictly greater\n-        than 1. If None, there is no maximum limit.\n-    max_depth : int or None, optional (default=None)\n-        The maximum depth of each tree. The depth of a tree is the number of\n-        nodes to go from the root to the deepest leaf. Must be strictly greater\n-        than 1. Depth isn't constrained by default.\n-    min_samples_leaf : int, optional (default=20)\n-        The minimum number of samples per leaf. For small datasets with less\n-        than a few hundred samples, it is recommended to lower this value\n-        since only very shallow trees would be built.\n-    l2_regularization : float, optional (default=0)\n-        The L2 regularization parameter. Use 0 for no regularization.\n-    max_bins : int, optional (default=255)\n-        The maximum number of bins to use for non-missing values. Before\n-        training, each feature of the input array `X` is binned into\n-        integer-valued bins, which allows for a much faster training stage.\n-        Features with a small number of unique values may use less than\n-        ``max_bins`` bins. In addition to the ``max_bins`` bins, one more bin\n-        is always reserved for missing values. Must be no larger than 255.\n-    warm_start : bool, optional (default=False)\n-        When set to ``True``, reuse the solution of the previous call to fit\n-        and add more estimators to the ensemble. For results to be valid, the\n-        estimator should be re-trained on the same data only.\n-        See :term:`the Glossary <warm_start>`.\n-    scoring : str or callable or None, optional (default=None)\n-        Scoring parameter to use for early stopping. It can be a single\n-        string (see :ref:`scoring_parameter`) or a callable (see\n-        :ref:`scoring`). If None, the estimator's default scorer\n-        is used. If ``scoring='loss'``, early stopping is checked\n-        w.r.t the loss value. Only used if ``n_iter_no_change`` is not None.\n-    validation_fraction : int or float or None, optional (default=0.1)\n-        Proportion (or absolute size) of training data to set aside as\n-        validation data for early stopping. If None, early stopping is done on\n-        the training data.\n-    n_iter_no_change : int or None, optional (default=None)\n-        Used to determine when to \"early stop\". The fitting process is\n-        stopped when none of the last ``n_iter_no_change`` scores are better\n-        than the ``n_iter_no_change - 1`` -th-to-last one, up to some\n-        tolerance. If None or 0, no early-stopping is done.\n-    tol : float or None, optional (default=1e-7)\n-        The absolute tolerance to use when comparing scores. The higher the\n-        tolerance, the more likely we are to early stop: higher tolerance\n-        means that it will be harder for subsequent iterations to be\n-        considered an improvement upon the reference score.\n-    verbose: int, optional (default=0)\n-        The verbosity level. If not zero, print some information about the\n-        fitting process.\n-    random_state : int, np.random.RandomStateInstance or None, \\\n-        optional (default=None)\n-        Pseudo-random number generator to control the subsampling in the\n-        binning process, and the train/validation data split if early stopping\n-        is enabled. See :term:`random_state`.\n-\n-    Attributes\n-    ----------\n-    n_iter_ : int\n-        The number of estimators as selected by early stopping (if\n-        n_iter_no_change is not None). Otherwise it corresponds to max_iter.\n-    n_trees_per_iteration_ : int\n-        The number of tree that are built at each iteration. This is equal to 1\n-        for binary classification, and to ``n_classes`` for multiclass\n-        classification.\n-    train_score_ : ndarray, shape (n_iter_ + 1,)\n-        The scores at each iteration on the training data. The first entry\n-        is the score of the ensemble before the first iteration. Scores are\n-        computed according to the ``scoring`` parameter. If ``scoring`` is\n-        not 'loss', scores are computed on a subset of at most 10 000\n-        samples. Empty if no early stopping.\n-    validation_score_ : ndarray, shape (n_iter_ + 1,)\n-        The scores at each iteration on the held-out validation data. The\n-        first entry is the score of the ensemble before the first iteration.\n-        Scores are computed according to the ``scoring`` parameter. Empty if\n-        no early stopping or if ``validation_fraction`` is None.\n-\n-    Examples\n-    --------\n-    >>> # To use this experimental feature, we need to explicitly ask for it:\n-    >>> from sklearn.experimental import enable_hist_gradient_boosting  # noqa\n-    >>> from sklearn.ensemble import HistGradientBoostingRegressor\n-    >>> from sklearn.datasets import load_iris\n-    >>> X, y = load_iris(return_X_y=True)\n-    >>> clf = HistGradientBoostingClassifier().fit(X, y)\n-    >>> clf.score(X, y)\n-    1.0\n-    \"\"\"\n-\n-    _VALID_LOSSES = ('binary_crossentropy', 'categorical_crossentropy',\n-                     'auto')\n-\n-    def __init__(self, loss='auto', learning_rate=0.1, max_iter=100,\n-                 max_leaf_nodes=31, max_depth=None, min_samples_leaf=20,\n-                 l2_regularization=0., max_bins=255, warm_start=False,\n-                 scoring=None, validation_fraction=0.1, n_iter_no_change=None,\n-                 tol=1e-7, verbose=0, random_state=None):\n-        super(HistGradientBoostingClassifier, self).__init__(\n-            loss=loss, learning_rate=learning_rate, max_iter=max_iter,\n-            max_leaf_nodes=max_leaf_nodes, max_depth=max_depth,\n-            min_samples_leaf=min_samples_leaf,\n-            l2_regularization=l2_regularization, max_bins=max_bins,\n-            warm_start=warm_start, scoring=scoring,\n-            validation_fraction=validation_fraction,\n-            n_iter_no_change=n_iter_no_change, tol=tol, verbose=verbose,\n-            random_state=random_state)\n-\n-    def predict(self, X):\n-        \"\"\"Predict classes for X.\n-\n-        Parameters\n-        ----------\n-        X : array-like, shape (n_samples, n_features)\n-            The input samples.\n-\n-        Returns\n-        -------\n-        y : ndarray, shape (n_samples,)\n-            The predicted classes.\n-        \"\"\"\n-        # TODO: This could be done in parallel\n-        encoded_classes = np.argmax(self.predict_proba(X), axis=1)\n-        return self.classes_[encoded_classes]\n-\n-    def predict_proba(self, X):\n-        \"\"\"Predict class probabilities for X.\n-\n-        Parameters\n-        ----------\n-        X : array-like, shape (n_samples, n_features)\n-            The input samples.\n-\n-        Returns\n-        -------\n-        p : ndarray, shape (n_samples, n_classes)\n-            The class probabilities of the input samples.\n-        \"\"\"\n-        raw_predictions = self._raw_predict(X)\n-        return self.loss_.predict_proba(raw_predictions)\n-\n-    def decision_function(self, X):\n-        \"\"\"Compute the decision function of X.\n-\n-        Parameters\n-        ----------\n-        X : array-like, shape (n_samples, n_features)\n-            The input samples.\n-\n-        Returns\n-        -------\n-        decision : ndarray, shape (n_samples,) or \\\n-                (n_samples, n_trees_per_iteration)\n-            The raw predicted values (i.e. the sum of the trees leaves) for\n-            each sample. n_trees_per_iteration is equal to the number of\n-            classes in multiclass classification.\n-        \"\"\"\n-        decision = self._raw_predict(X)\n-        if decision.shape[0] == 1:\n-            decision = decision.ravel()\n-        return decision.T\n-\n-    def _encode_y(self, y):\n-        # encode classes into 0 ... n_classes - 1 and sets attributes classes_\n-        # and n_trees_per_iteration_\n-        check_classification_targets(y)\n-\n-        label_encoder = LabelEncoder()\n-        encoded_y = label_encoder.fit_transform(y)\n-        self.classes_ = label_encoder.classes_\n-        n_classes = self.classes_.shape[0]\n-        # only 1 tree for binary classification. For multiclass classification,\n-        # we build 1 tree per class.\n-        self.n_trees_per_iteration_ = 1 if n_classes <= 2 else n_classes\n-        encoded_y = encoded_y.astype(Y_DTYPE, copy=False)\n-        return encoded_y\n-\n-    def _get_loss(self):\n-        if self.loss == 'auto':\n-            if self.n_trees_per_iteration_ == 1:\n-                return _LOSSES['binary_crossentropy']()\n-            else:\n-                return _LOSSES['categorical_crossentropy']()\n-\n-        return _LOSSES[self.loss]()\n+PLACEHOLDER\n\\ No newline at end of file\n", "model": "claude-sonnet-5-5", "steps": 9, "finished": true, "patch_lines": 1051, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 1051, "steps": 9}], "ms": 60164}
{"instance_id": "sympy__sympy-15809", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/functions/elementary/miscellaneous.py b/sympy/functions/elementary/miscellaneous.py\nindex 5f9fe73c5c..e69de29bb2 100644\n--- a/sympy/functions/elementary/miscellaneous.py\n+++ b/sympy/functions/elementary/miscellaneous.py\n@@ -1,827 +0,0 @@\n-from __future__ import print_function, division\n-\n-from sympy.core import S, sympify\n-from sympy.core.add import Add\n-from sympy.core.containers import Tuple\n-from sympy.core.operations import LatticeOp, ShortCircuit\n-from sympy.core.function import (Application, Lambda,\n-    ArgumentIndexError)\n-from sympy.core.expr import Expr\n-from sympy.core.mod import Mod\n-from sympy.core.mul import Mul\n-from sympy.core.numbers import Rational\n-from sympy.core.power import Pow\n-from sympy.core.relational import Eq, Relational\n-from sympy.core.singleton import Singleton\n-from sympy.core.symbol import Dummy\n-from sympy.core.rules import Transform\n-from sympy.core.compatibility import as_int, with_metaclass, range\n-from sympy.core.logic import fuzzy_and, fuzzy_or, _torf\n-from sympy.functions.elementary.integers import floor\n-from sympy.logic.boolalg import And, Or\n-\n-def _minmax_as_Piecewise(op, *args):\n-    # helper for Min/Max rewrite as Piecewise\n-    from sympy.functions.elementary.piecewise import Piecewise\n-    ec = []\n-    for i, a in enumerate(args):\n-        c = []\n-        for j in range(i + 1, len(args)):\n-            c.append(Relational(a, args[j], op))\n-        ec.append((a, And(*c)))\n-    return Piecewise(*ec)\n-\n-\n-class IdentityFunction(with_metaclass(Singleton, Lambda)):\n-    \"\"\"\n-    The identity function\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import Id, Symbol\n-    >>> x = Symbol('x')\n-    >>> Id(x)\n-    x\n-\n-    \"\"\"\n-\n-    def __new__(cls):\n-        from sympy.sets.sets import FiniteSet\n-        x = Dummy('x')\n-        #construct \"by hand\" to avoid infinite loop\n-        obj = Expr.__new__(cls, Tuple(x), x)\n-        obj.nargs = FiniteSet(1)\n-        return obj\n-\n-Id = S.IdentityFunction\n-\n-###############################################################################\n-############################# ROOT and SQUARE ROOT FUNCTION ###################\n-###############################################################################\n-\n-\n-def sqrt(arg, evaluate=None):\n-    \"\"\"The square root function\n-\n-    sqrt(x) -> Returns the principal square root of x.\n-\n-    The parameter evaluate determines if the expression should be evaluated.\n-    If None, its value is taken from global_evaluate\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import sqrt, Symbol\n-    >>> x = Symbol('x')\n-\n-    >>> sqrt(x)\n-    sqrt(x)\n-\n-    >>> sqrt(x)**2\n-    x\n-\n-    Note that sqrt(x**2) does not simplify to x.\n-\n-    >>> sqrt(x**2)\n-    sqrt(x**2)\n-\n-    This is because the two are not equal to each other in general.\n-    For example, consider x == -1:\n-\n-    >>> from sympy import Eq\n-    >>> Eq(sqrt(x**2), x).subs(x, -1)\n-    False\n-\n-    This is because sqrt computes the principal square root, so the square may\n-    put the argument in a different branch.  This identity does hold if x is\n-    positive:\n-\n-    >>> y = Symbol('y', positive=True)\n-    >>> sqrt(y**2)\n-    y\n-\n-    You can force this simplification by using the powdenest() function with\n-    the force option set to True:\n-\n-    >>> from sympy import powdenest\n-    >>> sqrt(x**2)\n-    sqrt(x**2)\n-    >>> powdenest(sqrt(x**2), force=True)\n-    x\n-\n-    To get both branches of the square root you can use the rootof function:\n-\n-    >>> from sympy import rootof\n-\n-    >>> [rootof(x**2-3,i) for i in (0,1)]\n-    [-sqrt(3), sqrt(3)]\n-\n-    See Also\n-    ========\n-\n-    sympy.polys.rootoftools.rootof, root, real_root\n-\n-    References\n-    ==========\n-\n-    .. [1] https://en.wikipedia.org/wiki/Square_root\n-    .. [2] https://en.wikipedia.org/wiki/Principal_value\n-    \"\"\"\n-    # arg = sympify(arg) is handled by Pow\n-    return Pow(arg, S.Half, evaluate=evaluate)\n-\n-\n-def cbrt(arg, evaluate=None):\n-    \"\"\"This function computes the principal cube root of `arg`, so\n-    it's just a shortcut for `arg**Rational(1, 3)`.\n-\n-    The parameter evaluate determines if the expression should be evaluated.\n-    If None, its value is taken from global_evaluate.\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import cbrt, Symbol\n-    >>> x = Symbol('x')\n-\n-    >>> cbrt(x)\n-    x**(1/3)\n-\n-    >>> cbrt(x)**3\n-    x\n-\n-    Note that cbrt(x**3) does not simplify to x.\n-\n-    >>> cbrt(x**3)\n-    (x**3)**(1/3)\n-\n-    This is because the two are not equal to each other in general.\n-    For example, consider `x == -1`:\n-\n-    >>> from sympy import Eq\n-    >>> Eq(cbrt(x**3), x).subs(x, -1)\n-    False\n-\n-    This is because cbrt computes the principal cube root, this\n-    identity does hold if `x` is positive:\n-\n-    >>> y = Symbol('y', positive=True)\n-    >>> cbrt(y**3)\n-    y\n-\n-    See Also\n-    ========\n-\n-    sympy.polys.rootoftools.rootof, root, real_root\n-\n-    References\n-    ==========\n-\n-    * https://en.wikipedia.org/wiki/Cube_root\n-    * https://en.wikipedia.org/wiki/Principal_value\n-\n-    \"\"\"\n-    return Pow(arg, Rational(1, 3), evaluate=evaluate)\n-\n-\n-def root(arg, n, k=0, evaluate=None):\n-    \"\"\"root(x, n, k) -> Returns the k-th n-th root of x, defaulting to the\n-    principal root (k=0).\n-\n-    The parameter evaluate determines if the expression should be evaluated.\n-    If None, its value is taken from global_evaluate.\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import root, Rational\n-    >>> from sympy.abc import x, n\n-\n-    >>> root(x, 2)\n-    sqrt(x)\n-\n-    >>> root(x, 3)\n-    x**(1/3)\n-\n-    >>> root(x, n)\n-    x**(1/n)\n-\n-    >>> root(x, -Rational(2, 3))\n-    x**(-3/2)\n-\n-    To get the k-th n-th root, specify k:\n-\n-    >>> root(-2, 3, 2)\n-    -(-1)**(2/3)*2**(1/3)\n-\n-    To get all n n-th roots you can use the rootof function.\n-    The following examples show the roots of unity for n\n-    equal 2, 3 and 4:\n-\n-    >>> from sympy import rootof, I\n-\n-    >>> [rootof(x**2 - 1, i) for i in range(2)]\n-    [-1, 1]\n-\n-    >>> [rootof(x**3 - 1,i) for i in range(3)]\n-    [1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]\n-\n-    >>> [rootof(x**4 - 1,i) for i in range(4)]\n-    [-1, 1, -I, I]\n-\n-    SymPy, like other symbolic algebra systems, returns the\n-    complex root of negative numbers. This is the principal\n-    root and differs from the text-book result that one might\n-    be expecting. For example, the cube root of -8 does not\n-    come back as -2:\n-\n-    >>> root(-8, 3)\n-    2*(-1)**(1/3)\n-\n-    The real_root function can be used to either make the principal\n-    result real (or simply to return the real root directly):\n-\n-    >>> from sympy import real_root\n-    >>> real_root(_)\n-    -2\n-    >>> real_root(-32, 5)\n-    -2\n-\n-    Alternatively, the n//2-th n-th root of a negative number can be\n-    computed with root:\n-\n-    >>> root(-32, 5, 5//2)\n-    -2\n-\n-    See Also\n-    ========\n-\n-    sympy.polys.rootoftools.rootof\n-    sympy.core.power.integer_nthroot\n-    sqrt, real_root\n-\n-    References\n-    ==========\n-\n-    * https://en.wikipedia.org/wiki/Square_root\n-    * https://en.wikipedia.org/wiki/Real_root\n-    * https://en.wikipedia.org/wiki/Root_of_unity\n-    * https://en.wikipedia.org/wiki/Principal_value\n-    * http://mathworld.wolfram.com/CubeRoot.html\n-\n-    \"\"\"\n-    n = sympify(n)\n-    if k:\n-        return Mul(Pow(arg, S.One/n, evaluate=evaluate), S.NegativeOne**(2*k/n), evaluate=evaluate)\n-    return Pow(arg, 1/n, evaluate=evaluate)\n-\n-\n-def real_root(arg, n=None, evaluate=None):\n-    \"\"\"Return the real nth-root of arg if possible. If n is omitted then\n-    all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this\n-    will only create a real root of a principal root -- the presence of\n-    other factors may cause the result to not be real.\n-\n-    The parameter evaluate determines if the expression should be evaluated.\n-    If None, its value is taken from global_evaluate.\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import root, real_root, Rational\n-    >>> from sympy.abc import x, n\n-\n-    >>> real_root(-8, 3)\n-    -2\n-    >>> root(-8, 3)\n-    2*(-1)**(1/3)\n-    >>> real_root(_)\n-    -2\n-\n-    If one creates a non-principal root and applies real_root, the\n-    result will not be real (so use with caution):\n-\n-    >>> root(-8, 3, 2)\n-    -2*(-1)**(2/3)\n-    >>> real_root(_)\n-    -2*(-1)**(2/3)\n-\n-\n-    See Also\n-    ========\n-\n-    sympy.polys.rootoftools.rootof\n-    sympy.core.power.integer_nthroot\n-    root, sqrt\n-    \"\"\"\n-    from sympy.functions.elementary.complexes import Abs, im, sign\n-    from sympy.functions.elementary.piecewise import Piecewise\n-    if n is not None:\n-        return Piecewise(\n-            (root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))),\n-            (Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate),\n-            And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),\n-            (root(arg, n, evaluate=evaluate), True))\n-    rv = sympify(arg)\n-    n1pow = Transform(lambda x: -(-x.base)**x.exp,\n-                      lambda x:\n-                      x.is_Pow and\n-                      x.base.is_negative and\n-                      x.exp.is_Rational and\n-                      x.exp.p == 1 and x.exp.q % 2)\n-    return rv.xreplace(n1pow)\n-\n-###############################################################################\n-############################# MINIMUM and MAXIMUM #############################\n-###############################################################################\n-\n-\n-class MinMaxBase(Expr, LatticeOp):\n-    def __new__(cls, *args, **assumptions):\n-        if not args:\n-            raise ValueError(\"The Max/Min functions must have arguments.\")\n-\n-        args = (sympify(arg) for arg in args)\n-\n-        # first standard filter, for cls.zero and cls.identity\n-        # also reshape Max(a, Max(b, c)) to Max(a, b, c)\n-        try:\n-            args = frozenset(cls._new_args_filter(args))\n-        except ShortCircuit:\n-            return cls.zero\n-\n-        if assumptions.pop('evaluate', True):\n-            # remove redundant args that are easily identified\n-            args = cls._collapse_arguments(args, **assumptions)\n-\n-        # find local zeros\n-        args = cls._find_localzeros(args, **assumptions)\n-\n-        if not args:\n-            return cls.identity\n-\n-        if len(args) == 1:\n-            return list(args).pop()\n-\n-        # base creation\n-        _args = frozenset(args)\n-        obj = Expr.__new__(cls, _args, **assumptions)\n-        obj._argset = _args\n-        return obj\n-\n-    @classmethod\n-    def _collapse_arguments(cls, args, **assumptions):\n-        \"\"\"Remove redundant args.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Min, Max\n-        >>> from sympy.abc import a, b, c, d, e\n-\n-        Any arg in parent that appears in any\n-        parent-like function in any of the flat args\n-        of parent can be removed from that sub-arg:\n-\n-        >>> Min(a, Max(b, Min(a, c, d)))\n-        Min(a, Max(b, Min(c, d)))\n-\n-        If the arg of parent appears in an opposite-than parent\n-        function in any of the flat args of parent that function\n-        can be replaced with the arg:\n-\n-        >>> Min(a, Max(b, Min(c, d, Max(a, e))))\n-        Min(a, Max(b, Min(a, c, d)))\n-\n-        \"\"\"\n-        from sympy.utilities.iterables import ordered\n-        from sympy.utilities.iterables import sift\n-        from sympy.simplify.simplify import walk\n-\n-        if not args:\n-            return args\n-        args = list(ordered(args))\n-        if cls == Min:\n-            other = Max\n-        else:\n-            other = Min\n-\n-        # find global comparable max of Max and min of Min if a new\n-        # value is being introduced in these args at position 0 of\n-        # the ordered args\n-        if args[0].is_number:\n-            sifted = mins, maxs = [], []\n-            for i in args:\n-                for v in walk(i, Min, Max):\n-                    if v.args[0].is_comparable:\n-                        sifted[isinstance(v, Max)].append(v)\n-            small = Min.identity\n-            for i in mins:\n-                v = i.args[0]\n-                if v.is_number and (v < small) == True:\n-                    small = v\n-            big = Max.identity\n-            for i in maxs:\n-                v = i.args[0]\n-                if v.is_number and (v > big) == True:\n-                    big = v\n-            # at the point when this function is called from __new__,\n-            # there may be more than one numeric arg present since\n-            # local zeros have not been handled yet, so look through\n-            # more than the first arg\n-            if cls == Min:\n-                for i in range(len(args)):\n-                    if not args[i].is_number:\n-                        break\n-                    if (args[i] < small) == True:\n-                        small = args[i]\n-            elif cls == Max:\n-                for i in range(len(args)):\n-                    if not args[i].is_number:\n-                        break\n-                    if (args[i] > big) == True:\n-                        big = args[i]\n-            T = None\n-            if cls == Min:\n-                if small != Min.identity:\n-                    other = Max\n-                    T = small\n-            elif big != Max.identity:\n-                other = Min\n-                T = big\n-            if T is not None:\n-                # remove numerical redundancy\n-                for i in range(len(args)):\n-                    a = args[i]\n-                    if isinstance(a, other):\n-                        a0 = a.args[0]\n-                        if ((a0 > T) if other == Max else (a0 < T)) == True:\n-                            args[i] = cls.identity\n-\n-        # remove redundant symbolic args\n-        def do(ai, a):\n-            if not isinstance(ai, (Min, Max)):\n-                return ai\n-            cond = a in ai.args\n-            if not cond:\n-                return ai.func(*[do(i, a) for i in ai.args],\n-                    evaluate=False)\n-            if isinstance(ai, cls):\n-                return ai.func(*[do(i, a) for i in ai.args if i != a],\n-                    evaluate=False)\n-            return a\n-        for i, a in enumerate(args):\n-            args[i + 1:] = [do(ai, a) for ai in args[i + 1:]]\n-\n-        # factor out common elements as for\n-        # Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))\n-        # and vice versa when swapping Min/Max -- do this only for the\n-        # easy case where all functions contain something in common;\n-        # trying to find some optimal subset of args to modify takes\n-        # too long\n-        if len(args) > 1:\n-            common = None\n-            remove = []\n-            sets = []\n-            for i in range(len(args)):\n-                a = args[i]\n-                if not isinstance(a, other):\n-                    continue\n-                s = set(a.args)\n-                common = s if common is None else (common & s)\n-                if not common:\n-                    break\n-                sets.append(s)\n-                remove.append(i)\n-            if common:\n-                sets = filter(None, [s - common for s in sets])\n-                sets = [other(*s, evaluate=False) for s in sets]\n-                for i in reversed(remove):\n-                    args.pop(i)\n-                oargs = [cls(*sets)] if sets else []\n-                oargs.extend(common)\n-                args.append(other(*oargs, evaluate=False))\n-\n-        return args\n-\n-    @classmethod\n-    def _new_args_filter(cls, arg_sequence):\n-        \"\"\"\n-        Generator filtering args.\n-\n-        first standard filter, for cls.zero and cls.identity.\n-        Also reshape Max(a, Max(b, c)) to Max(a, b, c),\n-        and check arguments for comparability\n-        \"\"\"\n-        for arg in arg_sequence:\n-\n-            # pre-filter, checking comparability of arguments\n-            if not isinstance(arg, Expr) or arg.is_real is False or (\n-                    arg.is_number and\n-                    not arg.is_comparable):\n-                raise ValueError(\"The argument '%s' is not comparable.\" % arg)\n-\n-            if arg == cls.zero:\n-                raise ShortCircuit(arg)\n-            elif arg == cls.identity:\n-                continue\n-            elif arg.func == cls:\n-                for x in arg.args:\n-                    yield x\n-            else:\n-                yield arg\n-\n-    @classmethod\n-    def _find_localzeros(cls, values, **options):\n-        \"\"\"\n-        Sequentially allocate values to localzeros.\n-\n-        When a value is identified as being more extreme than another member it\n-        replaces that member; if this is never true, then the value is simply\n-        appended to the localzeros.\n-        \"\"\"\n-        localzeros = set()\n-        for v in values:\n-            is_newzero = True\n-            localzeros_ = list(localzeros)\n-            for z in localzeros_:\n-                if id(v) == id(z):\n-                    is_newzero = False\n-                else:\n-                    con = cls._is_connected(v, z)\n-                    if con:\n-                        is_newzero = False\n-                        if con is True or con == cls:\n-                            localzeros.remove(z)\n-                            localzeros.update([v])\n-            if is_newzero:\n-                localzeros.update([v])\n-        return localzeros\n-\n-    @classmethod\n-    def _is_connected(cls, x, y):\n-        \"\"\"\n-        Check if x and y are connected somehow.\n-        \"\"\"\n-        from sympy.core.exprtools import factor_terms\n-        def hit(v, t, f):\n-            if not v.is_Relational:\n-                return t if v else f\n-        for i in range(2):\n-            if x == y:\n-                return True\n-            r = hit(x >= y, Max, Min)\n-            if r is not None:\n-                return r\n-            r = hit(y <= x, Max, Min)\n-            if r is not None:\n-                return r\n-            r = hit(x <= y, Min, Max)\n-            if r is not None:\n-                return r\n-            r = hit(y >= x, Min, Max)\n-            if r is not None:\n-                return r\n-            # simplification can be expensive, so be conservative\n-            # in what is attempted\n-            x = factor_terms(x - y)\n-            y = S.Zero\n-\n-        return False\n-\n-    def _eval_derivative(self, s):\n-        # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)\n-        i = 0\n-        l = []\n-        for a in self.args:\n-            i += 1\n-            da = a.diff(s)\n-            if da is S.Zero:\n-                continue\n-            try:\n-                df = self.fdiff(i)\n-            except ArgumentIndexError:\n-                df = Function.fdiff(self, i)\n-            l.append(df * da)\n-        return Add(*l)\n-\n-    def _eval_rewrite_as_Abs(self, *args, **kwargs):\n-        from sympy.functions.elementary.complexes import Abs\n-        s = (args[0] + self.func(*args[1:]))/2\n-        d = abs(args[0] - self.func(*args[1:]))/2\n-        return (s + d if isinstance(self, Max) else s - d).rewrite(Abs)\n-\n-    def evalf(self, prec=None, **options):\n-        return self.func(*[a.evalf(prec, **options) for a in self.args])\n-    n = evalf\n-\n-    _eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args)\n-    _eval_is_antihermitian = lambda s: _torf(i.is_antihermitian for i in s.args)\n-    _eval_is_commutative = lambda s: _torf(i.is_commutative for i in s.args)\n-    _eval_is_complex = lambda s: _torf(i.is_complex for i in s.args)\n-    _eval_is_composite = lambda s: _torf(i.is_composite for i in s.args)\n-    _eval_is_even = lambda s: _torf(i.is_even for i in s.args)\n-    _eval_is_finite = lambda s: _torf(i.is_finite for i in s.args)\n-    _eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args)\n-    _eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args)\n-    _eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args)\n-    _eval_is_integer = lambda s: _torf(i.is_integer for i in s.args)\n-    _eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args)\n-    _eval_is_negative = lambda s: _torf(i.is_negative for i in s.args)\n-    _eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args)\n-    _eval_is_nonnegative = lambda s: _torf(i.is_nonnegative for i in s.args)\n-    _eval_is_nonpositive = lambda s: _torf(i.is_nonpositive for i in s.args)\n-    _eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args)\n-    _eval_is_odd = lambda s: _torf(i.is_odd for i in s.args)\n-    _eval_is_polar = lambda s: _torf(i.is_polar for i in s.args)\n-    _eval_is_positive = lambda s: _torf(i.is_positive for i in s.args)\n-    _eval_is_prime = lambda s: _torf(i.is_prime for i in s.args)\n-    _eval_is_rational = lambda s: _torf(i.is_rational for i in s.args)\n-    _eval_is_real = lambda s: _torf(i.is_real for i in s.args)\n-    _eval_is_transcendental = lambda s: _torf(i.is_transcendental for i in s.args)\n-    _eval_is_zero = lambda s: _torf(i.is_zero for i in s.args)\n-\n-class Max(MinMaxBase, Application):\n-    \"\"\"\n-    Return, if possible, the maximum value of the list.\n-\n-    When number of arguments is equal one, then\n-    return this argument.\n-\n-    When number of arguments is equal two, then\n-    return, if possible, the value from (a, b) that is >= the other.\n-\n-    In common case, when the length of list greater than 2, the task\n-    is more complicated. Return only the arguments, which are greater\n-    than others, if it is possible to determine directional relation.\n-\n-    If is not possible to determine such a relation, return a partially\n-    evaluated result.\n-\n-    Assumptions are used to make the decision too.\n-\n-    Also, only comparable arguments are permitted.\n-\n-    It is named ``Max`` and not ``max`` to avoid conflicts\n-    with the built-in function ``max``.\n-\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import Max, Symbol, oo\n-    >>> from sympy.abc import x, y\n-    >>> p = Symbol('p', positive=True)\n-    >>> n = Symbol('n', negative=True)\n-\n-    >>> Max(x, -2)                  #doctest: +SKIP\n-    Max(x, -2)\n-    >>> Max(x, -2).subs(x, 3)\n-    3\n-    >>> Max(p, -2)\n-    p\n-    >>> Max(x, y)\n-    Max(x, y)\n-    >>> Max(x, y) == Max(y, x)\n-    True\n-    >>> Max(x, Max(y, z))           #doctest: +SKIP\n-    Max(x, y, z)\n-    >>> Max(n, 8, p, 7, -oo)        #doctest: +SKIP\n-    Max(8, p)\n-    >>> Max (1, x, oo)\n-    oo\n-\n-    * Algorithm\n-\n-    The task can be considered as searching of supremums in the\n-    directed complete partial orders [1]_.\n-\n-    The source values are sequentially allocated by the isolated subsets\n-    in which supremums are searched and result as Max arguments.\n-\n-    If the resulted supremum is single, then it is returned.\n-\n-    The isolated subsets are the sets of values which are only the comparable\n-    with each other in the current set. E.g. natural numbers are comparable with\n-    each other, but not comparable with the `x` symbol. Another example: the\n-    symbol `x` with negative assumption is comparable with a natural number.\n-\n-    Also there are \"least\" elements, which are comparable with all others,\n-    and have a zero property (maximum or minimum for all elements). E.g. `oo`.\n-    In case of it the allocation operation is terminated and only this value is\n-    returned.\n-\n-    Assumption:\n-       - if A > B > C then A > C\n-       - if A == B then B can be removed\n-\n-    References\n-    ==========\n-\n-    .. [1] https://en.wikipedia.org/wiki/Directed_complete_partial_order\n-    .. [2] https://en.wikipedia.org/wiki/Lattice_%28order%29\n-\n-    See Also\n-    ========\n-\n-    Min : find minimum values\n-    \"\"\"\n-    zero = S.Infinity\n-    identity = S.NegativeInfinity\n-\n-    def fdiff( self, argindex ):\n-        from sympy import Heaviside\n-        n = len(self.args)\n-        if 0 < argindex and argindex <= n:\n-            argindex -= 1\n-            if n == 2:\n-                return Heaviside(self.args[argindex] - self.args[1 - argindex])\n-            newargs = tuple([self.args[i] for i in range(n) if i != argindex])\n-            return Heaviside(self.args[argindex] - Max(*newargs))\n-        else:\n-            raise ArgumentIndexError(self, argindex)\n-\n-    def _eval_rewrite_as_Heaviside(self, *args, **kwargs):\n-        from sympy import Heaviside\n-        return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \\\n-                for j in args])\n-\n-    def _eval_rewrite_as_Piecewise(self, *args, **kwargs):\n-        is_real = all(i.is_real for i in args)\n-        if is_real:\n-            return _minmax_as_Piecewise('>=', *args)\n-\n-    def _eval_is_positive(self):\n-        return fuzzy_or(a.is_positive for a in self.args)\n-\n-    def _eval_is_nonnegative(self):\n-        return fuzzy_or(a.is_nonnegative for a in self.args)\n-\n-    def _eval_is_negative(self):\n-        return fuzzy_and(a.is_negative for a in self.args)\n-\n-\n-class Min(MinMaxBase, Application):\n-    \"\"\"\n-    Return, if possible, the minimum value of the list.\n-    It is named ``Min`` and not ``min`` to avoid conflicts\n-    with the built-in function ``min``.\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import Min, Symbol, oo\n-    >>> from sympy.abc import x, y\n-    >>> p = Symbol('p', positive=True)\n-    >>> n = Symbol('n', negative=True)\n-\n-    >>> Min(x, -2)                  #doctest: +SKIP\n-    Min(x, -2)\n-    >>> Min(x, -2).subs(x, 3)\n-    -2\n-    >>> Min(p, -3)\n-    -3\n-    >>> Min(x, y)                   #doctest: +SKIP\n-    Min(x, y)\n-    >>> Min(n, 8, p, -7, p, oo)     #doctest: +SKIP\n-    Min(n, -7)\n-\n-    See Also\n-    ========\n-\n-    Max : find maximum values\n-    \"\"\"\n-    zero = S.NegativeInfinity\n-    identity = S.Infinity\n-\n-    def fdiff( self, argindex ):\n-        from sympy import Heaviside\n-        n = len(self.args)\n-        if 0 < argindex and argindex <= n:\n-            argindex -= 1\n-            if n == 2:\n-                return Heaviside( self.args[1-argindex] - self.args[argindex] )\n-            newargs = tuple([ self.args[i] for i in range(n) if i != argindex])\n-            return Heaviside( Min(*newargs) - self.args[argindex] )\n-        else:\n-            raise ArgumentIndexError(self, argindex)\n-\n-    def _eval_rewrite_as_Heaviside(self, *args, **kwargs):\n-        from sympy import Heaviside\n-        return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \\\n-                for j in args])\n-\n-    def _eval_rewrite_as_Piecewise(self, *args, **kwargs):\n-        is_real = all(i.is_real for i in args)\n-        if is_real:\n-            return _minmax_as_Piecewise('<=', *args)\n-\n-    def _eval_is_positive(self):\n-        return fuzzy_and(a.is_positive for a in self.args)\n-\n-    def _eval_is_nonnegative(self):\n-        return fuzzy_and(a.is_nonnegative for a in self.args)\n-\n-    def _eval_is_negative(self):\n-        return fuzzy_or(a.is_negative for a in self.args)\n", "model": "claude-sonnet-5-5", "steps": 26, "finished": false, "patch_lines": 832, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 832, "steps": 26}], "ms": 193810}
