{
    "file_diffs": [
        {
            "old_file_content": "import inspect\nimport itertools\nfrom collections.abc import Iterable\nimport re\nimport warnings\nfrom typing import Callable, Dict\n\nimport numpy as np\nimport scipy\n\nfrom Orange.data import Table, Storage, Instance, Value\nfrom Orange.data.filter import HasClass\nfrom Orange.data.table import DomainTransformationError\nfrom Orange.data.util import one_hot\nfrom Orange.misc.environ import cache_dir\nfrom Orange.misc.wrapper_meta import WrapperMeta\nfrom Orange.preprocess import Continuize, RemoveNaNColumns, SklImpute, Normalize\nfrom Orange.statistics.util import all_nan\nfrom Orange.util import Reprable, OrangeDeprecationWarning, wrap_callback, \\\n    dummy_callback\n\n__all__ = [\"Learner\", \"Model\", \"SklLearner\", \"SklModel\",\n           \"ReprableWithPreprocessors\"]\n\n\nclass ReprableWithPreprocessors(Reprable):\n    def _reprable_omit_param(self, name, default, value):\n        if name == \"preprocessors\":\n            default_cls = type(self).preprocessors\n            if value is default or value is default_cls:\n                return True\n            else:\n                try:\n                    return all(p1 is p2 for p1, p2 in\n                               itertools.zip_longest(value, default_cls))\n                except (ValueError, TypeError):\n                    return False\n        else:\n            return super()._reprable_omit_param(name, default, value)\n\n\nclass Learner(ReprableWithPreprocessors):\n    \"\"\"The base learner class.\n\n    Preprocessors can behave in a number of different ways, all of which are\n    described here.\n    If the user does not pass a preprocessor argument into the Learner\n    constructor, the default learner preprocessors are used. We assume the user\n    would simply like to get things done without having to worry about\n    preprocessors.\n    If the user chooses to pass in their own preprocessors, we assume they know\n    what they are doing. In this case, only the user preprocessors are used and\n    the default preprocessors are ignored.\n    In case the user would like to use the default preprocessors as well as\n    their own ones, the `use_default_preprocessors` flag should be set.\n\n    Parameters\n    ----------\n    preprocessors : Preprocessor or tuple[Preprocessor], optional\n        User defined preprocessors. If the user specifies their own\n        preprocessors, the default ones will not be used, unless the\n        `use_default_preprocessors` flag is set.\n\n    Attributes\n    ----------\n    preprocessors : tuple[Preprocessor] (default None)\n        The used defined preprocessors that will be used on any data.\n    use_default_preprocessors : bool (default False)\n        This flag indicates whether to use the default preprocessors that are\n        defined on the Learner class. Since preprocessors can be applied in a\n        number of ways\n    active_preprocessors : tuple[Preprocessor]\n        The processors that will be used when data is passed to the learner.\n        This depends on whether the user has passed in their own preprocessors\n        and whether the `use_default_preprocessors` flag is set.\n\n        This property is needed mainly because of the `Fitter` class, which can\n        not know in advance, which preprocessors it will need to use. Therefore\n        this resolves the active preprocessors using a lazy approach.\n    params : dict\n        The params that the learner is constructed with.\n\n    \"\"\"\n    supports_multiclass = False\n    supports_weights = False\n    #: A sequence of data preprocessors to apply on data prior to\n    #: fitting the model\n    preprocessors = ()\n    learner_adequacy_err_msg = ''\n\n    def __init__(self, preprocessors=None):\n        self.use_default_preprocessors = False\n        if isinstance(preprocessors, Iterable):\n            self.preprocessors = tuple(preprocessors)\n        elif preprocessors:\n            self.preprocessors = (preprocessors,)\n\n    def fit(self, X, Y, W=None):\n        raise RuntimeError(\n            \"Descendants of Learner must overload method fit or fit_storage\")\n\n    def fit_storage(self, data):\n        \"\"\"Default implementation of fit_storage defaults to calling fit.\n        Derived classes must define fit_storage or fit\"\"\"\n        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n        return self.fit(X, Y, W)\n\n    def __call__(self, data, progress_callback=None):\n        if not self.check_learner_adequacy(data.domain):\n            raise ValueError(self.learner_adequacy_err_msg)\n\n        origdomain = data.domain\n\n        if isinstance(data, Instance):\n            data = Table(data.domain, [data])\n        origdata = data\n\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        progress_callback(0, \"Preprocessing...\")\n        try:\n            cb = wrap_callback(progress_callback, end=0.1)\n            data = self.preprocess(data, progress_callback=cb)\n        except TypeError:\n            data = self.preprocess(data)\n            warnings.warn(\"A keyword argument 'progress_callback' has been \"\n                          \"added to the preprocess() signature. Implementing \"\n                          \"the method without the argument is deprecated and \"\n                          \"will result in an error in the future.\",\n                          OrangeDeprecationWarning)\n\n        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:\n            raise TypeError(\"%s doesn't support multiple class variables\" %\n                            self.__class__.__name__)\n\n        progress_callback(0.1, \"Fitting...\")\n        model = self._fit_model(data)\n        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]\n        model.domain = data.domain\n        model.supports_multiclass = self.supports_multiclass\n        model.name = self.name\n        model.original_domain = origdomain\n        model.original_data = origdata\n        progress_callback(1)\n        return model\n\n    def _fit_model(self, data):\n        if type(self).fit is Learner.fit:\n            return self.fit_storage(data)\n        else:\n            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n            return self.fit(X, Y, W)\n\n    def preprocess(self, data, progress_callback=None):\n        \"\"\"Apply the `preprocessors` to the data\"\"\"\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        n_pps = len(list(self.active_preprocessors))\n        for i, pp in enumerate(self.active_preprocessors):\n            progress_callback(i / n_pps)\n            data = pp(data)\n        progress_callback(1)\n        return data\n\n    @property\n    def active_preprocessors(self):\n        yield from self.preprocessors\n        if (self.use_default_preprocessors and\n                self.preprocessors is not type(self).preprocessors):\n            yield from type(self).preprocessors\n\n    def check_learner_adequacy(self, _):\n        return True\n\n    @property\n    def name(self):\n        \"\"\"Return a short name derived from Learner type name\"\"\"\n        try:\n            return self.__name\n        except AttributeError:\n            name = self.__class__.__name__\n            if name.endswith('Learner'):\n                name = name[:-len('Learner')]\n            if name.endswith('Fitter'):\n                name = name[:-len('Fitter')]\n            if isinstance(self, SklLearner) and name.startswith('Skl'):\n                name = name[len('Skl'):]\n            name = name or 'learner'\n            # From http://stackoverflow.com/a/1176023/1090455 <3\n            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\\1 \\2',\n                               re.sub(r'(.)([A-Z][a-z]+)', r'\\1 \\2', name)).lower()\n            return self.name\n\n    @name.setter\n    def name(self, value):\n        self.__name = value\n\n    def __str__(self):\n        return self.name\n\n\nclass Model(Reprable):\n    supports_multiclass = False\n    supports_weights = False\n    Value = 0\n    Probs = 1\n    ValueProbs = 2\n\n    def __init__(self, domain=None, original_domain=None):\n        self.domain = domain\n        if original_domain is not None:\n            self.original_domain = original_domain\n        else:\n            self.original_domain = domain\n        self.used_vals = None\n\n    def predict(self, X):\n        if type(self).predict_storage is Model.predict_storage:\n            raise TypeError(\"Descendants of Model must overload method predict\")\n        else:\n            Y = np.zeros((len(X), len(self.domain.class_vars)))\n            Y[:] = np.nan\n            table = Table(self.domain, X, Y)\n            return self.predict_storage(table)\n\n    def predict_storage(self, data):\n        if isinstance(data, Storage):\n            return self.predict(data.X)\n        elif isinstance(data, Instance):\n            return self.predict(np.atleast_2d(data.x))\n        raise TypeError(\"Unrecognized argument (instance of '{}')\"\n                        .format(type(data).__name__))\n\n    def get_backmappers(self, data):\n        backmappers = []\n        n_values = []\n\n        dataclasses = data.domain.class_vars\n        modelclasses = self.domain.class_vars\n        if not (modelclasses and dataclasses):\n            return None, []  # classless model or data; don't touch\n        if len(dataclasses) != len(modelclasses):\n            raise DomainTransformationError(\n                \"Mismatching number of model's classes and data classes\")\n        for dataclass, modelclass in zip(dataclasses, modelclasses):\n            if dataclass != modelclass:\n                if dataclass.name != modelclass.name:\n                    raise DomainTransformationError(\n                        f\"Model for '{modelclass.name}' \"\n                        f\"cannot predict '{dataclass.name}'\")\n                else:\n                    raise DomainTransformationError(\n                        f\"Variables '{modelclass.name}' in the model is \"\n                        \"incompatible with the variable of the same name \"\n                        \"in the data.\")\n            n_values.append(dataclass.is_discrete and len(dataclass.values))\n            if dataclass is not modelclass and dataclass.is_discrete:\n                backmappers.append(dataclass.get_mapper_from(modelclass))\n            else:\n                backmappers.append(None)\n        if all(x is None for x in backmappers):\n            backmappers = None\n        return backmappers, n_values\n\n    def backmap_value(self, value, mapped_probs, n_values, backmappers):\n        if backmappers is None:\n            return value\n\n        if value.ndim == 2:  # For multitarget, recursive call by columns\n            new_value = np.zeros(value.shape)\n            for i, n_value, backmapper in zip(\n                    itertools.count(), n_values, backmappers):\n                new_value[:, i] = self.backmap_value(\n                    value[:, i], mapped_probs[:, i, :], [n_value], [backmapper])\n            return new_value\n\n        backmapper = backmappers[0]\n        if backmapper is None:\n            return value\n\n        value = backmapper(value)\n        nans = np.isnan(value)\n        if not np.any(nans) or n_values[0] < 2:\n            return value\n        if mapped_probs is not None:\n            value[nans] = np.argmax(mapped_probs[nans], axis=1)\n        else:\n            value[nans] = np.random.RandomState(0).choice(\n                backmapper(np.arange(0, n_values[0] - 1)),\n                (np.sum(nans), ))\n        return value\n\n    def backmap_probs(self, probs, n_values, backmappers):\n        if backmappers is None:\n            return probs\n\n        if probs.ndim == 3:\n            new_probs = np.zeros((len(probs), len(n_values), max(n_values)),\n                                 dtype=probs.dtype)\n            for i, n_value, backmapper in zip(\n                    itertools.count(), n_values, backmappers):\n                new_probs[:, i, :n_value] = self.backmap_probs(\n                    probs[:, i, :], [n_value], [backmapper])\n            return new_probs\n\n        backmapper = backmappers[0]\n        if backmapper is None:\n            return probs\n        n_value = n_values[0]\n        new_probs = np.zeros((len(probs), n_value), dtype=probs.dtype)\n        for col in range(probs.shape[1]):\n            target = backmapper(col)\n            if not np.isnan(target):\n                new_probs[:, int(target)] = probs[:, col]\n        tots = np.sum(new_probs, axis=1)\n        zero_sum = tots == 0\n        new_probs[zero_sum] = 1\n        tots[zero_sum] = n_value\n        new_probs = new_probs / tots[:, None]\n        return new_probs\n\n    def data_to_model_domain(\n            self, data: Table, progress_callback: Callable = dummy_callback\n    ) -> Table:\n        \"\"\"\n        Transforms data to the model domain if possible.\n\n        Parameters\n        ----------\n        data\n            Data to be transformed to the model domain\n        progress_callback\n            Callback - callable - to report the progress\n\n        Returns\n        -------\n        Transformed data table\n\n        Raises\n        ------\n        DomainTransformationError\n            Error indicates that transformation is not possible since domains\n            are not compatible\n        \"\"\"\n        if data.domain == self.domain:\n            return data\n\n        progress_callback(0)\n        if self.original_domain.attributes != data.domain.attributes \\\n                and data.X.size \\\n                and not all_nan(data.X):\n            progress_callback(0.5)\n            new_data = data.transform(self.original_domain)\n            if all_nan(new_data.X):\n                raise DomainTransformationError(\n                    \"domain transformation produced no defined values\")\n            progress_callback(0.75)\n            data = new_data.transform(self.domain)\n            progress_callback(1)\n            return data\n\n        progress_callback(0.5)\n        data = data.transform(self.domain)\n        progress_callback(1)\n        return data\n\n    def __call__(self, data, ret=Value):\n        multitarget = len(self.domain.class_vars) > 1\n\n        def one_hot_probs(value):\n            if not multitarget:\n                return one_hot(\n                    value,\n                    dim=len(self.domain.class_var.values)\n                    if self.domain is not None else None\n                )\n\n            max_card = max(len(c.values) for c in self.domain.class_vars)\n            probs = np.zeros(value.shape + (max_card,), float)\n            for i in range(len(self.domain.class_vars)):\n                probs[:, i, :] = one_hot(value[:, i])\n            return probs\n\n        def extend_probabilities(probs):\n            \"\"\"\n            Since SklModels and models implementing `fit` and not `fit_storage`\n            do not guarantee correct prediction dimensionality, extend\n            dimensionality of probabilities when it does not match the number\n            of values in the domain.\n            \"\"\"\n            class_vars = self.domain.class_vars\n            max_values = max(len(cv.values) for cv in class_vars)\n            if max_values == probs.shape[-1]:\n                return probs\n\n            if not self.supports_multiclass:\n                probs = probs[:, np.newaxis, :]\n\n            probs_ext = np.zeros((len(probs), len(class_vars), max_values))\n            for c, used_vals in enumerate(self.used_vals):\n                for i, cv in enumerate(used_vals):\n                    probs_ext[:, c, cv] = probs[:, c, i]\n\n            if not self.supports_multiclass:\n                probs_ext = probs_ext[:, 0, :]\n            return probs_ext\n\n        def fix_dim(x):\n            return x[0] if one_d else x\n\n        if not 0 <= ret <= 2:\n            raise ValueError(\"invalid value of argument 'ret'\")\n        if ret > 0 and any(v.is_continuous for v in self.domain.class_vars):\n            raise ValueError(\"cannot predict continuous distributions\")\n\n        # Convert 1d structures to 2d and remember doing it\n        one_d = True\n        if isinstance(data, Instance):\n            data = Table.from_list(data.domain, [data])\n        elif isinstance(data, (list, tuple)) \\\n                and not isinstance(data[0], (list, tuple)):\n            data = [data]\n        elif isinstance(data, np.ndarray) and data.ndim == 1:\n            data = np.atleast_2d(data)\n        else:\n            one_d = False\n\n        # if sparse convert to csr_matrix\n        if scipy.sparse.issparse(data):\n            data = data.tocsr()\n\n        # Call the predictor\n        backmappers = None\n        n_values = []\n        if isinstance(data, (np.ndarray, scipy.sparse.csr.csr_matrix)):\n            prediction = self.predict(data)\n        elif isinstance(data, Table):\n            backmappers, n_values = self.get_backmappers(data)\n            data = self.data_to_model_domain(data)\n            prediction = self.predict_storage(data)\n        elif isinstance(data, (list, tuple)):\n            data = Table.from_list(self.original_domain, data)\n            data = data.transform(self.domain)\n            prediction = self.predict_storage(data)\n        else:\n            raise TypeError(\"Unrecognized argument (instance of '{}')\"\n                            .format(type(data).__name__))\n\n        # Parse the result into value and probs\n        if isinstance(prediction, tuple):\n            value, probs = prediction\n        elif prediction.ndim == 1 + multitarget:\n            value, probs = prediction, None\n        elif prediction.ndim == 2 + multitarget:\n            value, probs = None, prediction\n        else:\n            raise TypeError(\"model returned a %i-dimensional array\",\n                            prediction.ndim)\n\n        # Ensure that we have what we need to return; backmapp everything\n        if probs is None and (ret != Model.Value or backmappers is not None):\n            probs = one_hot_probs(value)\n        if probs is not None:\n            probs = extend_probabilities(probs)\n            probs = self.backmap_probs(probs, n_values, backmappers)\n        if ret != Model.Probs:\n            if value is None:\n                value = np.argmax(probs, axis=-1)\n                # probs are already backmapped\n            else:\n                value = self.backmap_value(value, probs, n_values, backmappers)\n\n        # Return what we need to\n        if ret == Model.Probs:\n            return fix_dim(probs)\n        if isinstance(data, Instance) and not multitarget:\n            value = [Value(self.domain.class_var, value[0])]\n        if ret == Model.Value:\n            return fix_dim(value)\n        else:  # ret == Model.ValueProbs\n            return fix_dim(value), fix_dim(probs)\n\n    def __getstate__(self):\n        \"\"\"Skip (possibly large) data when pickling models\"\"\"\n        state = self.__dict__\n        if 'original_data' in state:\n            state = state.copy()\n            state['original_data'] = None\n        return state\n\n\nclass SklModel(Model, metaclass=WrapperMeta):\n    used_vals = None\n\n    def __init__(self, skl_model):\n        self.skl_model = skl_model\n\n    def predict(self, X):\n        value = self.skl_model.predict(X)\n        # SVM has probability attribute which defines if method compute probs\n        has_prob_attr = hasattr(self.skl_model, \"probability\")\n        if (has_prob_attr and self.skl_model.probability\n                or not has_prob_attr\n                and hasattr(self.skl_model, \"predict_proba\")):\n            probs = self.skl_model.predict_proba(X)\n            return value, probs\n        return value\n\n    def __repr__(self):\n        # Params represented as a comment because not passed into constructor\n        return super().__repr__() + '  # params=' + repr(self.params)\n\n\nclass SklLearner(Learner, metaclass=WrapperMeta):\n    \"\"\"\n    ${skldoc}\n    Additional Orange parameters\n\n    preprocessors : list, optional\n        An ordered list of preprocessors applied to data before\n        training or testing.\n        Defaults to\n        `[RemoveNaNClasses(), Continuize(), SklImpute(), RemoveNaNColumns()]`\n    \"\"\"\n    __wraps__ = None\n    __returns__ = SklModel\n    _params = {}\n\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        Continuize(),\n        RemoveNaNColumns(),\n        SklImpute()]\n\n    @property\n    def params(self):\n        return self._params\n\n    @params.setter\n    def params(self, value):\n        self._params = self._get_sklparams(value)\n\n    def _get_sklparams(self, values):\n        skllearner = self.__wraps__\n        if skllearner is not None:\n            spec = list(\n                inspect.signature(skllearner.__init__).parameters.keys()\n            )\n            # first argument is 'self'\n            assert spec[0] == \"self\"\n            params = {\n                name: values[name] for name in spec[1:] if name in values\n            }\n        else:\n            raise TypeError(\"Wrapper does not define '__wraps__'\")\n        return params\n\n    def preprocess(self, data, progress_callback=None):\n        data = super().preprocess(data, progress_callback)\n\n        if any(v.is_discrete and len(v.values) > 2\n               for v in data.domain.attributes):\n            raise ValueError(\"Wrapped scikit-learn methods do not support \" +\n                             \"multinomial variables.\")\n\n        return data\n\n    def __call__(self, data, progress_callback=None):\n        m = super().__call__(data, progress_callback)\n        m.params = self.params\n        return m\n\n    def _initialize_wrapped(self):\n        # pylint: disable=not-callable\n        return self.__wraps__(**self.params)\n\n    def fit(self, X, Y, W=None):\n        clf = self._initialize_wrapped()\n        Y = Y.reshape(-1)\n        if W is None or not self.supports_weights:\n            return self.__returns__(clf.fit(X, Y))\n        return self.__returns__(clf.fit(X, Y, sample_weight=W.reshape(-1)))\n\n    @property\n    def supports_weights(self):\n        \"\"\"Indicates whether this learner supports weighted instances.\n        \"\"\"\n        return 'sample_weight' in self.__wraps__.fit.__code__.co_varnames\n\n    def __getattr__(self, item):\n        try:\n            return self.params[item]\n        except (KeyError, AttributeError):\n            raise AttributeError(item) from None\n\n    # TODO: Disallow (or mirror) __setattr__ for keys in params?\n\n    def __dir__(self):\n        dd = super().__dir__()\n        return list(sorted(set(dd) | set(self.params.keys())))\n\n\nclass TreeModel(Model):\n    pass\n\n\nclass RandomForestModel(Model):\n    \"\"\"Interface for random forest models\n    \"\"\"\n\n    @property\n    def trees(self):\n        \"\"\"Return a list of Trees in the forest\n\n        Returns\n        -------\n        List[Tree]\n        \"\"\"\n\n\nclass KNNBase:\n    \"\"\"Base class for KNN (classification and regression) learners\n    \"\"\"\n\n    # pylint: disable=unused-argument\n    def __init__(self, n_neighbors=5, metric=\"euclidean\", weights=\"uniform\",\n                 algorithm='auto', metric_params=None,\n                 preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n    def fit(self, X, Y, W=None):\n        if self.params[\"metric_params\"] is None and \\\n                        self.params.get(\"metric\") == \"mahalanobis\":\n            self.params[\"metric_params\"] = {\"V\": np.cov(X.T)}\n        return super().fit(X, Y, W)\n\n\nclass NNBase:\n    \"\"\"Base class for neural network (classification and regression) learners\n    \"\"\"\n    preprocessors = SklLearner.preprocessors + [Normalize()]\n\n    # pylint: disable=unused-argument,too-many-arguments\n    def __init__(self, hidden_layer_sizes=(100,), activation='relu',\n                 solver='adam', alpha=0.0001, batch_size='auto',\n                 learning_rate='constant', learning_rate_init=0.001,\n                 power_t=0.5, max_iter=200, shuffle=True, random_state=None,\n                 tol=0.0001, verbose=False, warm_start=False, momentum=0.9,\n                 nesterovs_momentum=True, early_stopping=False,\n                 validation_fraction=0.1, beta_1=0.9, beta_2=0.999,\n                 epsilon=1e-08, preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n\nclass CatGBModel(Model, metaclass=WrapperMeta):\n    def __init__(self, cat_model, cat_features, domain):\n        super().__init__(domain)\n        self.cat_model = cat_model\n        self.cat_features = cat_features\n\n    def predict(self, X):\n        if self.cat_features:\n            X = X.astype(str)\n        value = self.cat_model.predict(X).flatten()\n        if hasattr(self.cat_model, \"predict_proba\"):\n            probs = self.cat_model.predict_proba(X)\n            return value, probs\n        return value\n\n    def __repr__(self):\n        # Params represented as a comment because not passed into constructor\n        return super().__repr__() + '  # params=' + repr(self.params)\n\n\nclass CatGBBaseLearner(Learner, metaclass=WrapperMeta):\n    \"\"\"\n    ${skldoc}\n    Additional Orange parameters\n\n    preprocessors : list, optional\n        An ordered list of preprocessors applied to data before\n        training or testing.\n        Defaults to\n        `[RemoveNaNClasses(), RemoveNaNColumns()]`\n    \"\"\"\n    supports_weights = True\n    __wraps__ = None\n    __returns__ = CatGBModel\n    _params = {}\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        RemoveNaNColumns(),\n    ]\n\n    # pylint: disable=unused-argument,too-many-arguments,too-many-locals\n    def __init__(self,\n                 iterations=None,\n                 learning_rate=None,\n                 depth=None,\n                 l2_leaf_reg=None,\n                 model_size_reg=None,\n                 rsm=None,\n                 loss_function=None,\n                 border_count=None,\n                 feature_border_type=None,\n                 per_float_feature_quantization=None,\n                 input_borders=None,\n                 output_borders=None,\n                 fold_permutation_block=None,\n                 od_pval=None,\n                 od_wait=None,\n                 od_type=None,\n                 nan_mode=None,\n                 counter_calc_method=None,\n                 leaf_estimation_iterations=None,\n                 leaf_estimation_method=None,\n                 thread_count=None,\n                 random_seed=None,\n                 use_best_model=None,\n                 verbose=False,\n                 logging_level=None,\n                 metric_period=None,\n                 ctr_leaf_count_limit=None,\n                 store_all_simple_ctr=None,\n                 max_ctr_complexity=None,\n                 has_time=None,\n                 allow_const_label=None,\n                 classes_count=None,\n                 class_weights=None,\n                 one_hot_max_size=None,\n                 random_strength=None,\n                 name=None,\n                 ignored_features=None,\n                 train_dir=cache_dir(),\n                 custom_loss=None,\n                 custom_metric=None,\n                 eval_metric=None,\n                 bagging_temperature=None,\n                 save_snapshot=None,\n                 snapshot_file=None,\n                 snapshot_interval=None,\n                 fold_len_multiplier=None,\n                 used_ram_limit=None,\n                 gpu_ram_part=None,\n                 allow_writing_files=False,\n                 final_ctr_computation_mode=None,\n                 approx_on_full_history=None,\n                 boosting_type=None,\n                 simple_ctr=None,\n                 combinations_ctr=None,\n                 per_feature_ctr=None,\n                 task_type=None,\n                 device_config=None,\n                 devices=None,\n                 bootstrap_type=None,\n                 subsample=None,\n                 sampling_unit=None,\n                 dev_score_calc_obj_block_size=None,\n                 max_depth=None,\n                 n_estimators=None,\n                 num_boost_round=None,\n                 num_trees=None,\n                 colsample_bylevel=None,\n                 random_state=None,\n                 reg_lambda=None,\n                 objective=None,\n                 eta=None,\n                 max_bin=None,\n                 scale_pos_weight=None,\n                 gpu_cat_features_storage=None,\n                 data_partition=None,\n                 metadata=None,\n                 early_stopping_rounds=None,\n                 cat_features=None,\n                 grow_policy=None,\n                 min_data_in_leaf=None,\n                 min_child_samples=None,\n                 max_leaves=None,\n                 num_leaves=None,\n                 score_function=None,\n                 leaf_estimation_backtracking=None,\n                 ctr_history_unit=None,\n                 monotone_constraints=None,\n                 feature_weights=None,\n                 penalties_coefficient=None,\n                 first_feature_use_penalties=None,\n                 model_shrink_rate=None,\n                 model_shrink_mode=None,\n                 langevin=None,\n                 diffusion_temperature=None,\n                 posterior_sampling=None,\n                 boost_from_average=None,\n                 text_features=None,\n                 tokenizers=None,\n                 dictionaries=None,\n                 feature_calcers=None,\n                 text_processing=None,\n                 preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n    @property\n    def params(self):\n        return self._params\n\n    @params.setter\n    def params(self, value):\n        self._params = self._get_wrapper_params(value)\n\n    def _get_wrapper_params(self, values):\n        spec = list(inspect.signature(\n            self.__wraps__.__init__).parameters.keys())\n        return {name: values[name] for name in spec[1:] if name in values}\n\n    def __call__(self, data, progress_callback=None):\n        m = super().__call__(data, progress_callback)\n        m.params = self.params\n        return m\n\n    def fit_storage(self, data: Table):\n        domain, X, Y, W = data.domain, data.X, data.Y.reshape(-1), None\n        if self.supports_weights and data.has_weights():\n            W = data.W.reshape(-1)\n        # pylint: disable=not-callable\n        clf = self.__wraps__(**self.params)\n        cat_features = [i for i, attr in enumerate(domain.attributes)\n                        if attr.is_discrete]\n        if cat_features:\n            X = X.astype(str)\n        cat_model = clf.fit(X, Y, cat_features=cat_features, sample_weight=W)\n        return self.__returns__(cat_model, cat_features, domain)\n\n    def __getattr__(self, item):\n        try:\n            return self.params[item]\n        except (KeyError, AttributeError):\n            raise AttributeError(item) from None\n\n    def __dir__(self):\n        dd = super().__dir__()\n        return list(sorted(set(dd) | set(self.params.keys())))\n\n\nclass XGBBase(SklLearner):\n    \"\"\"Base class for xgboost (classification and regression) learners \"\"\"\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        Continuize(),\n        RemoveNaNColumns(),\n    ]\n\n    def __init__(self, preprocessors=None, **kwargs):\n        super().__init__(preprocessors=preprocessors)\n        self.params = kwargs\n\n    @SklLearner.params.setter\n    def params(self, values: Dict):\n        self._params = values\n",
            "new_file_content": "import inspect\nimport itertools\nfrom collections.abc import Iterable\nimport re\nimport warnings\nfrom typing import Callable, Dict\n\nimport numpy as np\nimport scipy\n\nfrom Orange.data import Table, Storage, Instance, Value\nfrom Orange.data.filter import HasClass\nfrom Orange.data.table import DomainTransformationError\nfrom Orange.data.util import one_hot\nfrom Orange.misc.environ import cache_dir\nfrom Orange.misc.wrapper_meta import WrapperMeta\nfrom Orange.preprocess import Continuize, RemoveNaNColumns, SklImpute, Normalize\nfrom Orange.statistics.util import all_nan\nfrom Orange.util import Reprable, OrangeDeprecationWarning, wrap_callback, \\\n    dummy_callback\n\n__all__ = [\"Learner\", \"Model\", \"SklLearner\", \"SklModel\",\n           \"ReprableWithPreprocessors\"]\n\n\nclass ReprableWithPreprocessors(Reprable):\n    def _reprable_omit_param(self, name, default, value):\n        if name == \"preprocessors\":\n            default_cls = type(self).preprocessors\n            if value is default or value is default_cls:\n                return True\n            else:\n                try:\n                    return all(p1 is p2 for p1, p2 in\n                               itertools.zip_longest(value, default_cls))\n                except (ValueError, TypeError):\n                    return False\n        else:\n            return super()._reprable_omit_param(name, default, value)\n\n\nclass Learner(ReprableWithPreprocessors):\n    \"\"\"The base learner class.\n\n    Preprocessors can behave in a number of different ways, all of which are\n    described here.\n    If the user does not pass a preprocessor argument into the Learner\n    constructor, the default learner preprocessors are used. We assume the user\n    would simply like to get things done without having to worry about\n    preprocessors.\n    If the user chooses to pass in their own preprocessors, we assume they know\n    what they are doing. In this case, only the user preprocessors are used and\n    the default preprocessors are ignored.\n    In case the user would like to use the default preprocessors as well as\n    their own ones, the `use_default_preprocessors` flag should be set.\n\n    Parameters\n    ----------\n    preprocessors : Preprocessor or tuple[Preprocessor], optional\n        User defined preprocessors. If the user specifies their own\n        preprocessors, the default ones will not be used, unless the\n        `use_default_preprocessors` flag is set.\n\n    Attributes\n    ----------\n    preprocessors : tuple[Preprocessor] (default None)\n        The used defined preprocessors that will be used on any data.\n    use_default_preprocessors : bool (default False)\n        This flag indicates whether to use the default preprocessors that are\n        defined on the Learner class. Since preprocessors can be applied in a\n        number of ways\n    active_preprocessors : tuple[Preprocessor]\n        The processors that will be used when data is passed to the learner.\n        This depends on whether the user has passed in their own preprocessors\n        and whether the `use_default_preprocessors` flag is set.\n\n        This property is needed mainly because of the `Fitter` class, which can\n        not know in advance, which preprocessors it will need to use. Therefore\n        this resolves the active preprocessors using a lazy approach.\n    params : dict\n        The params that the learner is constructed with.\n\n    \"\"\"\n    supports_multiclass = False\n    supports_weights = False\n    #: A sequence of data preprocessors to apply on data prior to\n    #: fitting the model\n    preprocessors = ()\n    learner_adequacy_err_msg = ''\n\n    def __init__(self, preprocessors=None):\n        self.use_default_preprocessors = False\n        if isinstance(preprocessors, Iterable):\n            self.preprocessors = tuple(preprocessors)\n        elif preprocessors:\n            self.preprocessors = (preprocessors,)\n\n    def fit(self, X, Y, W=None):\n        raise RuntimeError(\n            \"Descendants of Learner must overload method fit or fit_storage\")\n\n    def fit_storage(self, data):\n        \"\"\"Default implementation of fit_storage defaults to calling fit.\n        Derived classes must define fit_storage or fit\"\"\"\n        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n        return self.fit(X, Y, W)\n\n    def __call__(self, data, progress_callback=None):\n        if not self.check_learner_adequacy(data.domain):\n            raise ValueError(self.learner_adequacy_err_msg)\n\n        origdomain = data.domain\n\n        if isinstance(data, Instance):\n            data = Table(data.domain, [data])\n        origdata = data\n\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        progress_callback(0, \"Preprocessing...\")\n        try:\n            cb = wrap_callback(progress_callback, end=0.1)\n            data = self.preprocess(data, progress_callback=cb)\n        except TypeError:\n            data = self.preprocess(data)\n            warnings.warn(\"A keyword argument 'progress_callback' has been \"\n                          \"added to the preprocess() signature. Implementing \"\n                          \"the method without the argument is deprecated and \"\n                          \"will result in an error in the future.\",\n                          OrangeDeprecationWarning)\n\n        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:\n            raise TypeError(\"%s doesn't support multiple class variables\" %\n                            self.__class__.__name__)\n\n        progress_callback(0.1, \"Fitting...\")\n        model = self._fit_model(data)\n        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]\n        if not hasattr(model, \"domain\") or model.domain is None:\n            # some models set domain themself and it should be respected\n            # e.g. calibration learners set the base_learner's domain which\n            # would be wrongly overwritten if we set it here for any model\n            model.domain = data.domain\n        model.supports_multiclass = self.supports_multiclass\n        model.name = self.name\n        model.original_domain = origdomain\n        model.original_data = origdata\n        progress_callback(1)\n        return model\n\n    def _fit_model(self, data):\n        if type(self).fit is Learner.fit:\n            return self.fit_storage(data)\n        else:\n            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n            return self.fit(X, Y, W)\n\n    def preprocess(self, data, progress_callback=None):\n        \"\"\"Apply the `preprocessors` to the data\"\"\"\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        n_pps = len(list(self.active_preprocessors))\n        for i, pp in enumerate(self.active_preprocessors):\n            progress_callback(i / n_pps)\n            data = pp(data)\n        progress_callback(1)\n        return data\n\n    @property\n    def active_preprocessors(self):\n        yield from self.preprocessors\n        if (self.use_default_preprocessors and\n                self.preprocessors is not type(self).preprocessors):\n            yield from type(self).preprocessors\n\n    def check_learner_adequacy(self, _):\n        return True\n\n    @property\n    def name(self):\n        \"\"\"Return a short name derived from Learner type name\"\"\"\n        try:\n            return self.__name\n        except AttributeError:\n            name = self.__class__.__name__\n            if name.endswith('Learner'):\n                name = name[:-len('Learner')]\n            if name.endswith('Fitter'):\n                name = name[:-len('Fitter')]\n            if isinstance(self, SklLearner) and name.startswith('Skl'):\n                name = name[len('Skl'):]\n            name = name or 'learner'\n            # From http://stackoverflow.com/a/1176023/1090455 <3\n            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\\1 \\2',\n                               re.sub(r'(.)([A-Z][a-z]+)', r'\\1 \\2', name)).lower()\n            return self.name\n\n    @name.setter\n    def name(self, value):\n        self.__name = value\n\n    def __str__(self):\n        return self.name\n\n\nclass Model(Reprable):\n    supports_multiclass = False\n    supports_weights = False\n    Value = 0\n    Probs = 1\n    ValueProbs = 2\n\n    def __init__(self, domain=None, original_domain=None):\n        self.domain = domain\n        if original_domain is not None:\n            self.original_domain = original_domain\n        else:\n            self.original_domain = domain\n        self.used_vals = None\n\n    def predict(self, X):\n        if type(self).predict_storage is Model.predict_storage:\n            raise TypeError(\"Descendants of Model must overload method predict\")\n        else:\n            Y = np.zeros((len(X), len(self.domain.class_vars)))\n            Y[:] = np.nan\n            table = Table(self.domain, X, Y)\n            return self.predict_storage(table)\n\n    def predict_storage(self, data):\n        if isinstance(data, Storage):\n            return self.predict(data.X)\n        elif isinstance(data, Instance):\n            return self.predict(np.atleast_2d(data.x))\n        raise TypeError(\"Unrecognized argument (instance of '{}')\"\n                        .format(type(data).__name__))\n\n    def get_backmappers(self, data):\n        backmappers = []\n        n_values = []\n\n        dataclasses = data.domain.class_vars\n        modelclasses = self.domain.class_vars\n        if not (modelclasses and dataclasses):\n            return None, []  # classless model or data; don't touch\n        if len(dataclasses) != len(modelclasses):\n            raise DomainTransformationError(\n                \"Mismatching number of model's classes and data classes\")\n        for dataclass, modelclass in zip(dataclasses, modelclasses):\n            if dataclass != modelclass:\n                if dataclass.name != modelclass.name:\n                    raise DomainTransformationError(\n                        f\"Model for '{modelclass.name}' \"\n                        f\"cannot predict '{dataclass.name}'\")\n                else:\n                    raise DomainTransformationError(\n                        f\"Variables '{modelclass.name}' in the model is \"\n                        \"incompatible with the variable of the same name \"\n                        \"in the data.\")\n            n_values.append(dataclass.is_discrete and len(dataclass.values))\n            if dataclass is not modelclass and dataclass.is_discrete:\n                backmappers.append(dataclass.get_mapper_from(modelclass))\n            else:\n                backmappers.append(None)\n        if all(x is None for x in backmappers):\n            backmappers = None\n        return backmappers, n_values\n\n    def backmap_value(self, value, mapped_probs, n_values, backmappers):\n        if backmappers is None:\n            return value\n\n        if value.ndim == 2:  # For multitarget, recursive call by columns\n            new_value = np.zeros(value.shape)\n            for i, n_value, backmapper in zip(\n                    itertools.count(), n_values, backmappers):\n                new_value[:, i] = self.backmap_value(\n                    value[:, i], mapped_probs[:, i, :], [n_value], [backmapper])\n            return new_value\n\n        backmapper = backmappers[0]\n        if backmapper is None:\n            return value\n\n        value = backmapper(value)\n        nans = np.isnan(value)\n        if not np.any(nans) or n_values[0] < 2:\n            return value\n        if mapped_probs is not None:\n            value[nans] = np.argmax(mapped_probs[nans], axis=1)\n        else:\n            value[nans] = np.random.RandomState(0).choice(\n                backmapper(np.arange(0, n_values[0] - 1)),\n                (np.sum(nans), ))\n        return value\n\n    def backmap_probs(self, probs, n_values, backmappers):\n        if backmappers is None:\n            return probs\n\n        if probs.ndim == 3:\n            new_probs = np.zeros((len(probs), len(n_values), max(n_values)),\n                                 dtype=probs.dtype)\n            for i, n_value, backmapper in zip(\n                    itertools.count(), n_values, backmappers):\n                new_probs[:, i, :n_value] = self.backmap_probs(\n                    probs[:, i, :], [n_value], [backmapper])\n            return new_probs\n\n        backmapper = backmappers[0]\n        if backmapper is None:\n            return probs\n        n_value = n_values[0]\n        new_probs = np.zeros((len(probs), n_value), dtype=probs.dtype)\n        for col in range(probs.shape[1]):\n            target = backmapper(col)\n            if not np.isnan(target):\n                new_probs[:, int(target)] = probs[:, col]\n        tots = np.sum(new_probs, axis=1)\n        zero_sum = tots == 0\n        new_probs[zero_sum] = 1\n        tots[zero_sum] = n_value\n        new_probs = new_probs / tots[:, None]\n        return new_probs\n\n    def data_to_model_domain(\n            self, data: Table, progress_callback: Callable = dummy_callback\n    ) -> Table:\n        \"\"\"\n        Transforms data to the model domain if possible.\n\n        Parameters\n        ----------\n        data\n            Data to be transformed to the model domain\n        progress_callback\n            Callback - callable - to report the progress\n\n        Returns\n        -------\n        Transformed data table\n\n        Raises\n        ------\n        DomainTransformationError\n            Error indicates that transformation is not possible since domains\n            are not compatible\n        \"\"\"\n        if data.domain == self.domain:\n            return data\n\n        progress_callback(0)\n        if self.original_domain.attributes != data.domain.attributes \\\n                and data.X.size \\\n                and not all_nan(data.X):\n            progress_callback(0.5)\n            new_data = data.transform(self.original_domain)\n            if all_nan(new_data.X):\n                raise DomainTransformationError(\n                    \"domain transformation produced no defined values\")\n            progress_callback(0.75)\n            data = new_data.transform(self.domain)\n            progress_callback(1)\n            return data\n\n        progress_callback(0.5)\n        data = data.transform(self.domain)\n        progress_callback(1)\n        return data\n\n    def __call__(self, data, ret=Value):\n        multitarget = len(self.domain.class_vars) > 1\n\n        def one_hot_probs(value):\n            if not multitarget:\n                return one_hot(\n                    value,\n                    dim=len(self.domain.class_var.values)\n                    if self.domain is not None else None\n                )\n\n            max_card = max(len(c.values) for c in self.domain.class_vars)\n            probs = np.zeros(value.shape + (max_card,), float)\n            for i in range(len(self.domain.class_vars)):\n                probs[:, i, :] = one_hot(value[:, i])\n            return probs\n\n        def extend_probabilities(probs):\n            \"\"\"\n            Since SklModels and models implementing `fit` and not `fit_storage`\n            do not guarantee correct prediction dimensionality, extend\n            dimensionality of probabilities when it does not match the number\n            of values in the domain.\n            \"\"\"\n            class_vars = self.domain.class_vars\n            max_values = max(len(cv.values) for cv in class_vars)\n            if max_values == probs.shape[-1]:\n                return probs\n\n            if not self.supports_multiclass:\n                probs = probs[:, np.newaxis, :]\n\n            probs_ext = np.zeros((len(probs), len(class_vars), max_values))\n            for c, used_vals in enumerate(self.used_vals):\n                for i, cv in enumerate(used_vals):\n                    probs_ext[:, c, cv] = probs[:, c, i]\n\n            if not self.supports_multiclass:\n                probs_ext = probs_ext[:, 0, :]\n            return probs_ext\n\n        def fix_dim(x):\n            return x[0] if one_d else x\n\n        if not 0 <= ret <= 2:\n            raise ValueError(\"invalid value of argument 'ret'\")\n        if ret > 0 and any(v.is_continuous for v in self.domain.class_vars):\n            raise ValueError(\"cannot predict continuous distributions\")\n\n        # Convert 1d structures to 2d and remember doing it\n        one_d = True\n        if isinstance(data, Instance):\n            data = Table.from_list(data.domain, [data])\n        elif isinstance(data, (list, tuple)) \\\n                and not isinstance(data[0], (list, tuple)):\n            data = [data]\n        elif isinstance(data, np.ndarray) and data.ndim == 1:\n            data = np.atleast_2d(data)\n        else:\n            one_d = False\n\n        # if sparse convert to csr_matrix\n        if scipy.sparse.issparse(data):\n            data = data.tocsr()\n\n        # Call the predictor\n        backmappers = None\n        n_values = []\n        if isinstance(data, (np.ndarray, scipy.sparse.csr.csr_matrix)):\n            prediction = self.predict(data)\n        elif isinstance(data, Table):\n            backmappers, n_values = self.get_backmappers(data)\n            data = self.data_to_model_domain(data)\n            prediction = self.predict_storage(data)\n        elif isinstance(data, (list, tuple)):\n            data = Table.from_list(self.original_domain, data)\n            data = data.transform(self.domain)\n            prediction = self.predict_storage(data)\n        else:\n            raise TypeError(\"Unrecognized argument (instance of '{}')\"\n                            .format(type(data).__name__))\n\n        # Parse the result into value and probs\n        if isinstance(prediction, tuple):\n            value, probs = prediction\n        elif prediction.ndim == 1 + multitarget:\n            value, probs = prediction, None\n        elif prediction.ndim == 2 + multitarget:\n            value, probs = None, prediction\n        else:\n            raise TypeError(\"model returned a %i-dimensional array\",\n                            prediction.ndim)\n\n        # Ensure that we have what we need to return; backmapp everything\n        if probs is None and (ret != Model.Value or backmappers is not None):\n            probs = one_hot_probs(value)\n        if probs is not None:\n            probs = extend_probabilities(probs)\n            probs = self.backmap_probs(probs, n_values, backmappers)\n        if ret != Model.Probs:\n            if value is None:\n                value = np.argmax(probs, axis=-1)\n                # probs are already backmapped\n            else:\n                value = self.backmap_value(value, probs, n_values, backmappers)\n\n        # Return what we need to\n        if ret == Model.Probs:\n            return fix_dim(probs)\n        if isinstance(data, Instance) and not multitarget:\n            value = [Value(self.domain.class_var, value[0])]\n        if ret == Model.Value:\n            return fix_dim(value)\n        else:  # ret == Model.ValueProbs\n            return fix_dim(value), fix_dim(probs)\n\n    def __getstate__(self):\n        \"\"\"Skip (possibly large) data when pickling models\"\"\"\n        state = self.__dict__\n        if 'original_data' in state:\n            state = state.copy()\n            state['original_data'] = None\n        return state\n\n\nclass SklModel(Model, metaclass=WrapperMeta):\n    used_vals = None\n\n    def __init__(self, skl_model):\n        self.skl_model = skl_model\n\n    def predict(self, X):\n        value = self.skl_model.predict(X)\n        # SVM has probability attribute which defines if method compute probs\n        has_prob_attr = hasattr(self.skl_model, \"probability\")\n        if (has_prob_attr and self.skl_model.probability\n                or not has_prob_attr\n                and hasattr(self.skl_model, \"predict_proba\")):\n            probs = self.skl_model.predict_proba(X)\n            return value, probs\n        return value\n\n    def __repr__(self):\n        # Params represented as a comment because not passed into constructor\n        return super().__repr__() + '  # params=' + repr(self.params)\n\n\nclass SklLearner(Learner, metaclass=WrapperMeta):\n    \"\"\"\n    ${skldoc}\n    Additional Orange parameters\n\n    preprocessors : list, optional\n        An ordered list of preprocessors applied to data before\n        training or testing.\n        Defaults to\n        `[RemoveNaNClasses(), Continuize(), SklImpute(), RemoveNaNColumns()]`\n    \"\"\"\n    __wraps__ = None\n    __returns__ = SklModel\n    _params = {}\n\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        Continuize(),\n        RemoveNaNColumns(),\n        SklImpute()]\n\n    @property\n    def params(self):\n        return self._params\n\n    @params.setter\n    def params(self, value):\n        self._params = self._get_sklparams(value)\n\n    def _get_sklparams(self, values):\n        skllearner = self.__wraps__\n        if skllearner is not None:\n            spec = list(\n                inspect.signature(skllearner.__init__).parameters.keys()\n            )\n            # first argument is 'self'\n            assert spec[0] == \"self\"\n            params = {\n                name: values[name] for name in spec[1:] if name in values\n            }\n        else:\n            raise TypeError(\"Wrapper does not define '__wraps__'\")\n        return params\n\n    def preprocess(self, data, progress_callback=None):\n        data = super().preprocess(data, progress_callback)\n\n        if any(v.is_discrete and len(v.values) > 2\n               for v in data.domain.attributes):\n            raise ValueError(\"Wrapped scikit-learn methods do not support \" +\n                             \"multinomial variables.\")\n\n        return data\n\n    def __call__(self, data, progress_callback=None):\n        m = super().__call__(data, progress_callback)\n        m.params = self.params\n        return m\n\n    def _initialize_wrapped(self):\n        # pylint: disable=not-callable\n        return self.__wraps__(**self.params)\n\n    def fit(self, X, Y, W=None):\n        clf = self._initialize_wrapped()\n        Y = Y.reshape(-1)\n        if W is None or not self.supports_weights:\n            return self.__returns__(clf.fit(X, Y))\n        return self.__returns__(clf.fit(X, Y, sample_weight=W.reshape(-1)))\n\n    @property\n    def supports_weights(self):\n        \"\"\"Indicates whether this learner supports weighted instances.\n        \"\"\"\n        return 'sample_weight' in self.__wraps__.fit.__code__.co_varnames\n\n    def __getattr__(self, item):\n        try:\n            return self.params[item]\n        except (KeyError, AttributeError):\n            raise AttributeError(item) from None\n\n    # TODO: Disallow (or mirror) __setattr__ for keys in params?\n\n    def __dir__(self):\n        dd = super().__dir__()\n        return list(sorted(set(dd) | set(self.params.keys())))\n\n\nclass TreeModel(Model):\n    pass\n\n\nclass RandomForestModel(Model):\n    \"\"\"Interface for random forest models\n    \"\"\"\n\n    @property\n    def trees(self):\n        \"\"\"Return a list of Trees in the forest\n\n        Returns\n        -------\n        List[Tree]\n        \"\"\"\n\n\nclass KNNBase:\n    \"\"\"Base class for KNN (classification and regression) learners\n    \"\"\"\n\n    # pylint: disable=unused-argument\n    def __init__(self, n_neighbors=5, metric=\"euclidean\", weights=\"uniform\",\n                 algorithm='auto', metric_params=None,\n                 preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n    def fit(self, X, Y, W=None):\n        if self.params[\"metric_params\"] is None and \\\n                        self.params.get(\"metric\") == \"mahalanobis\":\n            self.params[\"metric_params\"] = {\"V\": np.cov(X.T)}\n        return super().fit(X, Y, W)\n\n\nclass NNBase:\n    \"\"\"Base class for neural network (classification and regression) learners\n    \"\"\"\n    preprocessors = SklLearner.preprocessors + [Normalize()]\n\n    # pylint: disable=unused-argument,too-many-arguments\n    def __init__(self, hidden_layer_sizes=(100,), activation='relu',\n                 solver='adam', alpha=0.0001, batch_size='auto',\n                 learning_rate='constant', learning_rate_init=0.001,\n                 power_t=0.5, max_iter=200, shuffle=True, random_state=None,\n                 tol=0.0001, verbose=False, warm_start=False, momentum=0.9,\n                 nesterovs_momentum=True, early_stopping=False,\n                 validation_fraction=0.1, beta_1=0.9, beta_2=0.999,\n                 epsilon=1e-08, preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n\nclass CatGBModel(Model, metaclass=WrapperMeta):\n    def __init__(self, cat_model, cat_features, domain):\n        super().__init__(domain)\n        self.cat_model = cat_model\n        self.cat_features = cat_features\n\n    def predict(self, X):\n        if self.cat_features:\n            X = X.astype(str)\n        value = self.cat_model.predict(X).flatten()\n        if hasattr(self.cat_model, \"predict_proba\"):\n            probs = self.cat_model.predict_proba(X)\n            return value, probs\n        return value\n\n    def __repr__(self):\n        # Params represented as a comment because not passed into constructor\n        return super().__repr__() + '  # params=' + repr(self.params)\n\n\nclass CatGBBaseLearner(Learner, metaclass=WrapperMeta):\n    \"\"\"\n    ${skldoc}\n    Additional Orange parameters\n\n    preprocessors : list, optional\n        An ordered list of preprocessors applied to data before\n        training or testing.\n        Defaults to\n        `[RemoveNaNClasses(), RemoveNaNColumns()]`\n    \"\"\"\n    supports_weights = True\n    __wraps__ = None\n    __returns__ = CatGBModel\n    _params = {}\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        RemoveNaNColumns(),\n    ]\n\n    # pylint: disable=unused-argument,too-many-arguments,too-many-locals\n    def __init__(self,\n                 iterations=None,\n                 learning_rate=None,\n                 depth=None,\n                 l2_leaf_reg=None,\n                 model_size_reg=None,\n                 rsm=None,\n                 loss_function=None,\n                 border_count=None,\n                 feature_border_type=None,\n                 per_float_feature_quantization=None,\n                 input_borders=None,\n                 output_borders=None,\n                 fold_permutation_block=None,\n                 od_pval=None,\n                 od_wait=None,\n                 od_type=None,\n                 nan_mode=None,\n                 counter_calc_method=None,\n                 leaf_estimation_iterations=None,\n                 leaf_estimation_method=None,\n                 thread_count=None,\n                 random_seed=None,\n                 use_best_model=None,\n                 verbose=False,\n                 logging_level=None,\n                 metric_period=None,\n                 ctr_leaf_count_limit=None,\n                 store_all_simple_ctr=None,\n                 max_ctr_complexity=None,\n                 has_time=None,\n                 allow_const_label=None,\n                 classes_count=None,\n                 class_weights=None,\n                 one_hot_max_size=None,\n                 random_strength=None,\n                 name=None,\n                 ignored_features=None,\n                 train_dir=cache_dir(),\n                 custom_loss=None,\n                 custom_metric=None,\n                 eval_metric=None,\n                 bagging_temperature=None,\n                 save_snapshot=None,\n                 snapshot_file=None,\n                 snapshot_interval=None,\n                 fold_len_multiplier=None,\n                 used_ram_limit=None,\n                 gpu_ram_part=None,\n                 allow_writing_files=False,\n                 final_ctr_computation_mode=None,\n                 approx_on_full_history=None,\n                 boosting_type=None,\n                 simple_ctr=None,\n                 combinations_ctr=None,\n                 per_feature_ctr=None,\n                 task_type=None,\n                 device_config=None,\n                 devices=None,\n                 bootstrap_type=None,\n                 subsample=None,\n                 sampling_unit=None,\n                 dev_score_calc_obj_block_size=None,\n                 max_depth=None,\n                 n_estimators=None,\n                 num_boost_round=None,\n                 num_trees=None,\n                 colsample_bylevel=None,\n                 random_state=None,\n                 reg_lambda=None,\n                 objective=None,\n                 eta=None,\n                 max_bin=None,\n                 scale_pos_weight=None,\n                 gpu_cat_features_storage=None,\n                 data_partition=None,\n                 metadata=None,\n                 early_stopping_rounds=None,\n                 cat_features=None,\n                 grow_policy=None,\n                 min_data_in_leaf=None,\n                 min_child_samples=None,\n                 max_leaves=None,\n                 num_leaves=None,\n                 score_function=None,\n                 leaf_estimation_backtracking=None,\n                 ctr_history_unit=None,\n                 monotone_constraints=None,\n                 feature_weights=None,\n                 penalties_coefficient=None,\n                 first_feature_use_penalties=None,\n                 model_shrink_rate=None,\n                 model_shrink_mode=None,\n                 langevin=None,\n                 diffusion_temperature=None,\n                 posterior_sampling=None,\n                 boost_from_average=None,\n                 text_features=None,\n                 tokenizers=None,\n                 dictionaries=None,\n                 feature_calcers=None,\n                 text_processing=None,\n                 preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n    @property\n    def params(self):\n        return self._params\n\n    @params.setter\n    def params(self, value):\n        self._params = self._get_wrapper_params(value)\n\n    def _get_wrapper_params(self, values):\n        spec = list(inspect.signature(\n            self.__wraps__.__init__).parameters.keys())\n        return {name: values[name] for name in spec[1:] if name in values}\n\n    def __call__(self, data, progress_callback=None):\n        m = super().__call__(data, progress_callback)\n        m.params = self.params\n        return m\n\n    def fit_storage(self, data: Table):\n        domain, X, Y, W = data.domain, data.X, data.Y.reshape(-1), None\n        if self.supports_weights and data.has_weights():\n            W = data.W.reshape(-1)\n        # pylint: disable=not-callable\n        clf = self.__wraps__(**self.params)\n        cat_features = [i for i, attr in enumerate(domain.attributes)\n                        if attr.is_discrete]\n        if cat_features:\n            X = X.astype(str)\n        cat_model = clf.fit(X, Y, cat_features=cat_features, sample_weight=W)\n        return self.__returns__(cat_model, cat_features, domain)\n\n    def __getattr__(self, item):\n        try:\n            return self.params[item]\n        except (KeyError, AttributeError):\n            raise AttributeError(item) from None\n\n    def __dir__(self):\n        dd = super().__dir__()\n        return list(sorted(set(dd) | set(self.params.keys())))\n\n\nclass XGBBase(SklLearner):\n    \"\"\"Base class for xgboost (classification and regression) learners \"\"\"\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        Continuize(),\n        RemoveNaNColumns(),\n    ]\n\n    def __init__(self, preprocessors=None, **kwargs):\n        super().__init__(preprocessors=preprocessors)\n        self.params = kwargs\n\n    @SklLearner.params.setter\n    def params(self, values: Dict):\n        self._params = values\n",
            "header": {
                "file": {
                    "path": "Orange/base.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "162b29a3b",
                "new_commit_hash": "f618a876f",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/base.py"
            },
            "plus_file": {
                "path": "b/Orange/base.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 136,
                            "length": 7
                        },
                        "new_range": {
                            "start": 136,
                            "length": 11
                        },
                        "section": "class Learner(ReprableWithPreprocessors):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        progress_callback(0.1, \"Fitting...\")",
                                "type": "context"
                            },
                            {
                                "content": "        model = self._fit_model(data)",
                                "type": "context"
                            },
                            {
                                "content": "        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]",
                                "type": "context"
                            },
                            {
                                "content": "        model.domain = data.domain",
                                "type": "deleted"
                            },
                            {
                                "content": "        if not hasattr(model, \"domain\") or model.domain is None:",
                                "type": "added"
                            },
                            {
                                "content": "            # some models set domain themself and it should be respected",
                                "type": "added"
                            },
                            {
                                "content": "            # e.g. calibration learners set the base_learner's domain which",
                                "type": "added"
                            },
                            {
                                "content": "            # would be wrongly overwritten if we set it here for any model",
                                "type": "added"
                            },
                            {
                                "content": "            model.domain = data.domain",
                                "type": "added"
                            },
                            {
                                "content": "        model.supports_multiclass = self.supports_multiclass",
                                "type": "context"
                            },
                            {
                                "content": "        model.name = self.name",
                                "type": "context"
                            },
                            {
                                "content": "        model.original_domain = origdomain",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/base.py",
                            "type": "method",
                            "name": "Learner.__call__",
                            "content": "class Learner(ReprableWithPreprocessors):\n    \"\"\"The base learner class.\n\n    Preprocessors can behave in a number of different ways, all of which are\n    described here.\n    If the user does not pass a preprocessor argument into the Learner\n    constructor, the default learner preprocessors are used. We assume the user\n    would simply like to get things done without having to worry about\n    preprocessors.\n    If the user chooses to pass in their own preprocessors, we assume they know\n    what they are doing. In this case, only the user preprocessors are used and\n    the default preprocessors are ignored.\n    In case the user would like to use the default preprocessors as well as\n    their own ones, the `use_default_preprocessors` flag should be set.\n\n    Parameters\n    ----------\n    preprocessors : Preprocessor or tuple[Preprocessor], optional\n        User defined preprocessors. If the user specifies their own\n        preprocessors, the default ones will not be used, unless the\n        `use_default_preprocessors` flag is set.\n\n    Attributes\n    ----------\n    preprocessors : tuple[Preprocessor] (default None)\n        The used defined preprocessors that will be used on any data.\n    use_default_preprocessors : bool (default False)\n        This flag indicates whether to use the default preprocessors that are\n        defined on the Learner class. Since preprocessors can be applied in a\n        number of ways\n    active_preprocessors : tuple[Preprocessor]\n        The processors that will be used when data is passed to the learner.\n        This depends on whether the user has passed in their own preprocessors\n        and whether the `use_default_preprocessors` flag is set.\n\n        This property is needed mainly because of the `Fitter` class, which can\n        not know in advance, which preprocessors it will need to use. Therefore\n        this resolves the active preprocessors using a lazy approach.\n    params : dict\n        The params that the learner is constructed with.\n\n    \"\"\"\n    supports_multiclass = False\n    supports_weights = False\n    #: A sequence of data preprocessors to apply on data prior to\n    #: fitting the model\n    preprocessors = ()\n    learner_adequacy_err_msg = ''\n\n    def __init__(self, preprocessors=None):\n        self.use_default_preprocessors = False\n        if isinstance(preprocessors, Iterable):\n            self.preprocessors = tuple(preprocessors)\n        elif preprocessors:\n            self.preprocessors = (preprocessors,)\n\n    def fit(self, X, Y, W=None):\n        raise RuntimeError(\n            \"Descendants of Learner must overload method fit or fit_storage\")\n\n    def fit_storage(self, data):\n        \"\"\"Default implementation of fit_storage defaults to calling fit.\n        Derived classes must define fit_storage or fit\"\"\"\n        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n        return self.fit(X, Y, W)\n\n    def __call__(self, data, progress_callback=None):\n        if not self.check_learner_adequacy(data.domain):\n            raise ValueError(self.learner_adequacy_err_msg)\n\n        origdomain = data.domain\n\n        if isinstance(data, Instance):\n            data = Table(data.domain, [data])\n        origdata = data\n\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        progress_callback(0, \"Preprocessing...\")\n        try:\n            cb = wrap_callback(progress_callback, end=0.1)\n            data = self.preprocess(data, progress_callback=cb)\n        except TypeError:\n            data = self.preprocess(data)\n            warnings.warn(\"A keyword argument 'progress_callback' has been \"\n                          \"added to the preprocess() signature. Implementing \"\n                          \"the method without the argument is deprecated and \"\n                          \"will result in an error in the future.\",\n                          OrangeDeprecationWarning)\n\n        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:\n            raise TypeError(\"%s doesn't support multiple class variables\" %\n                            self.__class__.__name__)\n\n        progress_callback(0.1, \"Fitting...\")\n        model = self._fit_model(data)\n        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]\n        model.domain = data.domain\n        model.supports_multiclass = self.supports_multiclass\n        model.name = self.name\n        model.original_domain = origdomain\n        model.original_data = origdata\n        progress_callback(1)\n        return model\n\n    def _fit_model(self, data):\n        if type(self).fit is Learner.fit:\n            return self.fit_storage(data)\n        else:\n            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n            return self.fit(X, Y, W)\n\n    def preprocess(self, data, progress_callback=None):\n        \"\"\"Apply the `preprocessors` to the data\"\"\"\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        n_pps = len(list(self.active_preprocessors))\n        for i, pp in enumerate(self.active_preprocessors):\n            progress_callback(i / n_pps)\n            data = pp(data)\n        progress_callback(1)\n        return data\n\n    @property\n    def active_preprocessors(self):\n        yield from self.preprocessors\n        if (self.use_default_preprocessors and\n                self.preprocessors is not type(self).preprocessors):\n            yield from type(self).preprocessors\n\n    def check_learner_adequacy(self, _):\n        return True\n\n    @property\n    def name(self):\n        \"\"\"Return a short name derived from Learner type name\"\"\"\n        try:\n            return self.__name\n        except AttributeError:\n            name = self.__class__.__name__\n            if name.endswith('Learner'):\n                name = name[:-len('Learner')]\n            if name.endswith('Fitter'):\n                name = name[:-len('Fitter')]\n            if isinstance(self, SklLearner) and name.startswith('Skl'):\n                name = name[len('Skl'):]\n            name = name or 'learner'\n            # From http://stackoverflow.com/a/1176023/1090455 <3\n            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\\1 \\2',\n                               re.sub(r'(.)([A-Z][a-z]+)', r'\\1 \\2', name)).lower()\n            return self.name\n\n    @name.setter\n    def name(self, value):\n        self.__name = value\n\n    def __str__(self):\n        return self.name",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 108,
                            "end_lineno": 145,
                            "parent": {
                                "file_name": "Orange/base.py",
                                "type": "class",
                                "name": "Learner",
                                "content": "class Learner(ReprableWithPreprocessors):\n    \"\"\"The base learner class.\n\n    Preprocessors can behave in a number of different ways, all of which are\n    described here.\n    If the user does not pass a preprocessor argument into the Learner\n    constructor, the default learner preprocessors are used. We assume the user\n    would simply like to get things done without having to worry about\n    preprocessors.\n    If the user chooses to pass in their own preprocessors, we assume they know\n    what they are doing. In this case, only the user preprocessors are used and\n    the default preprocessors are ignored.\n    In case the user would like to use the default preprocessors as well as\n    their own ones, the `use_default_preprocessors` flag should be set.\n\n    Parameters\n    ----------\n    preprocessors : Preprocessor or tuple[Preprocessor], optional\n        User defined preprocessors. If the user specifies their own\n        preprocessors, the default ones will not be used, unless the\n        `use_default_preprocessors` flag is set.\n\n    Attributes\n    ----------\n    preprocessors : tuple[Preprocessor] (default None)\n        The used defined preprocessors that will be used on any data.\n    use_default_preprocessors : bool (default False)\n        This flag indicates whether to use the default preprocessors that are\n        defined on the Learner class. Since preprocessors can be applied in a\n        number of ways\n    active_preprocessors : tuple[Preprocessor]\n        The processors that will be used when data is passed to the learner.\n        This depends on whether the user has passed in their own preprocessors\n        and whether the `use_default_preprocessors` flag is set.\n\n        This property is needed mainly because of the `Fitter` class, which can\n        not know in advance, which preprocessors it will need to use. Therefore\n        this resolves the active preprocessors using a lazy approach.\n    params : dict\n        The params that the learner is constructed with.\n\n    \"\"\"\n    supports_multiclass = False\n    supports_weights = False\n    #: A sequence of data preprocessors to apply on data prior to\n    #: fitting the model\n    preprocessors = ()\n    learner_adequacy_err_msg = ''\n\n    def __init__(self, preprocessors=None):\n        self.use_default_preprocessors = False\n        if isinstance(preprocessors, Iterable):\n            self.preprocessors = tuple(preprocessors)\n        elif preprocessors:\n            self.preprocessors = (preprocessors,)\n\n    def fit(self, X, Y, W=None):\n        raise RuntimeError(\n            \"Descendants of Learner must overload method fit or fit_storage\")\n\n    def fit_storage(self, data):\n        \"\"\"Default implementation of fit_storage defaults to calling fit.\n        Derived classes must define fit_storage or fit\"\"\"\n        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n        return self.fit(X, Y, W)\n\n    def __call__(self, data, progress_callback=None):\n        if not self.check_learner_adequacy(data.domain):\n            raise ValueError(self.learner_adequacy_err_msg)\n\n        origdomain = data.domain\n\n        if isinstance(data, Instance):\n            data = Table(data.domain, [data])\n        origdata = data\n\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        progress_callback(0, \"Preprocessing...\")\n        try:\n            cb = wrap_callback(progress_callback, end=0.1)\n            data = self.preprocess(data, progress_callback=cb)\n        except TypeError:\n            data = self.preprocess(data)\n            warnings.warn(\"A keyword argument 'progress_callback' has been \"\n                          \"added to the preprocess() signature. Implementing \"\n                          \"the method without the argument is deprecated and \"\n                          \"will result in an error in the future.\",\n                          OrangeDeprecationWarning)\n\n        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:\n            raise TypeError(\"%s doesn't support multiple class variables\" %\n                            self.__class__.__name__)\n\n        progress_callback(0.1, \"Fitting...\")\n        model = self._fit_model(data)\n        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]\n        model.domain = data.domain\n        model.supports_multiclass = self.supports_multiclass\n        model.name = self.name\n        model.original_domain = origdomain\n        model.original_data = origdata\n        progress_callback(1)\n        return model\n\n    def _fit_model(self, data):\n        if type(self).fit is Learner.fit:\n            return self.fit_storage(data)\n        else:\n            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n            return self.fit(X, Y, W)\n\n    def preprocess(self, data, progress_callback=None):\n        \"\"\"Apply the `preprocessors` to the data\"\"\"\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        n_pps = len(list(self.active_preprocessors))\n        for i, pp in enumerate(self.active_preprocessors):\n            progress_callback(i / n_pps)\n            data = pp(data)\n        progress_callback(1)\n        return data\n\n    @property\n    def active_preprocessors(self):\n        yield from self.preprocessors\n        if (self.use_default_preprocessors and\n                self.preprocessors is not type(self).preprocessors):\n            yield from type(self).preprocessors\n\n    def check_learner_adequacy(self, _):\n        return True\n\n    @property\n    def name(self):\n        \"\"\"Return a short name derived from Learner type name\"\"\"\n        try:\n            return self.__name\n        except AttributeError:\n            name = self.__class__.__name__\n            if name.endswith('Learner'):\n                name = name[:-len('Learner')]\n            if name.endswith('Fitter'):\n                name = name[:-len('Fitter')]\n            if isinstance(self, SklLearner) and name.startswith('Skl'):\n                name = name[len('Skl'):]\n            name = name or 'learner'\n            # From http://stackoverflow.com/a/1176023/1090455 <3\n            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\\1 \\2',\n                               re.sub(r'(.)([A-Z][a-z]+)', r'\\1 \\2', name)).lower()\n            return self.name\n\n    @name.setter\n    def name(self, value):\n        self.__name = value\n\n    def __str__(self):\n        return self.name",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 42,
                                "end_lineno": 199,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Orange/base.py",
                            "type": "class",
                            "name": "Learner",
                            "content": "class Learner(ReprableWithPreprocessors):\n    \"\"\"The base learner class.\n\n    Preprocessors can behave in a number of different ways, all of which are\n    described here.\n    If the user does not pass a preprocessor argument into the Learner\n    constructor, the default learner preprocessors are used. We assume the user\n    would simply like to get things done without having to worry about\n    preprocessors.\n    If the user chooses to pass in their own preprocessors, we assume they know\n    what they are doing. In this case, only the user preprocessors are used and\n    the default preprocessors are ignored.\n    In case the user would like to use the default preprocessors as well as\n    their own ones, the `use_default_preprocessors` flag should be set.\n\n    Parameters\n    ----------\n    preprocessors : Preprocessor or tuple[Preprocessor], optional\n        User defined preprocessors. If the user specifies their own\n        preprocessors, the default ones will not be used, unless the\n        `use_default_preprocessors` flag is set.\n\n    Attributes\n    ----------\n    preprocessors : tuple[Preprocessor] (default None)\n        The used defined preprocessors that will be used on any data.\n    use_default_preprocessors : bool (default False)\n        This flag indicates whether to use the default preprocessors that are\n        defined on the Learner class. Since preprocessors can be applied in a\n        number of ways\n    active_preprocessors : tuple[Preprocessor]\n        The processors that will be used when data is passed to the learner.\n        This depends on whether the user has passed in their own preprocessors\n        and whether the `use_default_preprocessors` flag is set.\n\n        This property is needed mainly because of the `Fitter` class, which can\n        not know in advance, which preprocessors it will need to use. Therefore\n        this resolves the active preprocessors using a lazy approach.\n    params : dict\n        The params that the learner is constructed with.\n\n    \"\"\"\n    supports_multiclass = False\n    supports_weights = False\n    #: A sequence of data preprocessors to apply on data prior to\n    #: fitting the model\n    preprocessors = ()\n    learner_adequacy_err_msg = ''\n\n    def __init__(self, preprocessors=None):\n        self.use_default_preprocessors = False\n        if isinstance(preprocessors, Iterable):\n            self.preprocessors = tuple(preprocessors)\n        elif preprocessors:\n            self.preprocessors = (preprocessors,)\n\n    def fit(self, X, Y, W=None):\n        raise RuntimeError(\n            \"Descendants of Learner must overload method fit or fit_storage\")\n\n    def fit_storage(self, data):\n        \"\"\"Default implementation of fit_storage defaults to calling fit.\n        Derived classes must define fit_storage or fit\"\"\"\n        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n        return self.fit(X, Y, W)\n\n    def __call__(self, data, progress_callback=None):\n        if not self.check_learner_adequacy(data.domain):\n            raise ValueError(self.learner_adequacy_err_msg)\n\n        origdomain = data.domain\n\n        if isinstance(data, Instance):\n            data = Table(data.domain, [data])\n        origdata = data\n\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        progress_callback(0, \"Preprocessing...\")\n        try:\n            cb = wrap_callback(progress_callback, end=0.1)\n            data = self.preprocess(data, progress_callback=cb)\n        except TypeError:\n            data = self.preprocess(data)\n            warnings.warn(\"A keyword argument 'progress_callback' has been \"\n                          \"added to the preprocess() signature. Implementing \"\n                          \"the method without the argument is deprecated and \"\n                          \"will result in an error in the future.\",\n                          OrangeDeprecationWarning)\n\n        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:\n            raise TypeError(\"%s doesn't support multiple class variables\" %\n                            self.__class__.__name__)\n\n        progress_callback(0.1, \"Fitting...\")\n        model = self._fit_model(data)\n        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]\n        model.domain = data.domain\n        model.supports_multiclass = self.supports_multiclass\n        model.name = self.name\n        model.original_domain = origdomain\n        model.original_data = origdata\n        progress_callback(1)\n        return model\n\n    def _fit_model(self, data):\n        if type(self).fit is Learner.fit:\n            return self.fit_storage(data)\n        else:\n            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n            return self.fit(X, Y, W)\n\n    def preprocess(self, data, progress_callback=None):\n        \"\"\"Apply the `preprocessors` to the data\"\"\"\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        n_pps = len(list(self.active_preprocessors))\n        for i, pp in enumerate(self.active_preprocessors):\n            progress_callback(i / n_pps)\n            data = pp(data)\n        progress_callback(1)\n        return data\n\n    @property\n    def active_preprocessors(self):\n        yield from self.preprocessors\n        if (self.use_default_preprocessors and\n                self.preprocessors is not type(self).preprocessors):\n            yield from type(self).preprocessors\n\n    def check_learner_adequacy(self, _):\n        return True\n\n    @property\n    def name(self):\n        \"\"\"Return a short name derived from Learner type name\"\"\"\n        try:\n            return self.__name\n        except AttributeError:\n            name = self.__class__.__name__\n            if name.endswith('Learner'):\n                name = name[:-len('Learner')]\n            if name.endswith('Fitter'):\n                name = name[:-len('Fitter')]\n            if isinstance(self, SklLearner) and name.startswith('Skl'):\n                name = name[len('Skl'):]\n            name = name or 'learner'\n            # From http://stackoverflow.com/a/1176023/1090455 <3\n            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\\1 \\2',\n                               re.sub(r'(.)([A-Z][a-z]+)', r'\\1 \\2', name)).lower()\n            return self.name\n\n    @name.setter\n    def name(self, value):\n        self.__name = value\n\n    def __str__(self):\n        return self.name",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 42,
                            "end_lineno": 199,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import unittest\nfrom unittest.mock import Mock, patch\n\nimport numpy as np\n\nfrom Orange.base import Model\nfrom Orange.classification.calibration import \\\n    ThresholdLearner, ThresholdClassifier, \\\n    CalibratedLearner, CalibratedClassifier\nfrom Orange.data import Table\n\n\nclass TestThresholdClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = ThresholdClassifier(base_model, 0.5)\n        self.data = Mock()\n\n    def test_threshold(self):\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        self.model.threshold = 0.8\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 0, 0, 1, 1, 0])\n\n        self.model.threshold = 0\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [1] * 6)\n\n    def test_return_types(self):\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        probs = self.model(self.data, ret=Model.Probs)\n        np.testing.assert_equal(probs, self.probs)\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_nans(self):\n        self.probs[1, :] = np.nan\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, np.nan, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_non_binary_base(self):\n        base_model = Mock()\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var = Mock()\n        base_model.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n\nclass TestThresholdLearner(unittest.TestCase):\n    @patch(\"Orange.evaluation.performance_curves.Curves.from_results\")\n    @patch(\"Orange.classification.calibration.TestOnTrainingData\")\n    def test_fit_storage(self, test_on_training, curves_from_results):\n        curves_from_results.return_value = curves = Mock()\n        curves.probs = np.array([0.1, 0.15, 0.3, 0.45, 0.6, 0.8])\n        curves.ca = lambda: np.array([0.1, 0.7, 0.4, 0.4, 0.3, 0.1])\n        curves.f1 = lambda: np.array([0.1, 0.2, 0.4, 0.4, 0.3, 0.1])\n        model = Mock()\n        model.domain.class_var.is_discrete = True\n        model.domain.class_var.values = (\"a\", \"b\")\n        data = Table(\"heart_disease\")\n        learner = Mock()\n        test_on_training.return_value = tot = Mock()\n        res = Mock()\n        res.models = np.array([[model]])\n        tot.return_value = res\n\n        thresh_learner = ThresholdLearner(\n            base_learner=learner,\n            threshold_criterion=ThresholdLearner.OptimizeCA)\n        thresh_model = thresh_learner(data)\n        self.assertEqual(thresh_model.threshold, 0.15)\n        args, _ = tot.call_args  # pylint: disable=unpacking-non-sequence\n        self.assertEqual(len(args), 2)\n        self.assertIs(args[0], data)\n        self.assertIs(args[1][0], learner)\n\n        _, kwargs = test_on_training.call_args\n        self.assertEqual(len(args[1]), 1)\n        self.assertEqual(kwargs, {\"store_models\": 1})\n\n        thresh_learner = ThresholdLearner(\n            base_learner=learner,\n            threshold_criterion=ThresholdLearner.OptimizeF1)\n        thresh_model = thresh_learner(data)\n        self.assertEqual(thresh_model.threshold, 0.45)\n\n    def test_non_binary_class(self):\n        thresh_learner = ThresholdLearner(\n            base_learner=Mock(),\n            threshold_criterion=ThresholdLearner.OptimizeF1)\n\n        data = Mock()\n        data.domain.class_var.is_discrete = True\n        data.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n        data.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n        data.domain.class_var = Mock()\n        data.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n\nclass TestCalibratedClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = CalibratedClassifier(base_model, None)\n        self.data = Mock()\n\n    def test_call(self):\n        calprobs = np.arange(self.probs.size).reshape(self.probs.shape)\n        calprobs = calprobs / np.sum(calprobs, axis=1)[:, None]\n        calprobs[-1] = [0.7, 0.3]\n        self.model.calibrated_probs = Mock(return_value=calprobs)\n\n        probs = self.model(self.data, ret=Model.Probs)\n        self.model.calibrated_probs.assert_called_with(self.probs)\n        np.testing.assert_almost_equal(probs, calprobs)\n\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_almost_equal(probs, calprobs)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n    def test_calibrated_probs(self):\n        self.model.calibrators = None\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_equal(calprobs, self.probs)\n        self.assertIsNot(calprobs, self.probs)\n\n        calibrator = Mock()\n        calibrator.predict = lambda x: x**2\n        self.model.calibrators = [calibrator] * 2\n        calprobs = self.model.calibrated_probs(self.probs)\n        expprobs = self.probs ** 2 / np.sum(self.probs ** 2, axis=1)[:, None]\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n        self.probs[1] = 0\n        self.probs[2] = np.nan\n        expprobs[1] = 0.5\n        expprobs[2] = np.nan\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n\nclass TestCalibratedLearner(unittest.TestCase):\n    @patch(\"Orange.classification.calibration._SigmoidCalibration.fit\")\n    @patch(\"Orange.classification.calibration.TestOnTrainingData\")\n    def test_fit_storage(self, test_on_training, sigmoid_fit):\n        data = Table(\"heart_disease\")\n        learner = Mock()\n\n        model = Mock()\n        model.domain.class_var.is_discrete = True\n        model.domain.class_var.values = (\"a\", \"b\")\n\n        test_on_training.return_value = tot = Mock()\n        res = Mock()\n        res.models = np.array([[model]])\n        res.probabilities = np.arange(20, dtype=float).reshape(1, 5, 4)\n        tot.return_value = res\n\n        sigmoid_fit.return_value = Mock()\n\n        cal_learner = CalibratedLearner(\n            base_learner=learner, calibration_method=CalibratedLearner.Sigmoid)\n        cal_model = cal_learner(data)\n\n        self.assertIs(cal_model.base_model, model)\n        self.assertEqual(cal_model.calibrators, [sigmoid_fit.return_value] * 4)\n        args, _ = tot.call_args  # pylint: disable=unpacking-non-sequence\n        self.assertEqual(len(args), 2)\n        self.assertIs(args[0], data)\n        self.assertIs(args[1][0], learner)\n        self.assertEqual(len(args[1]), 1)\n\n        _, kwargs = test_on_training.call_args\n        self.assertEqual(kwargs, {\"store_models\": 1})\n\n        for call, cls_probs in zip(sigmoid_fit.call_args_list,\n                                   res.probabilities[0].T):\n            np.testing.assert_equal(call[0][0], cls_probs)\n",
            "new_file_content": "import unittest\nfrom unittest.mock import Mock, patch\n\nimport numpy as np\n\nfrom Orange.base import Model\nfrom Orange.classification import LogisticRegressionLearner\nfrom Orange.classification.calibration import \\\n    ThresholdLearner, ThresholdClassifier, \\\n    CalibratedLearner, CalibratedClassifier\nfrom Orange.data import Table\n\n\nclass TestThresholdClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = ThresholdClassifier(base_model, 0.5)\n        self.data = Mock()\n\n    def test_threshold(self):\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        self.model.threshold = 0.8\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 0, 0, 1, 1, 0])\n\n        self.model.threshold = 0\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [1] * 6)\n\n    def test_return_types(self):\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        probs = self.model(self.data, ret=Model.Probs)\n        np.testing.assert_equal(probs, self.probs)\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_nans(self):\n        self.probs[1, :] = np.nan\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, np.nan, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_non_binary_base(self):\n        base_model = Mock()\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var = Mock()\n        base_model.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n    def test_np_data(self):\n        \"\"\"\n        Test ThresholdModel with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = ThresholdLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)\n\n\nclass TestThresholdLearner(unittest.TestCase):\n    @patch(\"Orange.evaluation.performance_curves.Curves.from_results\")\n    @patch(\"Orange.classification.calibration.TestOnTrainingData\")\n    def test_fit_storage(self, test_on_training, curves_from_results):\n        curves_from_results.return_value = curves = Mock()\n        curves.probs = np.array([0.1, 0.15, 0.3, 0.45, 0.6, 0.8])\n        curves.ca = lambda: np.array([0.1, 0.7, 0.4, 0.4, 0.3, 0.1])\n        curves.f1 = lambda: np.array([0.1, 0.2, 0.4, 0.4, 0.3, 0.1])\n        model = Mock()\n        model.domain.class_var.is_discrete = True\n        model.domain.class_var.values = (\"a\", \"b\")\n        data = Table(\"heart_disease\")\n        learner = Mock()\n        test_on_training.return_value = tot = Mock()\n        res = Mock()\n        res.models = np.array([[model]])\n        tot.return_value = res\n\n        thresh_learner = ThresholdLearner(\n            base_learner=learner,\n            threshold_criterion=ThresholdLearner.OptimizeCA)\n        thresh_model = thresh_learner(data)\n        self.assertEqual(thresh_model.threshold, 0.15)\n        args, _ = tot.call_args  # pylint: disable=unpacking-non-sequence\n        self.assertEqual(len(args), 2)\n        self.assertIs(args[0], data)\n        self.assertIs(args[1][0], learner)\n\n        _, kwargs = test_on_training.call_args\n        self.assertEqual(len(args[1]), 1)\n        self.assertEqual(kwargs, {\"store_models\": 1})\n\n        thresh_learner = ThresholdLearner(\n            base_learner=learner,\n            threshold_criterion=ThresholdLearner.OptimizeF1)\n        thresh_model = thresh_learner(data)\n        self.assertEqual(thresh_model.threshold, 0.45)\n\n    def test_non_binary_class(self):\n        thresh_learner = ThresholdLearner(\n            base_learner=Mock(),\n            threshold_criterion=ThresholdLearner.OptimizeF1)\n\n        data = Mock()\n        data.domain.class_var.is_discrete = True\n        data.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n        data.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n        data.domain.class_var = Mock()\n        data.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n\nclass TestCalibratedClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = CalibratedClassifier(base_model, None)\n        self.data = Mock()\n\n    def test_call(self):\n        calprobs = np.arange(self.probs.size).reshape(self.probs.shape)\n        calprobs = calprobs / np.sum(calprobs, axis=1)[:, None]\n        calprobs[-1] = [0.7, 0.3]\n        self.model.calibrated_probs = Mock(return_value=calprobs)\n\n        probs = self.model(self.data, ret=Model.Probs)\n        self.model.calibrated_probs.assert_called_with(self.probs)\n        np.testing.assert_almost_equal(probs, calprobs)\n\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_almost_equal(probs, calprobs)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n    def test_calibrated_probs(self):\n        self.model.calibrators = None\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_equal(calprobs, self.probs)\n        self.assertIsNot(calprobs, self.probs)\n\n        calibrator = Mock()\n        calibrator.predict = lambda x: x**2\n        self.model.calibrators = [calibrator] * 2\n        calprobs = self.model.calibrated_probs(self.probs)\n        expprobs = self.probs ** 2 / np.sum(self.probs ** 2, axis=1)[:, None]\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n        self.probs[1] = 0\n        self.probs[2] = np.nan\n        expprobs[1] = 0.5\n        expprobs[2] = np.nan\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n    def test_np_data(self):\n        \"\"\"\n        Test CalibratedClassifier with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = CalibratedLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)\n\n\nclass TestCalibratedLearner(unittest.TestCase):\n    @patch(\"Orange.classification.calibration._SigmoidCalibration.fit\")\n    @patch(\"Orange.classification.calibration.TestOnTrainingData\")\n    def test_fit_storage(self, test_on_training, sigmoid_fit):\n        data = Table(\"heart_disease\")\n        learner = Mock()\n\n        model = Mock()\n        model.domain.class_var.is_discrete = True\n        model.domain.class_var.values = (\"a\", \"b\")\n\n        test_on_training.return_value = tot = Mock()\n        res = Mock()\n        res.models = np.array([[model]])\n        res.probabilities = np.arange(20, dtype=float).reshape(1, 5, 4)\n        tot.return_value = res\n\n        sigmoid_fit.return_value = Mock()\n\n        cal_learner = CalibratedLearner(\n            base_learner=learner, calibration_method=CalibratedLearner.Sigmoid)\n        cal_model = cal_learner(data)\n\n        self.assertIs(cal_model.base_model, model)\n        self.assertEqual(cal_model.calibrators, [sigmoid_fit.return_value] * 4)\n        args, _ = tot.call_args  # pylint: disable=unpacking-non-sequence\n        self.assertEqual(len(args), 2)\n        self.assertIs(args[0], data)\n        self.assertIs(args[1][0], learner)\n        self.assertEqual(len(args[1]), 1)\n\n        _, kwargs = test_on_training.call_args\n        self.assertEqual(kwargs, {\"store_models\": 1})\n\n        for call, cls_probs in zip(sigmoid_fit.call_args_list,\n                                   res.probabilities[0].T):\n            np.testing.assert_equal(call[0][0], cls_probs)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Orange/classification/tests/test_calibration.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "733ca9383",
                "new_commit_hash": "1d5e8e6da",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Orange/classification/tests/test_calibration.py"
            },
            "plus_file": {
                "path": "b/Orange/classification/tests/test_calibration.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 4,
                            "length": 6
                        },
                        "new_range": {
                            "start": 4,
                            "length": 7
                        },
                        "section": "from unittest.mock import Mock, patch"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import numpy as np",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.base import Model",
                                "type": "context"
                            },
                            {
                                "content": "from Orange.classification import LogisticRegressionLearner",
                                "type": "added"
                            },
                            {
                                "content": "from Orange.classification.calibration import \\",
                                "type": "context"
                            },
                            {
                                "content": "    ThresholdLearner, ThresholdClassifier, \\",
                                "type": "context"
                            },
                            {
                                "content": "    CalibratedLearner, CalibratedClassifier",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/classification/tests/test_calibration.py",
                            "type": "statement",
                            "name": "",
                            "content": "from Orange.classification import LogisticRegressionLearner",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 7,
                            "end_lineno": 7,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 65,
                            "length": 6
                        },
                        "new_range": {
                            "start": 66,
                            "length": 18
                        },
                        "section": "class TestThresholdClassifier(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        base_model.domain.class_var.is_discrete = False",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_np_data(self):",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        Test ThresholdModel with numpy data.",
                                "type": "added"
                            },
                            {
                                "content": "        When passing numpy data to model they should be already",
                                "type": "added"
                            },
                            {
                                "content": "        transformed to models domain since model do not know how to do it.",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        data = Table('heart_disease')",
                                "type": "added"
                            },
                            {
                                "content": "        base_learner = LogisticRegressionLearner()",
                                "type": "added"
                            },
                            {
                                "content": "        model = ThresholdLearner(base_learner)(data)",
                                "type": "added"
                            },
                            {
                                "content": "        res = model(model.data_to_model_domain(data).X)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTupleEqual((len(data),), res.shape)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestThresholdLearner(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    @patch(\"Orange.evaluation.performance_curves.Curves.from_results\")",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/classification/tests/test_calibration.py",
                            "type": "class",
                            "name": "TestThresholdClassifier",
                            "content": "class TestThresholdClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = ThresholdClassifier(base_model, 0.5)\n        self.data = Mock()\n\n    def test_threshold(self):\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        self.model.threshold = 0.8\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 0, 0, 1, 1, 0])\n\n        self.model.threshold = 0\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [1] * 6)\n\n    def test_return_types(self):\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        probs = self.model(self.data, ret=Model.Probs)\n        np.testing.assert_equal(probs, self.probs)\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_nans(self):\n        self.probs[1, :] = np.nan\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, np.nan, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_non_binary_base(self):\n        base_model = Mock()\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var = Mock()\n        base_model.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n    def test_np_data(self):\n        \"\"\"\n        Test ThresholdModel with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = ThresholdLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 14,
                            "end_lineno": 79,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/classification/tests/test_calibration.py",
                            "type": "method",
                            "name": "TestThresholdClassifier.test_np_data",
                            "content": "class TestThresholdClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = ThresholdClassifier(base_model, 0.5)\n        self.data = Mock()\n\n    def test_threshold(self):\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        self.model.threshold = 0.8\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 0, 0, 1, 1, 0])\n\n        self.model.threshold = 0\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [1] * 6)\n\n    def test_return_types(self):\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        probs = self.model(self.data, ret=Model.Probs)\n        np.testing.assert_equal(probs, self.probs)\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_nans(self):\n        self.probs[1, :] = np.nan\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, np.nan, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_non_binary_base(self):\n        base_model = Mock()\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var = Mock()\n        base_model.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n    def test_np_data(self):\n        \"\"\"\n        Test ThresholdModel with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = ThresholdLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 69,
                            "end_lineno": 79,
                            "parent": {
                                "file_name": "Orange/classification/tests/test_calibration.py",
                                "type": "class",
                                "name": "TestThresholdClassifier",
                                "content": "class TestThresholdClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = ThresholdClassifier(base_model, 0.5)\n        self.data = Mock()\n\n    def test_threshold(self):\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        self.model.threshold = 0.8\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 0, 0, 1, 1, 0])\n\n        self.model.threshold = 0\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [1] * 6)\n\n    def test_return_types(self):\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        probs = self.model(self.data, ret=Model.Probs)\n        np.testing.assert_equal(probs, self.probs)\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_nans(self):\n        self.probs[1, :] = np.nan\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, np.nan, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_non_binary_base(self):\n        base_model = Mock()\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var = Mock()\n        base_model.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n    def test_np_data(self):\n        \"\"\"\n        Test ThresholdModel with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = ThresholdLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 14,
                                "end_lineno": 79,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 169,
                            "length": 6
                        },
                        "new_range": {
                            "start": 182,
                            "length": 18
                        },
                        "section": "class TestCalibratedClassifier(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        calprobs = self.model.calibrated_probs(self.probs)",
                                "type": "context"
                            },
                            {
                                "content": "        np.testing.assert_almost_equal(calprobs, expprobs)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_np_data(self):",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        Test CalibratedClassifier with numpy data.",
                                "type": "added"
                            },
                            {
                                "content": "        When passing numpy data to model they should be already",
                                "type": "added"
                            },
                            {
                                "content": "        transformed to models domain since model do not know how to do it.",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        data = Table('heart_disease')",
                                "type": "added"
                            },
                            {
                                "content": "        base_learner = LogisticRegressionLearner()",
                                "type": "added"
                            },
                            {
                                "content": "        model = CalibratedLearner(base_learner)(data)",
                                "type": "added"
                            },
                            {
                                "content": "        res = model(model.data_to_model_domain(data).X)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertTupleEqual((len(data),), res.shape)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestCalibratedLearner(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    @patch(\"Orange.classification.calibration._SigmoidCalibration.fit\")",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Orange/classification/tests/test_calibration.py",
                            "type": "class",
                            "name": "TestCalibratedClassifier",
                            "content": "class TestCalibratedClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = CalibratedClassifier(base_model, None)\n        self.data = Mock()\n\n    def test_call(self):\n        calprobs = np.arange(self.probs.size).reshape(self.probs.shape)\n        calprobs = calprobs / np.sum(calprobs, axis=1)[:, None]\n        calprobs[-1] = [0.7, 0.3]\n        self.model.calibrated_probs = Mock(return_value=calprobs)\n\n        probs = self.model(self.data, ret=Model.Probs)\n        self.model.calibrated_probs.assert_called_with(self.probs)\n        np.testing.assert_almost_equal(probs, calprobs)\n\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_almost_equal(probs, calprobs)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n    def test_calibrated_probs(self):\n        self.model.calibrators = None\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_equal(calprobs, self.probs)\n        self.assertIsNot(calprobs, self.probs)\n\n        calibrator = Mock()\n        calibrator.predict = lambda x: x**2\n        self.model.calibrators = [calibrator] * 2\n        calprobs = self.model.calibrated_probs(self.probs)\n        expprobs = self.probs ** 2 / np.sum(self.probs ** 2, axis=1)[:, None]\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n        self.probs[1] = 0\n        self.probs[2] = np.nan\n        expprobs[1] = 0.5\n        expprobs[2] = np.nan\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n    def test_np_data(self):\n        \"\"\"\n        Test CalibratedClassifier with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = CalibratedLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 138,
                            "end_lineno": 195,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Orange/classification/tests/test_calibration.py",
                            "type": "method",
                            "name": "TestCalibratedClassifier.test_np_data",
                            "content": "class TestCalibratedClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = CalibratedClassifier(base_model, None)\n        self.data = Mock()\n\n    def test_call(self):\n        calprobs = np.arange(self.probs.size).reshape(self.probs.shape)\n        calprobs = calprobs / np.sum(calprobs, axis=1)[:, None]\n        calprobs[-1] = [0.7, 0.3]\n        self.model.calibrated_probs = Mock(return_value=calprobs)\n\n        probs = self.model(self.data, ret=Model.Probs)\n        self.model.calibrated_probs.assert_called_with(self.probs)\n        np.testing.assert_almost_equal(probs, calprobs)\n\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_almost_equal(probs, calprobs)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n    def test_calibrated_probs(self):\n        self.model.calibrators = None\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_equal(calprobs, self.probs)\n        self.assertIsNot(calprobs, self.probs)\n\n        calibrator = Mock()\n        calibrator.predict = lambda x: x**2\n        self.model.calibrators = [calibrator] * 2\n        calprobs = self.model.calibrated_probs(self.probs)\n        expprobs = self.probs ** 2 / np.sum(self.probs ** 2, axis=1)[:, None]\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n        self.probs[1] = 0\n        self.probs[2] = np.nan\n        expprobs[1] = 0.5\n        expprobs[2] = np.nan\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n    def test_np_data(self):\n        \"\"\"\n        Test CalibratedClassifier with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = CalibratedLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 185,
                            "end_lineno": 195,
                            "parent": {
                                "file_name": "Orange/classification/tests/test_calibration.py",
                                "type": "class",
                                "name": "TestCalibratedClassifier",
                                "content": "class TestCalibratedClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = CalibratedClassifier(base_model, None)\n        self.data = Mock()\n\n    def test_call(self):\n        calprobs = np.arange(self.probs.size).reshape(self.probs.shape)\n        calprobs = calprobs / np.sum(calprobs, axis=1)[:, None]\n        calprobs[-1] = [0.7, 0.3]\n        self.model.calibrated_probs = Mock(return_value=calprobs)\n\n        probs = self.model(self.data, ret=Model.Probs)\n        self.model.calibrated_probs.assert_called_with(self.probs)\n        np.testing.assert_almost_equal(probs, calprobs)\n\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_almost_equal(probs, calprobs)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n    def test_calibrated_probs(self):\n        self.model.calibrators = None\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_equal(calprobs, self.probs)\n        self.assertIsNot(calprobs, self.probs)\n\n        calibrator = Mock()\n        calibrator.predict = lambda x: x**2\n        self.model.calibrators = [calibrator] * 2\n        calprobs = self.model.calibrated_probs(self.probs)\n        expprobs = self.probs ** 2 / np.sum(self.probs ** 2, axis=1)[:, None]\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n        self.probs[1] = 0\n        self.probs[2] = np.nan\n        expprobs[1] = 0.5\n        expprobs[2] = np.nan\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n    def test_np_data(self):\n        \"\"\"\n        Test CalibratedClassifier with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = CalibratedLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 138,
                                "end_lineno": 195,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 207,
                            "length": 3
                        },
                        "new_range": {
                            "start": 232,
                            "length": 7
                        },
                        "section": "class TestCalibratedLearner(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        for call, cls_probs in zip(sigmoid_fit.call_args_list,",
                                "type": "context"
                            },
                            {
                                "content": "                                   res.probabilities[0].T):",
                                "type": "context"
                            },
                            {
                                "content": "            np.testing.assert_equal(call[0][0], cls_probs)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "if __name__ == \"__main__\":",
                                "type": "added"
                            },
                            {
                                "content": "    unittest.main()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Orange/classification/tests/test_calibration.py",
                            "type": "statement",
                            "name": "",
                            "content": "if __name__ == \"__main__\":\n    unittest.main()",
                            "ast_type_str": "If",
                            "start_lineno": 237,
                            "end_lineno": 238,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "6791ae20d003b4d1c5adae8097dd53a08141d07a^",
    "new_commit_hash": "6791ae20d003b4d1c5adae8097dd53a08141d07a",
    "commit_message": "Calibration: prevent wrongly overwriting the domain",
    "commit_date": "2021-02-19T12:47:33+01:00",
    "metadata": {}
}
{
    "repo_name": "orange3",
    "new_commit_hash": "6791ae20d003b4d1c5adae8097dd53a08141d07a",
    "test_file_codes": [
        "import unittest\nfrom unittest.mock import Mock, patch\n\nimport numpy as np\n\nfrom Orange.base import Model\nfrom Orange.classification import LogisticRegressionLearner\nfrom Orange.classification.calibration import \\\n    ThresholdLearner, ThresholdClassifier, \\\n    CalibratedLearner, CalibratedClassifier\nfrom Orange.data import Table\n\n\nclass TestThresholdClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = ThresholdClassifier(base_model, 0.5)\n        self.data = Mock()\n\n    def test_threshold(self):\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        self.model.threshold = 0.8\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 0, 0, 1, 1, 0])\n\n        self.model.threshold = 0\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [1] * 6)\n\n    def test_return_types(self):\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        vals = self.model(self.data)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n\n        probs = self.model(self.data, ret=Model.Probs)\n        np.testing.assert_equal(probs, self.probs)\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, 1, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_nans(self):\n        self.probs[1, :] = np.nan\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_equal(vals, [0, np.nan, 0, 1, 1, 0])\n        np.testing.assert_equal(probs, self.probs)\n\n    def test_non_binary_base(self):\n        base_model = Mock()\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n        base_model.domain.class_var = Mock()\n        base_model.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, ThresholdClassifier, base_model, 0.5)\n\n    def test_np_data(self):\n        \"\"\"\n        Test ThresholdModel with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = ThresholdLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)\n\n\nclass TestThresholdLearner(unittest.TestCase):\n    @patch(\"Orange.evaluation.performance_curves.Curves.from_results\")\n    @patch(\"Orange.classification.calibration.TestOnTrainingData\")\n    def test_fit_storage(self, test_on_training, curves_from_results):\n        curves_from_results.return_value = curves = Mock()\n        curves.probs = np.array([0.1, 0.15, 0.3, 0.45, 0.6, 0.8])\n        curves.ca = lambda: np.array([0.1, 0.7, 0.4, 0.4, 0.3, 0.1])\n        curves.f1 = lambda: np.array([0.1, 0.2, 0.4, 0.4, 0.3, 0.1])\n        model = Mock()\n        model.domain.class_var.is_discrete = True\n        model.domain.class_var.values = (\"a\", \"b\")\n        data = Table(\"heart_disease\")\n        learner = Mock()\n        test_on_training.return_value = tot = Mock()\n        res = Mock()\n        res.models = np.array([[model]])\n        tot.return_value = res\n\n        thresh_learner = ThresholdLearner(\n            base_learner=learner,\n            threshold_criterion=ThresholdLearner.OptimizeCA)\n        thresh_model = thresh_learner(data)\n        self.assertEqual(thresh_model.threshold, 0.15)\n        args, _ = tot.call_args  # pylint: disable=unpacking-non-sequence\n        self.assertEqual(len(args), 2)\n        self.assertIs(args[0], data)\n        self.assertIs(args[1][0], learner)\n\n        _, kwargs = test_on_training.call_args\n        self.assertEqual(len(args[1]), 1)\n        self.assertEqual(kwargs, {\"store_models\": 1})\n\n        thresh_learner = ThresholdLearner(\n            base_learner=learner,\n            threshold_criterion=ThresholdLearner.OptimizeF1)\n        thresh_model = thresh_learner(data)\n        self.assertEqual(thresh_model.threshold, 0.45)\n\n    def test_non_binary_class(self):\n        thresh_learner = ThresholdLearner(\n            base_learner=Mock(),\n            threshold_criterion=ThresholdLearner.OptimizeF1)\n\n        data = Mock()\n        data.domain.class_var.is_discrete = True\n        data.domain.class_var.values = [\"a\"]\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n        data.domain.class_var.values = [\"a\", \"b\", \"c\"]\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n        data.domain.class_var = Mock()\n        data.domain.class_var.is_discrete = False\n        self.assertRaises(ValueError, thresh_learner.fit_storage, data)\n\n\nclass TestCalibratedClassifier(unittest.TestCase):\n    def setUp(self):\n        probs1 = np.array([0.3, 0.5, 0.2, 0.8, 0.9, 0]).reshape(-1, 1)\n        self.probs = np.hstack((1 - probs1, probs1))\n        base_model = Mock(return_value=self.probs)\n        base_model.domain.class_var.is_discrete = True\n        base_model.domain.class_var.values = [\"a\", \"b\"]\n        self.model = CalibratedClassifier(base_model, None)\n        self.data = Mock()\n\n    def test_call(self):\n        calprobs = np.arange(self.probs.size).reshape(self.probs.shape)\n        calprobs = calprobs / np.sum(calprobs, axis=1)[:, None]\n        calprobs[-1] = [0.7, 0.3]\n        self.model.calibrated_probs = Mock(return_value=calprobs)\n\n        probs = self.model(self.data, ret=Model.Probs)\n        self.model.calibrated_probs.assert_called_with(self.probs)\n        np.testing.assert_almost_equal(probs, calprobs)\n\n        vals = self.model(self.data, ret=Model.Value)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n        vals, probs = self.model(self.data, ret=Model.ValueProbs)\n        np.testing.assert_almost_equal(probs, calprobs)\n        np.testing.assert_almost_equal(vals, [1, 1, 1, 1, 1, 0])\n\n    def test_calibrated_probs(self):\n        self.model.calibrators = None\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_equal(calprobs, self.probs)\n        self.assertIsNot(calprobs, self.probs)\n\n        calibrator = Mock()\n        calibrator.predict = lambda x: x**2\n        self.model.calibrators = [calibrator] * 2\n        calprobs = self.model.calibrated_probs(self.probs)\n        expprobs = self.probs ** 2 / np.sum(self.probs ** 2, axis=1)[:, None]\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n        self.probs[1] = 0\n        self.probs[2] = np.nan\n        expprobs[1] = 0.5\n        expprobs[2] = np.nan\n        calprobs = self.model.calibrated_probs(self.probs)\n        np.testing.assert_almost_equal(calprobs, expprobs)\n\n    def test_np_data(self):\n        \"\"\"\n        Test CalibratedClassifier with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = CalibratedLearner(base_learner)(data)\n        res = model(model.data_to_model_domain(data).X)\n        self.assertTupleEqual((len(data),), res.shape)\n\n\nclass TestCalibratedLearner(unittest.TestCase):\n    @patch(\"Orange.classification.calibration._SigmoidCalibration.fit\")\n    @patch(\"Orange.classification.calibration.TestOnTrainingData\")\n    def test_fit_storage(self, test_on_training, sigmoid_fit):\n        data = Table(\"heart_disease\")\n        learner = Mock()\n\n        model = Mock()\n        model.domain.class_var.is_discrete = True\n        model.domain.class_var.values = (\"a\", \"b\")\n\n        test_on_training.return_value = tot = Mock()\n        res = Mock()\n        res.models = np.array([[model]])\n        res.probabilities = np.arange(20, dtype=float).reshape(1, 5, 4)\n        tot.return_value = res\n\n        sigmoid_fit.return_value = Mock()\n\n        cal_learner = CalibratedLearner(\n            base_learner=learner, calibration_method=CalibratedLearner.Sigmoid)\n        cal_model = cal_learner(data)\n\n        self.assertIs(cal_model.base_model, model)\n        self.assertEqual(cal_model.calibrators, [sigmoid_fit.return_value] * 4)\n        args, _ = tot.call_args  # pylint: disable=unpacking-non-sequence\n        self.assertEqual(len(args), 2)\n        self.assertIs(args[0], data)\n        self.assertIs(args[1][0], learner)\n        self.assertEqual(len(args[1]), 1)\n\n        _, kwargs = test_on_training.call_args\n        self.assertEqual(kwargs, {\"store_models\": 1})\n\n        for call, cls_probs in zip(sigmoid_fit.call_args_list,\n                                   res.probabilities[0].T):\n            np.testing.assert_equal(call[0][0], cls_probs)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Orange installation attempts...\nAttempting installation with Python 3.7...\nrunning build_ext\nCompiling Orange/classification/_tree_scorers.pyx because it changed.\nCompiling Orange/data/_contingency.pyx because it changed.\nCompiling Orange/data/_io.pyx because it changed.\nCompiling Orange/data/_valuecount.pyx because it changed.\nCompiling Orange/data/_variable.pyx because it changed.\nCompiling Orange/distance/_distance.pyx because it changed.\nCompiling Orange/preprocess/_discretize.pyx because it changed.\nCompiling Orange/preprocess/_relieff.pyx because it changed.\nCompiling Orange/projection/_som.pyx because it changed.\n[1/9] Cythonizing Orange/classification/_tree_scorers.pyx\n[2/9] Cythonizing Orange/data/_contingency.pyx\n[3/9] Cythonizing Orange/data/_io.pyx\n[4/9] Cythonizing Orange/data/_valuecount.pyx\n[5/9] Cythonizing Orange/data/_variable.pyx\n[6/9] Cythonizing Orange/distance/_distance.pyx\n[7/9] Cythonizing Orange/preprocess/_discretize.pyx\n[8/9] Cythonizing Orange/preprocess/_relieff.pyx\n[9/9] Cythonizing Orange/projection/_som.pyx\nbuilding 'Orange.classification._tree_scorers' extension\ncreating build\ncreating build/temp.linux-x86_64-3.7\ncreating build/temp.linux-x86_64-3.7/Orange\ncreating build/temp.linux-x86_64-3.7/Orange/classification\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/classification/_tree_scorers.c -o build/temp.linux-x86_64-3.7/Orange/classification/_tree_scorers.o\ncreating build/lib.linux-x86_64-3.7\ncreating build/lib.linux-x86_64-3.7/Orange\ncreating build/lib.linux-x86_64-3.7/Orange/classification\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_tree_scorers.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._contingency' extension\ncreating build/temp.linux-x86_64-3.7/Orange/data\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_contingency.c -o build/temp.linux-x86_64-3.7/Orange/data/_contingency.o\ncreating build/lib.linux-x86_64-3.7/Orange/data\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_contingency.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._io' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_io.c -o build/temp.linux-x86_64-3.7/Orange/data/_io.o\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_io.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/data/_io.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._valuecount' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_valuecount.c -o build/temp.linux-x86_64-3.7/Orange/data/_valuecount.o\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_valuecount.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.data._variable' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/data/_variable.c -o build/temp.linux-x86_64-3.7/Orange/data/_variable.o\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/data/_variable.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.distance._distance' extension\ncreating build/temp.linux-x86_64-3.7/Orange/distance\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/distance/_distance.c -o build/temp.linux-x86_64-3.7/Orange/distance/_distance.o\ncreating build/lib.linux-x86_64-3.7/Orange/distance\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/distance/_distance.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._discretize' extension\ncreating build/temp.linux-x86_64-3.7/Orange/preprocess\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/preprocess/_discretize.c -o build/temp.linux-x86_64-3.7/Orange/preprocess/_discretize.o\ncreating build/lib.linux-x86_64-3.7/Orange/preprocess\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_discretize.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.preprocess._relieff' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/preprocess/_relieff.cpp -o build/temp.linux-x86_64-3.7/Orange/preprocess/_relieff.o\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/preprocess/_relieff.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.projection._som' extension\ncreating build/temp.linux-x86_64-3.7/Orange/projection\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/projection/_som.c -o build/temp.linux-x86_64-3.7/Orange/projection/_som.o\ncreating build/lib.linux-x86_64-3.7/Orange/projection\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/projection/_som.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.classification._simple_tree' extension\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/classification/_simple_tree.c -o build/temp.linux-x86_64-3.7/Orange/classification/_simple_tree.o\ncc -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/classification/_simple_tree.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so\nbuilding 'Orange.widgets.utils._grid_density' extension\ncreating build/temp.linux-x86_64-3.7/Orange/widgets\ncreating build/temp.linux-x86_64-3.7/Orange/widgets/utils\ncc -pthread -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -I/tools/deps/include -I/tools/deps/include/ncursesw -fPIC -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include -I/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/include -I/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/include/python3.7m -c Orange/widgets/utils/_grid_density.cpp -o build/temp.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.o\ncreating build/lib.linux-x86_64-3.7/Orange/widgets\ncreating build/lib.linux-x86_64-3.7/Orange/widgets/utils\nc++ -pthread -shared -L/tools/deps/lib build/temp.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.o -L/home/gcpuser/.local/share/uv/python/cpython-3.7.9-linux-x86_64-gnu/lib -lm -lpython3.7m -o build/lib.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_io.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so -> Orange/distance\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so -> Orange/projection\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so -> Orange/widgets/utils\nrunning develop\nrunning egg_info\ncreating Orange3.egg-info\nwriting Orange3.egg-info/PKG-INFO\nwriting dependency_links to Orange3.egg-info/dependency_links.txt\nwriting entry points to Orange3.egg-info/entry_points.txt\nwriting requirements to Orange3.egg-info/requires.txt\nwriting top-level names to Orange3.egg-info/top_level.txt\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest file 'Orange3.egg-info/SOURCES.txt'\nreading manifest template 'MANIFEST.in'\nadding license file 'LICENSE'\nwriting manifest file 'Orange3.egg-info/SOURCES.txt'\nrunning build_ext\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_tree_scorers.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/data/_contingency.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_io.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_valuecount.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/data/_variable.cpython-37m-x86_64-linux-gnu.so -> Orange/data\ncopying build/lib.linux-x86_64-3.7/Orange/distance/_distance.cpython-37m-x86_64-linux-gnu.so -> Orange/distance\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_discretize.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/preprocess/_relieff.cpython-37m-x86_64-linux-gnu.so -> Orange/preprocess\ncopying build/lib.linux-x86_64-3.7/Orange/projection/_som.cpython-37m-x86_64-linux-gnu.so -> Orange/projection\ncopying build/lib.linux-x86_64-3.7/Orange/classification/_simple_tree.cpython-37m-x86_64-linux-gnu.so -> Orange/classification\ncopying build/lib.linux-x86_64-3.7/Orange/widgets/utils/_grid_density.cpython-37m-x86_64-linux-gnu.so -> Orange/widgets/utils\nCreating /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/Orange3.egg-link (link to .)\nAdding Orange3 3.28.0.dev0+6791ae2 to easy-install.pth file\nInstalling orange-canvas script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nInstalled /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a\nProcessing dependencies for Orange3==3.28.0.dev0+6791ae2\nSearching for XlsxWriter==3.2.0\nBest match: XlsxWriter 3.2.0\nAdding XlsxWriter 3.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for xlrd==2.0.1\nBest match: xlrd 2.0.1\nAdding xlrd 2.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for setuptools==59.8.0\nBest match: setuptools 59.8.0\nAdding setuptools 59.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for serverfiles==0.3.1\nBest match: serverfiles 0.3.1\nAdding serverfiles 0.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for scipy==1.7.3\nBest match: scipy 1.7.3\nAdding scipy 1.7.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for scikit-learn==1.0.2\nBest match: scikit-learn 1.0.2\nAdding scikit-learn 1.0.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for requests==2.31.0\nBest match: requests 2.31.0\nAdding requests 2.31.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for PyYAML==6.0.1\nBest match: PyYAML 6.0.1\nAdding PyYAML 6.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for python-louvain==0.16\nBest match: python-louvain 0.16\nAdding python-louvain 0.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for pyqtgraph==0.12.4\nBest match: pyqtgraph 0.12.4\nAdding pyqtgraph 0.12.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for pip==24.0\nBest match: pip 24.0\nAdding pip 24.0 to easy-install.pth file\nInstalling pip script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling pip3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling pip3.10 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for pandas==1.3.5\nBest match: pandas 1.3.5\nAdding pandas 1.3.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for orange-widget-base==4.22.0\nBest match: orange-widget-base 4.22.0\nAdding orange-widget-base 4.22.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for orange-canvas-core==0.1.35\nBest match: orange-canvas-core 0.1.35\nAdding orange-canvas-core 0.1.35 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for openpyxl==3.1.3\nBest match: openpyxl 3.1.3\nAdding openpyxl 3.1.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for openTSNE==1.0.1\nBest match: openTSNE 1.0.1\nAdding openTSNE 1.0.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for numpy==1.17.5\nBest match: numpy 1.17.5\nAdding numpy 1.17.5 to easy-install.pth file\nInstalling f2py script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling f2py3 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling f2py3.7 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for networkx==2.6.3\nBest match: networkx 2.6.3\nAdding networkx 2.6.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for matplotlib==3.5.3\nBest match: matplotlib 3.5.3\nAdding matplotlib 3.5.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for keyrings.alt==4.2.0\nBest match: keyrings.alt 4.2.0\nAdding keyrings.alt 4.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for keyring==24.1.1\nBest match: keyring 24.1.1\nAdding keyring 24.1.1 to easy-install.pth file\nInstalling keyring script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for joblib==1.3.2\nBest match: joblib 1.3.2\nAdding joblib 1.3.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for httpx==0.16.1\nBest match: httpx 0.16.1\nAdding httpx 0.16.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for chardet==5.2.0\nBest match: chardet 5.2.0\nAdding chardet 5.2.0 to easy-install.pth file\nInstalling chardetect script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for Bottleneck==1.4.0\nBest match: Bottleneck 1.4.0\nAdding Bottleneck 1.4.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for baycomp==1.0.3\nBest match: baycomp 1.0.3\nAdding baycomp 1.0.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for PyQtWebEngine==5.15.6\nBest match: PyQtWebEngine 5.15.6\nAdding PyQtWebEngine 5.15.6 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for PyQt5==5.15.10\nBest match: PyQt5 5.15.10\nAdding PyQt5 5.15.10 to easy-install.pth file\nInstalling pylupdate5 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling pyrcc5 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling pyuic5 script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for AnyQt==0.2.0\nBest match: AnyQt 0.2.0\nAdding AnyQt 0.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for threadpoolctl==3.1.0\nBest match: threadpoolctl 3.1.0\nAdding threadpoolctl 3.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for charset-normalizer==3.4.1\nBest match: charset-normalizer 3.4.1\nAdding charset-normalizer 3.4.1 to easy-install.pth file\nInstalling normalizer script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for urllib3==2.0.7\nBest match: urllib3 2.0.7\nAdding urllib3 2.0.7 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for certifi==2024.12.14\nBest match: certifi 2024.12.14\nAdding certifi 2024.12.14 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for idna==3.10\nBest match: idna 3.10\nAdding idna 3.10 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for pytz==2024.2\nBest match: pytz 2024.2\nAdding pytz 2024.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for python-dateutil==2.9.0.post0\nBest match: python-dateutil 2.9.0.post0\nAdding python-dateutil 2.9.0.post0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for typing-extensions==4.7.1\nBest match: typing-extensions 4.7.1\nAdding typing-extensions 4.7.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for qasync==0.25.0\nBest match: qasync 0.25.0\nAdding qasync 0.25.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for packaging==24.0\nBest match: packaging 24.0\nAdding packaging 24.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for requests-cache==1.1.1\nBest match: requests-cache 1.1.1\nAdding requests-cache 1.1.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for commonmark==0.9.1\nBest match: commonmark 0.9.1\nAdding commonmark 0.9.1 to easy-install.pth file\nInstalling cmark script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for importlib-metadata==6.7.0\nBest match: importlib-metadata 6.7.0\nAdding importlib-metadata 6.7.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for docutils==0.20.1\nBest match: docutils 0.20.1\nAdding docutils 0.20.1 to easy-install.pth file\nInstalling docutils script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for dictdiffer==0.9.0\nBest match: dictdiffer 0.9.0\nAdding dictdiffer 0.9.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for et-xmlfile==1.1.0\nBest match: et-xmlfile 1.1.0\nAdding et-xmlfile 1.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for pyparsing==3.1.4\nBest match: pyparsing 3.1.4\nAdding pyparsing 3.1.4 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for cycler==0.11.0\nBest match: cycler 0.11.0\nAdding cycler 0.11.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for fonttools==4.38.0\nBest match: fonttools 4.38.0\nAdding fonttools 4.38.0 to easy-install.pth file\nInstalling fonttools script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling pyftmerge script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling pyftsubset script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\nInstalling ttx script to /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/bin\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for kiwisolver==1.4.5\nBest match: kiwisolver 1.4.5\nAdding kiwisolver 1.4.5 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for Pillow==9.5.0\nBest match: Pillow 9.5.0\nAdding Pillow 9.5.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for jaraco.classes==3.2.3\nBest match: jaraco.classes 3.2.3\nAdding jaraco.classes 3.2.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for importlib-resources==5.12.0\nBest match: importlib-resources 5.12.0\nAdding importlib-resources 5.12.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for jeepney==0.8.0\nBest match: jeepney 0.8.0\nAdding jeepney 0.8.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for SecretStorage==3.3.3\nBest match: SecretStorage 3.3.3\nAdding SecretStorage 3.3.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for rfc3986==1.5.0\nBest match: rfc3986 1.5.0\nAdding rfc3986 1.5.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for httpcore==0.12.3\nBest match: httpcore 0.12.3\nAdding httpcore 0.12.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for sniffio==1.3.1\nBest match: sniffio 1.3.1\nAdding sniffio 1.3.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for PyQtWebEngine-Qt5==5.15.16\nBest match: PyQtWebEngine-Qt5 5.15.16\nAdding PyQtWebEngine-Qt5 5.15.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for PyQt5-sip==12.13.0\nBest match: PyQt5-sip 12.13.0\nAdding PyQt5-sip 12.13.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for PyQt5-Qt5==5.15.16\nBest match: PyQt5-Qt5 5.15.16\nAdding PyQt5-Qt5 5.15.16 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for six==1.17.0\nBest match: six 1.17.0\nAdding six 1.17.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for cattrs==23.1.2\nBest match: cattrs 23.1.2\nAdding cattrs 23.1.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for platformdirs==4.0.0\nBest match: platformdirs 4.0.0\nAdding platformdirs 4.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for attrs==24.2.0\nBest match: attrs 24.2.0\nAdding attrs 24.2.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for url-normalize==1.4.3\nBest match: url-normalize 1.4.3\nAdding url-normalize 1.4.3 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for zipp==3.15.0\nBest match: zipp 3.15.0\nAdding zipp 3.15.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for more-itertools==9.1.0\nBest match: more-itertools 9.1.0\nAdding more-itertools 9.1.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for cryptography==44.0.0\nBest match: cryptography 44.0.0\nAdding cryptography 44.0.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for h11==0.14.0\nBest match: h11 0.14.0\nAdding h11 0.14.0 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for exceptiongroup==1.2.2\nBest match: exceptiongroup 1.2.2\nAdding exceptiongroup 1.2.2 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for cffi==1.15.1\nBest match: cffi 1.15.1\nAdding cffi 1.15.1 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nSearching for pycparser==2.21\nBest match: pycparser 2.21\nAdding pycparser 2.21 to easy-install.pth file\n\nUsing /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages\nFinished processing dependencies for Orange3==3.28.0.dev0+6791ae2\nVerifying Orange installation...\n✅ Orange installation successful!\nSuccessfully installed orange using Python 3.7\n",
    "setup_res_stderr": "Using CPython 3.7.9\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 18 packages in 63ms\nPrepared 18 packages in 13ms\nInstalled 18 packages in 88ms\n + cython==0.29.37\n + exceptiongroup==1.2.2\n + importlib-metadata==6.7.0\n + iniconfig==2.0.0\n + numpy==1.17.5\n + packaging==24.0\n + pluggy==1.2.0\n + pyqt5==5.15.10\n + pyqt5-qt5==5.15.16\n + pyqt5-sip==12.13.0\n + pyqtwebengine==5.15.6\n + pyqtwebengine-qt5==5.15.16\n + pytest==7.4.4\n + setuptools==59.8.0\n + tomli==2.0.1\n + typing-extensions==4.7.1\n + wheel==0.42.0\n + zipp==3.15.0\nResolved 53 packages in 410ms\nInstalled 47 packages in 1.11s\n + baycomp==1.0.3\n + bottleneck==1.4.0\n + certifi==2024.12.14\n + cffi==1.15.1\n + chardet==5.2.0\n + charset-normalizer==3.4.1\n + cryptography==44.0.0\n + cycler==0.11.0\n + et-xmlfile==1.1.0\n + fonttools==4.38.0\n + h11==0.14.0\n + httpcore==0.12.3\n + httpx==0.16.1\n + idna==3.10\n + importlib-resources==5.12.0\n + jaraco-classes==3.2.3\n + jeepney==0.8.0\n + joblib==1.3.2\n + keyring==24.1.1\n + keyrings-alt==4.2.0\n + kiwisolver==1.4.5\n + matplotlib==3.5.3\n + more-itertools==9.1.0\n + networkx==2.6.3\n + openpyxl==3.1.3\n + opentsne==1.0.1\n + pandas==1.3.5\n + pillow==9.5.0\n + pip==24.0\n + pycparser==2.21\n + pyparsing==3.1.4\n + python-dateutil==2.9.0.post0\n + python-louvain==0.16\n + pytz==2024.2\n + pyyaml==6.0.1\n + requests==2.31.0\n + rfc3986==1.5.0\n + scikit-learn==1.0.2\n + scipy==1.7.3\n + secretstorage==3.3.3\n + serverfiles==0.3.1\n + six==1.17.0\n + sniffio==1.3.1\n + threadpoolctl==3.1.0\n + urllib3==2.0.7\n + xlrd==2.0.1\n + xlsxwriter==3.2.0\nResolved 39 packages in 65ms\nInstalled 13 packages in 173ms\n + anyqt==0.2.0\n + attrs==24.2.0\n + cattrs==23.1.2\n + commonmark==0.9.1\n + dictdiffer==0.9.0\n + docutils==0.20.1\n + orange-canvas-core==0.1.35\n + orange-widget-base==4.22.0\n + platformdirs==4.0.0\n + pyqtgraph==0.12.4\n + qasync==0.25.0\n + requests-cache==1.1.1\n + url-normalize==1.4.3\nResolved 2 packages in 4ms\nInstalled 2 packages in 12ms\n + psycopg2==2.9.9\n + pymssql==2.3.2\nResolved 19 packages in 92ms\nInstalled 5 packages in 1.35s\n + catboost==1.2.7\n + graphviz==0.20.1\n + plotly==5.18.0\n + tenacity==8.2.3\n + xgboost==1.6.2\nAudited 2 packages in 1ms\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/classification/_tree_scorers.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_2find_threshold_entropy’:\nOrange/classification/_tree_scorers.c:3413:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 3413 |   __pyx_t_7 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_6find_threshold_MSE’:\nOrange/classification/_tree_scorers.c:4869:27: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 4869 |   __pyx_t_1 = ((__pyx_v_N <= __pyx_v_min_leaf) != 0);\n      |                           ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_8find_binarization_MSE’:\nOrange/classification/_tree_scorers.c:5615:43: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5615 |           for (__pyx_t_19 = 0; __pyx_t_19 < __pyx_t_18; __pyx_t_19+=1) {\n      |                                           ^\nOrange/classification/_tree_scorers.c:5736:39: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5736 |           __pyx_t_20 = ((__pyx_v_left >= __pyx_v_min_leaf) != 0);\n      |                                       ^~\nOrange/classification/_tree_scorers.c:5742:53: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 5742 |           __pyx_t_20 = (((__pyx_v_N - __pyx_v_left) >= __pyx_v_min_leaf) != 0);\n      |                                                     ^~\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_14compute_predictions_csr’:\nOrange/classification/_tree_scorers.c:7202:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7202 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c: In function ‘__pyx_pf_6Orange_14classification_13_tree_scorers_16compute_predictions_csc’:\nOrange/classification/_tree_scorers.c:7857:41: warning: comparison of integer expressions of different signedness: ‘unsigned int’ and ‘int’ [-Wsign-compare]\n 7857 |         for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_10; __pyx_t_11+=1) {\n      |                                         ^\nOrange/classification/_tree_scorers.c:7917:143: warning: comparison of integer expressions of different signedness: ‘__pyx_t_5numpy_int32_t’ {aka ‘int’} and ‘unsigned int’ [-Wsign-compare]\n 7917 |               __pyx_t_15 = (((*((__pyx_t_5numpy_int32_t *) ( /* dim=0 */ (__pyx_v_indices.data + __pyx_t_14 * __pyx_v_indices.strides[0]) ))) != __pyx_v_i) != 0);\n      |                                                                                                                                               ^~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_contingency.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/data/_io.c: In function ‘__pyx_pf_6Orange_4data_3_io_sparse_read_float.constprop’:\nOrange/data/_io.c:4120:43: warning: ‘__pyx_v_decs’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4120 |           __pyx_v_value = ((__pyx_v_value * __pyx_v_decs) + (__pyx_v_c & 0xf));\n      |                            ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/data/_io.c:4318:24: warning: ‘__pyx_v_value’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4318 |           __pyx_t_10 = PyFloat_FromDouble(__pyx_v_value); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 223, __pyx_L5_error)\n      |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:683:40: warning: ‘__pyx_v_attr_index’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n  683 |   #define PyInt_FromLong               PyLong_FromLong\n      |                                        ^~~~~~~~~~~~~~~\nOrange/data/_io.c:1590:7: note: ‘__pyx_v_attr_index’ was declared here\n 1590 |   int __pyx_v_attr_index;\n      |       ^~~~~~~~~~~~~~~~~~\nOrange/data/_io.c:3183:25: warning: ‘__pyx_v_atomp’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3183 |           __pyx_v_atomp = (__pyx_v_atomp + 1);\n      |           ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/data/_valuecount.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/distance/_distance.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_discretize.c:774:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/preprocess/_relieff.cpp:790:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nIn file included from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1830,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:12,\n                 from /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,\n                 from Orange/projection/_som.c:775:\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning \"Using deprecated NumPy API, disable it with \" \"#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\" [-Wcpp]\n   17 | #warning \"Using deprecated NumPy API, disable it with \" \\\n      |  ^~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_5update_hex’:\nOrange/projection/_som.c:3863:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3863 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:3862:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3862 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_8update_sparse.constprop’:\nOrange/projection/_som.c:4934:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4934 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4933:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4933 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_7get_winners_sparse’:\nOrange/projection/_som.c:4732:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4732 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_27, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4307:7: note: ‘__pyx_v_win_y’ was declared here\n 4307 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:4721:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 4721 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:4306:7: note: ‘__pyx_v_win_x’ was declared here\n 4306 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pf_6Orange_10projection_4_som_10update_sparse_hex.constprop’:\nOrange/projection/_som.c:5682:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5682 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:5681:7: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 5681 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_1get_winners’:\nOrange/projection/_som.c:3184:223: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3184 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_y;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2887:7: note: ‘__pyx_v_win_y’ was declared here\n 2887 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c:3173:223: warning: ‘__pyx_v_win_x’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3173 |           *__Pyx_BufPtrStrided2d(__pyx_t_5numpy_int16_t *, __pyx_pybuffernd_winners.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_winners.diminfo[0].strides, __pyx_t_22, __pyx_pybuffernd_winners.diminfo[1].strides) = __pyx_v_win_x;\n      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~\nOrange/projection/_som.c:2886:7: note: ‘__pyx_v_win_x’ was declared here\n 2886 |   int __pyx_v_win_x;\n      |       ^~~~~~~~~~~~~\nOrange/projection/_som.c: In function ‘__pyx_pw_6Orange_10projection_4_som_3update’:\nOrange/projection/_som.c:3357:7: warning: ‘__pyx_v_win_y’ may be used uninitialized in this function [-Wmaybe-uninitialized]\n 3357 |   int __pyx_v_win_y;\n      |       ^~~~~~~~~~~~~\nOrange/classification/_simple_tree.c: In function ‘gain_ratio_c’:\nOrange/classification/_simple_tree.c:63:9: warning: implicit declaration of function ‘qsort_r’; did you mean ‘qsort’? [-Wimplicit-function-declaration]\n   63 |         qsort_r(base, nel, size, compar, thunk)\n      |         ^~~~~~~\nOrange/classification/_simple_tree.c:147:9: note: in expansion of macro ‘QSORT_R_FUNC’\n  147 |         QSORT_R_FUNC(examples, size, sizeof(struct Example), (void*) &compar_attr, compar_examples);\n      |         ^~~~~~~~~~~~\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/setuptools/command/easy_install.py:159: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.\n  EasyInstallDeprecationWarning,\n/home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a/.venv/lib/python3.7/site-packages/setuptools/command/install.py:37: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.\n  setuptools.SetuptoolsDeprecationWarning,\nwarning: no files found matching 'README*' under directory 'Orange'\nwarning: no files found matching 'LICENSE' under directory 'Orange'\nwarning: no files found matching '*.basket' under directory 'Orange/datasets'\nwarning: no files found matching '*.js' under directory 'Orange/widgets'\nwarning: no files found matching '*.css' under directory 'Orange/widgets'\nwarning: no files found matching '*.html' under directory 'Orange/widgets'\nwarning: no files found matching 'COPYING'\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a\ncollected 11 items\n\nr2e_tests/test_1.py ...........                                          [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_nans\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_non_binary_base\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_np_data\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_return_types\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_threshold\nPASSED r2e_tests/test_1.py::TestThresholdLearner::test_fit_storage\nPASSED r2e_tests/test_1.py::TestThresholdLearner::test_non_binary_class\nPASSED r2e_tests/test_1.py::TestCalibratedClassifier::test_calibrated_probs\nPASSED r2e_tests/test_1.py::TestCalibratedClassifier::test_call\nPASSED r2e_tests/test_1.py::TestCalibratedClassifier::test_np_data\nPASSED r2e_tests/test_1.py::TestCalibratedLearner::test_fit_storage\n============================== 11 passed in 3.70s ==============================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.7.9, pytest-7.4.4, pluggy-1.2.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/orange3_6791ae20d003b4d1c5adae8097dd53a08141d07a\ncollected 11 items\n\nr2e_tests/test_1.py ..F......F.                                          [100%]\n\n=================================== FAILURES ===================================\n_____________________ TestThresholdClassifier.test_np_data _____________________\n\nself = <r2e_tests.test_1.TestThresholdClassifier testMethod=test_np_data>\n\n    def test_np_data(self):\n        \"\"\"\n        Test ThresholdModel with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = ThresholdLearner(base_learner)(data)\n>       res = model(model.data_to_model_domain(data).X)\n\nr2e_tests/test_1.py:78: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/classification/calibration.py:35: in __call__\n    probs = self.base_model(data, ret=Model.Probs)\nOrange/base.py:436: in __call__\n    prediction = self.predict(data)\nOrange/base.py:499: in predict\n    value = self.skl_model.predict(X)\n.venv/lib/python3.7/site-packages/sklearn/linear_model/_base.py:425: in predict\n    scores = self.decision_function(X)\n.venv/lib/python3.7/site-packages/sklearn/linear_model/_base.py:407: in decision_function\n    X = self._validate_data(X, accept_sparse=\"csr\", reset=False)\n.venv/lib/python3.7/site-packages/sklearn/base.py:566: in _validate_data\n    X = check_array(X, **check_params)\n.venv/lib/python3.7/site-packages/sklearn/utils/validation.py:800: in check_array\n    _assert_all_finite(array, allow_nan=force_all_finite == \"allow-nan\")\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nX = array([[63.,  1.,  3., ...,  2.,  0.,  2.],\n       [67.,  1.,  0., ...,  1.,  3.,  0.],\n       [67.,  1.,  0., ...,  1... 1.,  0., ...,  1.,  1.,  1.],\n       [57.,  0.,  1., ...,  1.,  1.,  0.],\n       [38.,  1.,  2., ...,  0., nan,  0.]])\nallow_nan = False, msg_dtype = None\n\n    def _assert_all_finite(X, allow_nan=False, msg_dtype=None):\n        \"\"\"Like assert_all_finite, but only for ndarray.\"\"\"\n        # validation is also imported in extmath\n        from .extmath import _safe_accumulator_op\n    \n        if _get_config()[\"assume_finite\"]:\n            return\n        X = np.asanyarray(X)\n        # First try an O(n) time, O(1) space solution for the common case that\n        # everything is finite; fall back to O(n) space np.isfinite to prevent\n        # false positives from overflow in sum method. The sum is also calculated\n        # safely to reduce dtype induced overflows.\n        is_float = X.dtype.kind in \"fc\"\n        if is_float and (np.isfinite(_safe_accumulator_op(np.sum, X))):\n            pass\n        elif is_float:\n            msg_err = \"Input contains {} or a value too large for {!r}.\"\n            if (\n                allow_nan\n                and np.isinf(X).any()\n                or not allow_nan\n                and not np.isfinite(X).all()\n            ):\n                type_err = \"infinity\" if allow_nan else \"NaN, infinity\"\n                raise ValueError(\n                    msg_err.format(\n>                       type_err, msg_dtype if msg_dtype is not None else X.dtype\n                    )\n                )\nE               ValueError: Input contains NaN, infinity or a value too large for dtype('float64').\n\n.venv/lib/python3.7/site-packages/sklearn/utils/validation.py:116: ValueError\n____________________ TestCalibratedClassifier.test_np_data _____________________\n\nself = <r2e_tests.test_1.TestCalibratedClassifier testMethod=test_np_data>\n\n    def test_np_data(self):\n        \"\"\"\n        Test CalibratedClassifier with numpy data.\n        When passing numpy data to model they should be already\n        transformed to models domain since model do not know how to do it.\n        \"\"\"\n        data = Table('heart_disease')\n        base_learner = LogisticRegressionLearner()\n        model = CalibratedLearner(base_learner)(data)\n>       res = model(model.data_to_model_domain(data).X)\n\nr2e_tests/test_1.py:194: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \nOrange/classification/calibration.py:108: in __call__\n    probs = self.base_model(data, Model.Probs)\nOrange/base.py:436: in __call__\n    prediction = self.predict(data)\nOrange/base.py:499: in predict\n    value = self.skl_model.predict(X)\n.venv/lib/python3.7/site-packages/sklearn/linear_model/_base.py:425: in predict\n    scores = self.decision_function(X)\n.venv/lib/python3.7/site-packages/sklearn/linear_model/_base.py:407: in decision_function\n    X = self._validate_data(X, accept_sparse=\"csr\", reset=False)\n.venv/lib/python3.7/site-packages/sklearn/base.py:566: in _validate_data\n    X = check_array(X, **check_params)\n.venv/lib/python3.7/site-packages/sklearn/utils/validation.py:800: in check_array\n    _assert_all_finite(array, allow_nan=force_all_finite == \"allow-nan\")\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nX = array([[63.,  1.,  3., ...,  2.,  0.,  2.],\n       [67.,  1.,  0., ...,  1.,  3.,  0.],\n       [67.,  1.,  0., ...,  1... 1.,  0., ...,  1.,  1.,  1.],\n       [57.,  0.,  1., ...,  1.,  1.,  0.],\n       [38.,  1.,  2., ...,  0., nan,  0.]])\nallow_nan = False, msg_dtype = None\n\n    def _assert_all_finite(X, allow_nan=False, msg_dtype=None):\n        \"\"\"Like assert_all_finite, but only for ndarray.\"\"\"\n        # validation is also imported in extmath\n        from .extmath import _safe_accumulator_op\n    \n        if _get_config()[\"assume_finite\"]:\n            return\n        X = np.asanyarray(X)\n        # First try an O(n) time, O(1) space solution for the common case that\n        # everything is finite; fall back to O(n) space np.isfinite to prevent\n        # false positives from overflow in sum method. The sum is also calculated\n        # safely to reduce dtype induced overflows.\n        is_float = X.dtype.kind in \"fc\"\n        if is_float and (np.isfinite(_safe_accumulator_op(np.sum, X))):\n            pass\n        elif is_float:\n            msg_err = \"Input contains {} or a value too large for {!r}.\"\n            if (\n                allow_nan\n                and np.isinf(X).any()\n                or not allow_nan\n                and not np.isfinite(X).all()\n            ):\n                type_err = \"infinity\" if allow_nan else \"NaN, infinity\"\n                raise ValueError(\n                    msg_err.format(\n>                       type_err, msg_dtype if msg_dtype is not None else X.dtype\n                    )\n                )\nE               ValueError: Input contains NaN, infinity or a value too large for dtype('float64').\n\n.venv/lib/python3.7/site-packages/sklearn/utils/validation.py:116: ValueError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_nans\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_non_binary_base\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_return_types\nPASSED r2e_tests/test_1.py::TestThresholdClassifier::test_threshold\nPASSED r2e_tests/test_1.py::TestThresholdLearner::test_fit_storage\nPASSED r2e_tests/test_1.py::TestThresholdLearner::test_non_binary_class\nPASSED r2e_tests/test_1.py::TestCalibratedClassifier::test_calibrated_probs\nPASSED r2e_tests/test_1.py::TestCalibratedClassifier::test_call\nPASSED r2e_tests/test_1.py::TestCalibratedLearner::test_fit_storage\nFAILED r2e_tests/test_1.py::TestThresholdClassifier::test_np_data - ValueErro...\nFAILED r2e_tests/test_1.py::TestCalibratedClassifier::test_np_data - ValueErr...\n========================= 2 failed, 9 passed in 2.11s ==========================\n",
    "old_commit_res_stderr": ""
}
Orange/base.py Orange/classification/tests/test_calibration.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Calibration Overwrites Model Domain Incorrectly, Causing Prediction Errors with NumPy Data

**Description**
When using Calibration learners, the model's domain is being overwritten regardless of whether it was previously set. This leads to improper data transformations when passing NumPy arrays, resulting in invalid inputs for prediction methods.

**Example Buggy Code:**
```python
from Orange.classification import LogisticRegressionLearner, CalibratedLearner
from Orange.data import Table

data = Table('heart_disease')
base_learner = LogisticRegressionLearner()
model = CalibratedLearner(base_learner)(data)
predictions = model(model.data_to_model_domain(data).X)
```
In this example, the `CalibratedLearner` incorrectly sets `model.domain` to `data.domain` even if `model.domain` is already defined. As a result, the NumPy data passed to the model is not properly transformed, introducing `NaN` values.

**Expected Behavior**
The `CalibratedLearner` should respect the existing `model.domain` if it is already set and not overwrite it. This ensures that NumPy data is correctly transformed according to the model's domain, preventing the introduction of `NaN` or infinite values during predictions.

**Actual Behavior**
The `CalibratedLearner` overwrites `model.domain` unconditionally, leading to improper data transformations. When making predictions with NumPy data, this results in `ValueError` due to the presence of `NaN` or infinite values in the input.

**Error Message:**
```
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
```

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/base.py
import inspect
import itertools
from collections.abc import Iterable
import re
import warnings
from typing import Callable, Dict

import numpy as np
import scipy

from Orange.data import Table, Storage, Instance, Value
from Orange.data.filter import HasClass
from Orange.data.table import DomainTransformationError
from Orange.data.util import one_hot
from Orange.misc.environ import cache_dir
from Orange.misc.wrapper_meta import WrapperMeta
from Orange.preprocess import Continuize, RemoveNaNColumns, SklImpute, Normalize
from Orange.statistics.util import all_nan
from Orange.util import Reprable, OrangeDeprecationWarning, wrap_callback, \
    dummy_callback

__all__ = ["Learner", "Model", "SklLearner", "SklModel",
           "ReprableWithPreprocessors"]


class ReprableWithPreprocessors(Reprable):
    def _reprable_omit_param(self, name, default, value):
        if name == "preprocessors":
            default_cls = type(self).preprocessors
            if value is default or value is default_cls:
                return True
            else:
                try:
                    return all(p1 is p2 for p1, p2 in
                               itertools.zip_longest(value, default_cls))
                except (ValueError, TypeError):
                    return False
        else:
            return super()._reprable_omit_param(name, default, value)


class Learner(ReprableWithPreprocessors):
    """The base learner class.

    Preprocessors can behave in a number of different ways, all of which are
    described here.
    If the user does not pass a preprocessor argument into the Learner
    constructor, the default learner preprocessors are used. We assume the user
    would simply like to get things done without having to worry about
    preprocessors.
    If the user chooses to pass in their own preprocessors, we assume they know
    what they are doing. In this case, only the user preprocessors are used and
    the default preprocessors are ignored.
    In case the user would like to use the default preprocessors as well as
    their own ones, the `use_default_preprocessors` flag should be set.

    Parameters
    ----------
    preprocessors : Preprocessor or tuple[Preprocessor], optional
        User defined preprocessors. If the user specifies their own
        preprocessors, the default ones will not be used, unless the
        `use_default_preprocessors` flag is set.

    Attributes
    ----------
    preprocessors : tuple[Preprocessor] (default None)
        The used defined preprocessors that will be used on any data.
    use_default_preprocessors : bool (default False)
        This flag indicates whether to use the default preprocessors that are
        defined on the Learner class. Since preprocessors can be applied in a
        number of ways
    active_preprocessors : tuple[Preprocessor]
        The processors that will be used when data is passed to the learner.
        This depends on whether the user has passed in their own preprocessors
        and whether the `use_default_preprocessors` flag is set.

        This property is needed mainly because of the `Fitter` class, which can
        not know in advance, which preprocessors it will need to use. Therefore
        this resolves the active preprocessors using a lazy approach.
    params : dict
        The params that the learner is constructed with.

    """
    supports_multiclass = False
    supports_weights = False
    #: A sequence of data preprocessors to apply on data prior to
    #: fitting the model
    preprocessors = ()
    learner_adequacy_err_msg = ''

    def __init__(self, preprocessors=None):
        self.use_default_preprocessors = False
        if isinstance(preprocessors, Iterable):
            self.preprocessors = tuple(preprocessors)
        elif preprocessors:
            self.preprocessors = (preprocessors,)

    def fit(self, X, Y, W=None):
        raise RuntimeError(
            "Descendants of Learner must overload method fit or fit_storage")

    def fit_storage(self, data):
        """Default implementation of fit_storage defaults to calling fit.
        Derived classes must define fit_storage or fit"""
        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None
        return self.fit(X, Y, W)

    def __call__(self, data, progress_callback=None):
        if not self.check_learner_adequacy(data.domain):
            raise ValueError(self.learner_adequacy_err_msg)

        origdomain = data.domain

        if isinstance(data, Instance):
            data = Table(data.domain, [data])
        origdata = data

        if progress_callback is None:
            progress_callback = dummy_callback
        progress_callback(0, "Preprocessing...")
        try:
            cb = wrap_callback(progress_callback, end=0.1)
            data = self.preprocess(data, progress_callback=cb)
        except TypeError:
            data = self.preprocess(data)
            warnings.warn("A keyword argument 'progress_callback' has been "
                          "added to the preprocess() signature. Implementing "
                          "the method without the argument is deprecated and "
                          "will result in an error in the future.",
                          OrangeDeprecationWarning)

        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:
            raise TypeError("%s doesn't support multiple class variables" %
                            self.__class__.__name__)

        progress_callback(0.1, "Fitting...")
        model = self._fit_model(data)
        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]
        model.domain = data.domain
        model.supports_multiclass = self.supports_multiclass
        model.name = self.name
        model.original_domain = origdomain
        model.original_data = origdata
        progress_callback(1)
        return model

    def _fit_model(self, data):
        if type(self).fit is Learner.fit:
            return self.fit_storage(data)
        else:
            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None
            return self.fit(X, Y, W)

    def preprocess(self, data, progress_callback=None):
        """Apply the `preprocessors` to the data"""
        if progress_callback is None:
            progress_callback = dummy_callback
        n_pps = len(list(self.active_preprocessors))
        for i, pp in enumerate(self.active_preprocessors):
            progress_callback(i / n_pps)
            data = pp(data)
        progress_callback(1)
        return data

    @property
    def active_preprocessors(self):
        yield from self.preprocessors
        if (self.use_default_preprocessors and
                self.preprocessors is not type(self).preprocessors):
            yield from type(self).preprocessors

    def check_learner_adequacy(self, _):
        return True

    @property
    def name(self):
        """Return a short name derived from Learner type name"""
        try:
            return self.__name
        except AttributeError:
            name = self.__class__.__name__
            if name.endswith('Learner'):
                name = name[:-len('Learner')]
            if name.endswith('Fitter'):
                name = name[:-len('Fitter')]
            if isinstance(self, SklLearner) and name.startswith('Skl'):
                name = name[len('Skl'):]
            name = name or 'learner'
            # From http://stackoverflow.com/a/1176023/1090455 <3
            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2',
                               re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name)).lower()
            return self.name

    @name.setter
    def name(self, value):
        self.__name = value

    def __str__(self):
        return self.name


class Model(Reprable):
    supports_multiclass = False
    supports_weights = False
    Value = 0
    Probs = 1
    ValueProbs = 2

    def __init__(self, domain=None, original_domain=None):
        self.domain = domain
        if original_domain is not None:
            self.original_domain = original_domain
        else:
            self.original_domain = domain
        self.used_vals = None

    def predict(self, X):
        if type(self).predict_storage is Model.predict_storage:
            raise TypeError("Descendants of Model must overload method predict")
        else:
            Y = np.zeros((len(X), len(self.domain.class_vars)))
            Y[:] = np.nan
            table = Table(self.domain, X, Y)
            return self.predict_storage(table)

    def predict_storage(self, data):
        if isinstance(data, Storage):
            return self.predict(data.X)
        elif isinstance(data, Instance):
            return self.predict(np.atleast_2d(data.x))
        raise TypeError("Unrecognized argument (instance of '{}')"
                        .format(type(data).__name__))

    def get_backmappers(self, data):
        backmappers = []
        n_values = []

        dataclasses = data.domain.class_vars
        modelclasses = self.domain.class_vars
        if not (modelclasses and dataclasses):
            return None, []  # classless model or data; don't touch
        if len(dataclasses) != len(modelclasses):
            raise DomainTransformationError(
                "Mismatching number of model's classes and data classes")
        for dataclass, modelclass in zip(dataclasses, modelclasses):
            if dataclass != modelclass:
                if dataclass.name != modelclass.name:
                    raise DomainTransformationError(
                        f"Model for '{modelclass.name}' "
                        f"cannot predict '{dataclass.name}'")
                else:
                    raise DomainTransformationError(
                        f"Variables '{modelclass.name}' in the model is "
                        "incompatible with the variable of the same name "
                        "in the data.")
            n_values.append(dataclass.is_discrete and len(dataclass.values))
            if dataclass is not modelclass and dataclass.is_discrete:
                backmappers.append(dataclass.get_mapper_from(modelclass))
            else:
                backmappers.append(None)
        if all(x is None for x in backmappers):
            backmappers = None
        return backmappers, n_values

    def backmap_value(self, value, mapped_probs, n_values, backmappers):
        if backmappers is None:
            return value

        if value.ndim == 2:  # For multitarget, recursive call by columns
            new_value = np.zeros(value.shape)
            for i, n_value, backmapper in zip(
                    itertools.count(), n_values, backmappers):
                new_value[:, i] = self.backmap_value(
                    value[:, i], mapped_probs[:, i, :], [n_value], [backmapper])
            return new_value

        backmapper = backmappers[0]
        if backmapper is None:
            return value

        value = backmapper(value)
        nans = np.isnan(value)
        if not np.any(nans) or n_values[0] < 2:
            return value
        if mapped_probs is not None:
            value[nans] = np.argmax(mapped_probs[nans], axis=1)
        else:
            value[nans] = np.random.RandomState(0).choice(
                backmapper(np.arange(0, n_values[0] - 1)),
                (np.sum(nans), ))
        return value

    def backmap_probs(self, probs, n_values, backmappers):
        if backmappers is None:
            return probs

        if probs.ndim == 3:
            new_probs = np.zeros((len(probs), len(n_values), max(n_values)),
                                 dtype=probs.dtype)
            for i, n_value, backmapper in zip(
                    itertools.count(), n_values, backmappers):
                new_probs[:, i, :n_value] = self.backmap_probs(
                    probs[:, i, :], [n_value], [backmapper])
            return new_probs

        backmapper = backmappers[0]
        if backmapper is None:
            return probs
        n_value = n_values[0]
        new_probs = np.zeros((len(probs), n_value), dtype=probs.dtype)
        for col in range(probs.shape[1]):
            target = backmapper(col)
            if not np.isnan(target):
                new_probs[:, int(target)] = probs[:, col]
        tots = np.sum(new_probs, axis=1)
        zero_sum = tots == 0
        new_probs[zero_sum] = 1
        tots[zero_sum] = n_value
        new_probs = new_probs / tots[:, None]
        return new_probs

    def data_to_model_domain(
            self, data: Table, progress_callback: Callable = dummy_callback
    ) -> Table:
        """
        Transforms data to the model domain if possible.

        Parameters
        ----------
        data
            Data to be transformed to the model domain
        progress_callback
            Callback - callable - to report the progress

        Returns
        -------
        Transformed data table

        Raises
        ------
        DomainTransformationError
            Error indicates that transformation is not possible since domains
            are not compatible
        """
        if data.domain == self.domain:
            return data

        progress_callback(0)
        if self.original_domain.attributes != data.domain.attributes \
                and data.X.size \
                and not all_nan(data.X):
            progress_callback(0.5)
            new_data = data.transform(self.original_domain)
            if all_nan(new_data.X):
                raise DomainTransformationError(
                    "domain transformation produced no defined values")
            progress_callback(0.75)
            data = new_data.transform(self.domain)
            progress_callback(1)
            return data

        progress_callback(0.5)
        data = data.transform(self.domain)
        progress_callback(1)
        return data

    def __call__(self, data, ret=Value):
        multitarget = len(self.domain.class_vars) > 1

        def one_hot_probs(value):
            if not multitarget:
                return one_hot(
                    value,
                    dim=len(self.domain.class_var.values)
                    if self.domain is not None else None
                )

            max_card = max(len(c.values) for c in self.domain.class_vars)
            probs = np.zeros(value.shape + (max_card,), float)
            for i in range(len(self.domain.class_vars)):
                probs[:, i, :] = one_hot(value[:, i])
            return probs

        def extend_probabilities(probs):
            """
            Since SklModels and models implementing `fit` and not `fit_storage`
            do not guarantee correct prediction dimensionality, extend
            dimensionality of probabilities when it does not match the number
            of values in the domain.
            """
            class_vars = self.domain.class_vars
            max_values = max(len(cv.values) for cv in class_vars)
            if max_values == probs.shape[-1]:
                return probs

            if not self.supports_multiclass:
                probs = probs[:, np.newaxis, :]

            probs_ext = np.zeros((len(probs), len(class_vars), max_values))
            for c, used_vals in enumerate(self.used_vals):
                for i, cv in enumerate(used_vals):
                    probs_ext[:, c, cv] = probs[:, c, i]

            if not self.supports_multiclass:
                probs_ext = probs_ext[:, 0, :]
            return probs_ext

        def fix_dim(x):
            return x[0] if one_d else x

        if not 0 <= ret <= 2:
            raise ValueError("invalid value of argument 'ret'")
        if ret > 0 and any(v.is_continuous for v in self.domain.class_vars):
            raise ValueError("cannot predict continuous distributions")

        # Convert 1d structures to 2d and remember doing it
        one_d = True
        if isinstance(data, Instance):
            data = Table.from_list(data.domain, [data])
        elif isinstance(data, (list, tuple)) \
                and not isinstance(data[0], (list, tuple)):
            data = [data]
        elif isinstance(data, np.ndarray) and data.ndim == 1:
            data = np.atleast_2d(data)
        else:
            one_d = False

        # if sparse convert to csr_matrix
        if scipy.sparse.issparse(data):
            data = data.tocsr()

        # Call the predictor
        backmappers = None
        n_values = []
        if isinstance(data, (np.ndarray, scipy.sparse.csr.csr_matrix)):
            prediction = self.predict(data)
        elif isinstance(data, Table):
            backmappers, n_values = self.get_backmappers(data)
            data = self.data_to_model_domain(data)
            prediction = self.predict_storage(data)
        elif isinstance(data, (list, tuple)):
            data = Table.from_list(self.original_domain, data)
            data = data.transform(self.domain)
            prediction = self.predict_storage(data)
        else:
            raise TypeError("Unrecognized argument (instance of '{}')"
                            .format(type(data).__name__))

        # Parse the result into value and probs
        if isinstance(prediction, tuple):
            value, probs = prediction
        elif prediction.ndim == 1 + multitarget:
            value, probs = prediction, None
        elif prediction.ndim == 2 + multitarget:
            value, probs = None, prediction
        else:
            raise TypeError("model returned a %i-dimensional array",
                            prediction.ndim)

        # Ensure that we have what we need to return; backmapp everything
        if probs is None and (ret != Model.Value or backmappers is not None):
            probs = one_hot_probs(value)
        if probs is not None:
            probs = extend_probabilities(probs)
            probs = self.backmap_probs(probs, n_values, backmappers)
        if ret != Model.Probs:
            if value is None:
                value = np.argmax(probs, axis=-1)
                # probs are already backmapped
            else:
                value = self.backmap_value(value, probs, n_values, backmappers)

        # Return what we need to
        if ret == Model.Probs:
            return fix_dim(probs)
        if isinstance(data, Instance) and not multitarget:
            value = [Value(self.domain.class_var, value[0])]
        if ret == Model.Value:
            return fix_dim(value)
        else:  # ret == Model.ValueProbs
            return fix_dim(value), fix_dim(probs)

    def __getstate__(self):
        """Skip (possibly large) data when pickling models"""
        state = self.__dict__
        if 'original_data' in state:
            state = state.copy()
            state['original_data'] = None
        return state


class SklModel(Model, metaclass=WrapperMeta):
    used_vals = None

    def __init__(self, skl_model):
        self.skl_model = skl_model

    def predict(self, X):
        value = self.skl_model.predict(X)
        # SVM has probability attribute which defines if method compute probs
        has_prob_attr = hasattr(self.skl_model, "probability")
        if (has_prob_attr and self.skl_model.probability
                or not has_prob_attr
                and hasattr(self.skl_model, "predict_proba")):
            probs = self.skl_model.predict_proba(X)
            return value, probs
        return value

    def __repr__(self):
        # Params represented as a comment because not passed into constructor
        return super().__repr__() + '  # params=' + repr(self.params)


class SklLearner(Learner, metaclass=WrapperMeta):
    """
    ${skldoc}
    Additional Orange parameters

    preprocessors : list, optional
        An ordered list of preprocessors applied to data before
        training or testing.
        Defaults to
        `[RemoveNaNClasses(), Continuize(), SklImpute(), RemoveNaNColumns()]`
    """
    __wraps__ = None
    __returns__ = SklModel
    _params = {}

    preprocessors = default_preprocessors = [
        HasClass(),
        Continuize(),
        RemoveNaNColumns(),
        SklImpute()]

    @property
    def params(self):
        return self._params

    @params.setter
    def params(self, value):
        self._params = self._get_sklparams(value)

    def _get_sklparams(self, values):
        skllearner = self.__wraps__
        if skllearner is not None:
            spec = list(
                inspect.signature(skllearner.__init__).parameters.keys()
            )
            # first argument is 'self'
            assert spec[0] == "self"
            params = {
                name: values[name] for name in spec[1:] if name in values
            }
        else:
            raise TypeError("Wrapper does not define '__wraps__'")
        return params

    def preprocess(self, data, progress_callback=None):
        data = super().preprocess(data, progress_callback)

        if any(v.is_discrete and len(v.values) > 2
               for v in data.domain.attributes):
            raise ValueError("Wrapped scikit-learn methods do not support " +
                             "multinomial variables.")

        return data

    def __call__(self, data, progress_callback=None):
        m = super().__call__(data, progress_callback)
        m.params = self.params
        return m

    def _initialize_wrapped(self):
        # pylint: disable=not-callable
        return self.__wraps__(**self.params)

    def fit(self, X, Y, W=None):
        clf = self._initialize_wrapped()
        Y = Y.reshape(-1)
        if W is None or not self.supports_weights:
            return self.__returns__(clf.fit(X, Y))
        return self.__returns__(clf.fit(X, Y, sample_weight=W.reshape(-1)))

    @property
    def supports_weights(self):
        """Indicates whether this learner supports weighted instances.
        """
        return 'sample_weight' in self.__wraps__.fit.__code__.co_varnames

    def __getattr__(self, item):
        try:
            return self.params[item]
        except (KeyError, AttributeError):
            raise AttributeError(item) from None

    # TODO: Disallow (or mirror) __setattr__ for keys in params?

    def __dir__(self):
        dd = super().__dir__()
        return list(sorted(set(dd) | set(self.params.keys())))


class TreeModel(Model):
    pass


class RandomForestModel(Model):
    """Interface for random forest models
    """

    @property
    def trees(self):
        """Return a list of Trees in the forest

        Returns
        -------
        List[Tree]
        """


class KNNBase:
    """Base class for KNN (classification and regression) learners
    """

    # pylint: disable=unused-argument
    def __init__(self, n_neighbors=5, metric="euclidean", weights="uniform",
                 algorithm='auto', metric_params=None,
                 preprocessors=None):
        super().__init__(preprocessors=preprocessors)
        self.params = vars()

    def fit(self, X, Y, W=None):
        if self.params["metric_params"] is None and \
                        self.params.get("metric") == "mahalanobis":
            self.params["metric_params"] = {"V": np.cov(X.T)}
        return super().fit(X, Y, W)


class NNBase:
    """Base class for neural network (classification and regression) learners
    """
    preprocessors = SklLearner.preprocessors + [Normalize()]

    # pylint: disable=unused-argument,too-many-arguments
    def __init__(self, hidden_layer_sizes=(100,), activation='relu',
                 solver='adam', alpha=0.0001, batch_size='auto',
                 learning_rate='constant', learning_rate_init=0.001,
                 power_t=0.5, max_iter=200, shuffle=True, random_state=None,
                 tol=0.0001, verbose=False, warm_start=False, momentum=0.9,
                 nesterovs_momentum=True, early_stopping=False,
                 validation_fraction=0.1, beta_1=0.9, beta_2=0.999,
                 epsilon=1e-08, preprocessors=None):
        super().__init__(preprocessors=preprocessors)
        self.params = vars()


class CatGBModel(Model, metaclass=WrapperMeta):
    def __init__(self, cat_model, cat_features, domain):
        super().__init__(domain)
        self.cat_model = cat_model
        self.cat_features = cat_features

    def predict(self, X):
        if self.cat_features:
            X = X.astype(str)
        value = self.cat_model.predict(X).flatten()
        if hasattr(self.cat_model, "predict_proba"):
            probs = self.cat_model.predict_proba(X)
            return value, probs
        return value

    def __repr__(self):
        # Params represented as a comment because not passed into constructor
        return super().__repr__() + '  # params=' + repr(self.params)


class CatGBBaseLearner(Learner, metaclass=WrapperMeta):
    """
    ${skldoc}
    Additional Orange parameters

    preprocessors : list, optional
        An ordered list of preprocessors applied to data before
        training or testing.
        Defaults to
        `[RemoveNaNClasses(), RemoveNaNColumns()]`
    """
    supports_weights = True
    __wraps__ = None
    __returns__ = CatGBModel
    _params = {}
    preprocessors = default_preprocessors = [
        HasClass(),
        RemoveNaNColumns(),
    ]

    # pylint: disable=unused-argument,too-many-arguments,too-many-locals
    def __init__(self,
                 iterations=None,
                 learning_rate=None,
                 depth=None,
                 l2_leaf_reg=None,
                 model_size_reg=None,
                 rsm=None,
                 loss_function=None,
                 border_count=None,
                 feature_border_type=None,
                 per_float_feature_quantization=None,
                 input_borders=None,
                 output_borders=None,
                 fold_permutation_block=None,
                 od_pval=None,
                 od_wait=None,
                 od_type=None,
                 nan_mode=None,
                 counter_calc_method=None,
                 leaf_estimation_iterations=None,
                 leaf_estimation_method=None,
                 thread_count=None,
                 random_seed=None,
                 use_best_model=None,
                 verbose=False,
                 logging_level=None,
                 metric_period=None,
                 ctr_leaf_count_limit=None,
                 store_all_simple_ctr=None,
                 max_ctr_complexity=None,
                 has_time=None,
                 allow_const_label=None,
                 classes_count=None,
                 class_weights=None,
                 one_hot_max_size=None,
                 random_strength=None,
                 name=None,
                 ignored_features=None,
                 train_dir=cache_dir(),
                 custom_loss=None,
                 custom_metric=None,
                 eval_metric=None,
                 bagging_temperature=None,
                 save_snapshot=None,
                 snapshot_file=None,
                 snapshot_interval=None,
                 fold_len_multiplier=None,
                 used_ram_limit=None,
                 gpu_ram_part=None,
                 allow_writing_files=False,
                 final_ctr_computation_mode=None,
                 approx_on_full_history=None,
                 boosting_type=None,
                 simple_ctr=None,
                 combinations_ctr=None,
                 per_feature_ctr=None,
                 task_type=None,
                 device_config=None,
                 devices=None,
                 bootstrap_type=None,
                 subsample=None,
                 sampling_unit=None,
                 dev_score_calc_obj_block_size=None,
                 max_depth=None,
                 n_estimators=None,
                 num_boost_round=None,
                 num_trees=None,
                 colsample_bylevel=None,
                 random_state=None,
                 reg_lambda=None,
                 objective=None,
                 eta=None,
                 max_bin=None,
                 scale_pos_weight=None,
                 gpu_cat_features_storage=None,
                 data_partition=None,
                 metadata=None,
                 early_stopping_rounds=None,
                 cat_features=None,
                 grow_policy=None,
                 min_data_in_leaf=None,
                 min_child_samples=None,
                 max_leaves=None,
                 num_leaves=None,
                 score_function=None,
                 leaf_estimation_backtracking=None,
                 ctr_history_unit=None,
                 monotone_constraints=None,
                 feature_weights=None,
                 penalties_coefficient=None,
                 first_feature_use_penalties=None,
                 model_shrink_rate=None,
                 model_shrink_mode=None,
                 langevin=None,
                 diffusion_temperature=None,
                 posterior_sampling=None,
                 boost_from_average=None,
                 text_features=None,
                 tokenizers=None,
                 dictionaries=None,
                 feature_calcers=None,
                 text_processing=None,
                 preprocessors=None):
        super().__init__(preprocessors=preprocessors)
        self.params = vars()

    @property
    def params(self):
        return self._params

    @params.setter
    def params(self, value):
        self._params = self._get_wrapper_params(value)

    def _get_wrapper_params(self, values):
        spec = list(inspect.signature(
            self.__wraps__.__init__).parameters.keys())
        return {name: values[name] for name in spec[1:] if name in values}

    def __call__(self, data, progress_callback=None):
        m = super().__call__(data, progress_callback)
        m.params = self.params
        return m

    def fit_storage(self, data: Table):
        domain, X, Y, W = data.domain, data.X, data.Y.reshape(-1), None
        if self.supports_weights and data.has_weights():
            W = data.W.reshape(-1)
        # pylint: disable=not-callable
        clf = self.__wraps__(**self.params)
        cat_features = [i for i, attr in enumerate(domain.attributes)
                        if attr.is_discrete]
        if cat_features:
            X = X.astype(str)
        cat_model = clf.fit(X, Y, cat_features=cat_features, sample_weight=W)
        return self.__returns__(cat_model, cat_features, domain)

    def __getattr__(self, item):
        try:
            return self.params[item]
        except (KeyError, AttributeError):
            raise AttributeError(item) from None

    def __dir__(self):
        dd = super().__dir__()
        return list(sorted(set(dd) | set(self.params.keys())))


class XGBBase(SklLearner):
    """Base class for xgboost (classification and regression) learners """
    preprocessors = default_preprocessors = [
        HasClass(),
        Continuize(),
        RemoveNaNColumns(),
    ]

    def __init__(self, preprocessors=None, **kwargs):
        super().__init__(preprocessors=preprocessors)
        self.params = kwargs

    @SklLearner.params.setter
    def params(self, values: Dict):
        self._params = values

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Calibration Overwrites Model Domain Incorrectly, Causing Prediction Errors with NumPy Data

**Description**
When using Calibration learners, the model's domain is being overwritten regardless of whether it was previously set. This leads to improper data transformations when passing NumPy arrays, resulting in invalid inputs for prediction methods.

**Example Buggy Code:**
```python
from Orange.classification import LogisticRegressionLearner, CalibratedLearner
from Orange.data import Table

data = Table('heart_disease')
base_learner = LogisticRegressionLearner()
model = CalibratedLearner(base_learner)(data)
predictions = model(model.data_to_model_domain(data).X)
```
In this example, the `CalibratedLearner` incorrectly sets `model.domain` to `data.domain` even if `model.domain` is already defined. As a result, the NumPy data passed to the model is not properly transformed, introducing `NaN` values.

**Expected Behavior**
The `CalibratedLearner` should respect the existing `model.domain` if it is already set and not overwrite it. This ensures that NumPy data is correctly transformed according to the model's domain, preventing the introduction of `NaN` or infinite values during predictions.

**Actual Behavior**
The `CalibratedLearner` overwrites `model.domain` unconditionally, leading to improper data transformations. When making predictions with NumPy data, this results in `ValueError` due to the presence of `NaN` or infinite values in the input.

**Error Message:**
```
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
```

[/ISSUE]
{
    "TestThresholdClassifier.test_nans": "PASSED",
    "TestThresholdClassifier.test_non_binary_base": "PASSED",
    "TestThresholdClassifier.test_np_data": "PASSED",
    "TestThresholdClassifier.test_return_types": "PASSED",
    "TestThresholdClassifier.test_threshold": "PASSED",
    "TestThresholdLearner.test_fit_storage": "PASSED",
    "TestThresholdLearner.test_non_binary_class": "PASSED",
    "TestCalibratedClassifier.test_calibrated_probs": "PASSED",
    "TestCalibratedClassifier.test_call": "PASSED",
    "TestCalibratedClassifier.test_np_data": "PASSED",
    "TestCalibratedLearner.test_fit_storage": "PASSED"
}
diff --git a/Orange/base.py b/Orange/base.py
index 162b29a3b..f618a876f 100644
--- a/Orange/base.py
+++ b/Orange/base.py
@@ -136,7 +136,11 @@ class Learner(ReprableWithPreprocessors):
         progress_callback(0.1, "Fitting...")
         model = self._fit_model(data)
         model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]
-        model.domain = data.domain
+        if not hasattr(model, "domain") or model.domain is None:
+            # some models set domain themself and it should be respected
+            # e.g. calibration learners set the base_learner's domain which
+            # would be wrongly overwritten if we set it here for any model
+            model.domain = data.domain
         model.supports_multiclass = self.supports_multiclass
         model.name = self.name
         model.original_domain = origdomain

{"Orange/base.py": "import inspect\nimport itertools\nfrom collections.abc import Iterable\nimport re\nimport warnings\nfrom typing import Callable, Dict\n\nimport numpy as np\nimport scipy\n\nfrom Orange.data import Table, Storage, Instance, Value\nfrom Orange.data.filter import HasClass\nfrom Orange.data.table import DomainTransformationError\nfrom Orange.data.util import one_hot\nfrom Orange.misc.environ import cache_dir\nfrom Orange.misc.wrapper_meta import WrapperMeta\nfrom Orange.preprocess import Continuize, RemoveNaNColumns, SklImpute, Normalize\nfrom Orange.statistics.util import all_nan\nfrom Orange.util import Reprable, OrangeDeprecationWarning, wrap_callback, \\\n    dummy_callback\n\n__all__ = [\"Learner\", \"Model\", \"SklLearner\", \"SklModel\",\n           \"ReprableWithPreprocessors\"]\n\n\nclass ReprableWithPreprocessors(Reprable):\n    def _reprable_omit_param(self, name, default, value):\n        if name == \"preprocessors\":\n            default_cls = type(self).preprocessors\n            if value is default or value is default_cls:\n                return True\n            else:\n                try:\n                    return all(p1 is p2 for p1, p2 in\n                               itertools.zip_longest(value, default_cls))\n                except (ValueError, TypeError):\n                    return False\n        else:\n            return super()._reprable_omit_param(name, default, value)\n\n\nclass Learner(ReprableWithPreprocessors):\n    \"\"\"The base learner class.\n\n    Preprocessors can behave in a number of different ways, all of which are\n    described here.\n    If the user does not pass a preprocessor argument into the Learner\n    constructor, the default learner preprocessors are used. We assume the user\n    would simply like to get things done without having to worry about\n    preprocessors.\n    If the user chooses to pass in their own preprocessors, we assume they know\n    what they are doing. In this case, only the user preprocessors are used and\n    the default preprocessors are ignored.\n    In case the user would like to use the default preprocessors as well as\n    their own ones, the `use_default_preprocessors` flag should be set.\n\n    Parameters\n    ----------\n    preprocessors : Preprocessor or tuple[Preprocessor], optional\n        User defined preprocessors. If the user specifies their own\n        preprocessors, the default ones will not be used, unless the\n        `use_default_preprocessors` flag is set.\n\n    Attributes\n    ----------\n    preprocessors : tuple[Preprocessor] (default None)\n        The used defined preprocessors that will be used on any data.\n    use_default_preprocessors : bool (default False)\n        This flag indicates whether to use the default preprocessors that are\n        defined on the Learner class. Since preprocessors can be applied in a\n        number of ways\n    active_preprocessors : tuple[Preprocessor]\n        The processors that will be used when data is passed to the learner.\n        This depends on whether the user has passed in their own preprocessors\n        and whether the `use_default_preprocessors` flag is set.\n\n        This property is needed mainly because of the `Fitter` class, which can\n        not know in advance, which preprocessors it will need to use. Therefore\n        this resolves the active preprocessors using a lazy approach.\n    params : dict\n        The params that the learner is constructed with.\n\n    \"\"\"\n    supports_multiclass = False\n    supports_weights = False\n    #: A sequence of data preprocessors to apply on data prior to\n    #: fitting the model\n    preprocessors = ()\n    learner_adequacy_err_msg = ''\n\n    def __init__(self, preprocessors=None):\n        self.use_default_preprocessors = False\n        if isinstance(preprocessors, Iterable):\n            self.preprocessors = tuple(preprocessors)\n        elif preprocessors:\n            self.preprocessors = (preprocessors,)\n\n    def fit(self, X, Y, W=None):\n        raise RuntimeError(\n            \"Descendants of Learner must overload method fit or fit_storage\")\n\n    def fit_storage(self, data):\n        \"\"\"Default implementation of fit_storage defaults to calling fit.\n        Derived classes must define fit_storage or fit\"\"\"\n        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n        return self.fit(X, Y, W)\n\n    def __call__(self, data, progress_callback=None):\n        if not self.check_learner_adequacy(data.domain):\n            raise ValueError(self.learner_adequacy_err_msg)\n\n        origdomain = data.domain\n\n        if isinstance(data, Instance):\n            data = Table(data.domain, [data])\n        origdata = data\n\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        progress_callback(0, \"Preprocessing...\")\n        try:\n            cb = wrap_callback(progress_callback, end=0.1)\n            data = self.preprocess(data, progress_callback=cb)\n        except TypeError:\n            data = self.preprocess(data)\n            warnings.warn(\"A keyword argument 'progress_callback' has been \"\n                          \"added to the preprocess() signature. Implementing \"\n                          \"the method without the argument is deprecated and \"\n                          \"will result in an error in the future.\",\n                          OrangeDeprecationWarning)\n\n        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:\n            raise TypeError(\"%s doesn't support multiple class variables\" %\n                            self.__class__.__name__)\n\n        progress_callback(0.1, \"Fitting...\")\n        model = self._fit_model(data)\n        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]\n        model.domain = data.domain\n        model.supports_multiclass = self.supports_multiclass\n        model.name = self.name\n        model.original_domain = origdomain\n        model.original_data = origdata\n        progress_callback(1)\n        return model\n\n    def _fit_model(self, data):\n        if type(self).fit is Learner.fit:\n            return self.fit_storage(data)\n        else:\n            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None\n            return self.fit(X, Y, W)\n\n    def preprocess(self, data, progress_callback=None):\n        \"\"\"Apply the `preprocessors` to the data\"\"\"\n        if progress_callback is None:\n            progress_callback = dummy_callback\n        n_pps = len(list(self.active_preprocessors))\n        for i, pp in enumerate(self.active_preprocessors):\n            progress_callback(i / n_pps)\n            data = pp(data)\n        progress_callback(1)\n        return data\n\n    @property\n    def active_preprocessors(self):\n        yield from self.preprocessors\n        if (self.use_default_preprocessors and\n                self.preprocessors is not type(self).preprocessors):\n            yield from type(self).preprocessors\n\n    def check_learner_adequacy(self, _):\n        return True\n\n    @property\n    def name(self):\n        \"\"\"Return a short name derived from Learner type name\"\"\"\n        try:\n            return self.__name\n        except AttributeError:\n            name = self.__class__.__name__\n            if name.endswith('Learner'):\n                name = name[:-len('Learner')]\n            if name.endswith('Fitter'):\n                name = name[:-len('Fitter')]\n            if isinstance(self, SklLearner) and name.startswith('Skl'):\n                name = name[len('Skl'):]\n            name = name or 'learner'\n            # From http://stackoverflow.com/a/1176023/1090455 <3\n            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\\1 \\2',\n                               re.sub(r'(.)([A-Z][a-z]+)', r'\\1 \\2', name)).lower()\n            return self.name\n\n    @name.setter\n    def name(self, value):\n        self.__name = value\n\n    def __str__(self):\n        return self.name\n\n\nclass Model(Reprable):\n    supports_multiclass = False\n    supports_weights = False\n    Value = 0\n    Probs = 1\n    ValueProbs = 2\n\n    def __init__(self, domain=None, original_domain=None):\n        self.domain = domain\n        if original_domain is not None:\n            self.original_domain = original_domain\n        else:\n            self.original_domain = domain\n        self.used_vals = None\n\n    def predict(self, X):\n        if type(self).predict_storage is Model.predict_storage:\n            raise TypeError(\"Descendants of Model must overload method predict\")\n        else:\n            Y = np.zeros((len(X), len(self.domain.class_vars)))\n            Y[:] = np.nan\n            table = Table(self.domain, X, Y)\n            return self.predict_storage(table)\n\n    def predict_storage(self, data):\n        if isinstance(data, Storage):\n            return self.predict(data.X)\n        elif isinstance(data, Instance):\n            return self.predict(np.atleast_2d(data.x))\n        raise TypeError(\"Unrecognized argument (instance of '{}')\"\n                        .format(type(data).__name__))\n\n    def get_backmappers(self, data):\n        backmappers = []\n        n_values = []\n\n        dataclasses = data.domain.class_vars\n        modelclasses = self.domain.class_vars\n        if not (modelclasses and dataclasses):\n            return None, []  # classless model or data; don't touch\n        if len(dataclasses) != len(modelclasses):\n            raise DomainTransformationError(\n                \"Mismatching number of model's classes and data classes\")\n        for dataclass, modelclass in zip(dataclasses, modelclasses):\n            if dataclass != modelclass:\n                if dataclass.name != modelclass.name:\n                    raise DomainTransformationError(\n                        f\"Model for '{modelclass.name}' \"\n                        f\"cannot predict '{dataclass.name}'\")\n                else:\n                    raise DomainTransformationError(\n                        f\"Variables '{modelclass.name}' in the model is \"\n                        \"incompatible with the variable of the same name \"\n                        \"in the data.\")\n            n_values.append(dataclass.is_discrete and len(dataclass.values))\n            if dataclass is not modelclass and dataclass.is_discrete:\n                backmappers.append(dataclass.get_mapper_from(modelclass))\n            else:\n                backmappers.append(None)\n        if all(x is None for x in backmappers):\n            backmappers = None\n        return backmappers, n_values\n\n    def backmap_value(self, value, mapped_probs, n_values, backmappers):\n        if backmappers is None:\n            return value\n\n        if value.ndim == 2:  # For multitarget, recursive call by columns\n            new_value = np.zeros(value.shape)\n            for i, n_value, backmapper in zip(\n                    itertools.count(), n_values, backmappers):\n                new_value[:, i] = self.backmap_value(\n                    value[:, i], mapped_probs[:, i, :], [n_value], [backmapper])\n            return new_value\n\n        backmapper = backmappers[0]\n        if backmapper is None:\n            return value\n\n        value = backmapper(value)\n        nans = np.isnan(value)\n        if not np.any(nans) or n_values[0] < 2:\n            return value\n        if mapped_probs is not None:\n            value[nans] = np.argmax(mapped_probs[nans], axis=1)\n        else:\n            value[nans] = np.random.RandomState(0).choice(\n                backmapper(np.arange(0, n_values[0] - 1)),\n                (np.sum(nans), ))\n        return value\n\n    def backmap_probs(self, probs, n_values, backmappers):\n        if backmappers is None:\n            return probs\n\n        if probs.ndim == 3:\n            new_probs = np.zeros((len(probs), len(n_values), max(n_values)),\n                                 dtype=probs.dtype)\n            for i, n_value, backmapper in zip(\n                    itertools.count(), n_values, backmappers):\n                new_probs[:, i, :n_value] = self.backmap_probs(\n                    probs[:, i, :], [n_value], [backmapper])\n            return new_probs\n\n        backmapper = backmappers[0]\n        if backmapper is None:\n            return probs\n        n_value = n_values[0]\n        new_probs = np.zeros((len(probs), n_value), dtype=probs.dtype)\n        for col in range(probs.shape[1]):\n            target = backmapper(col)\n            if not np.isnan(target):\n                new_probs[:, int(target)] = probs[:, col]\n        tots = np.sum(new_probs, axis=1)\n        zero_sum = tots == 0\n        new_probs[zero_sum] = 1\n        tots[zero_sum] = n_value\n        new_probs = new_probs / tots[:, None]\n        return new_probs\n\n    def data_to_model_domain(\n            self, data: Table, progress_callback: Callable = dummy_callback\n    ) -> Table:\n        \"\"\"\n        Transforms data to the model domain if possible.\n\n        Parameters\n        ----------\n        data\n            Data to be transformed to the model domain\n        progress_callback\n            Callback - callable - to report the progress\n\n        Returns\n        -------\n        Transformed data table\n\n        Raises\n        ------\n        DomainTransformationError\n            Error indicates that transformation is not possible since domains\n            are not compatible\n        \"\"\"\n        if data.domain == self.domain:\n            return data\n\n        progress_callback(0)\n        if self.original_domain.attributes != data.domain.attributes \\\n                and data.X.size \\\n                and not all_nan(data.X):\n            progress_callback(0.5)\n            new_data = data.transform(self.original_domain)\n            if all_nan(new_data.X):\n                raise DomainTransformationError(\n                    \"domain transformation produced no defined values\")\n            progress_callback(0.75)\n            data = new_data.transform(self.domain)\n            progress_callback(1)\n            return data\n\n        progress_callback(0.5)\n        data = data.transform(self.domain)\n        progress_callback(1)\n        return data\n\n    def __call__(self, data, ret=Value):\n        multitarget = len(self.domain.class_vars) > 1\n\n        def one_hot_probs(value):\n            if not multitarget:\n                return one_hot(\n                    value,\n                    dim=len(self.domain.class_var.values)\n                    if self.domain is not None else None\n                )\n\n            max_card = max(len(c.values) for c in self.domain.class_vars)\n            probs = np.zeros(value.shape + (max_card,), float)\n            for i in range(len(self.domain.class_vars)):\n                probs[:, i, :] = one_hot(value[:, i])\n            return probs\n\n        def extend_probabilities(probs):\n            \"\"\"\n            Since SklModels and models implementing `fit` and not `fit_storage`\n            do not guarantee correct prediction dimensionality, extend\n            dimensionality of probabilities when it does not match the number\n            of values in the domain.\n            \"\"\"\n            class_vars = self.domain.class_vars\n            max_values = max(len(cv.values) for cv in class_vars)\n            if max_values == probs.shape[-1]:\n                return probs\n\n            if not self.supports_multiclass:\n                probs = probs[:, np.newaxis, :]\n\n            probs_ext = np.zeros((len(probs), len(class_vars), max_values))\n            for c, used_vals in enumerate(self.used_vals):\n                for i, cv in enumerate(used_vals):\n                    probs_ext[:, c, cv] = probs[:, c, i]\n\n            if not self.supports_multiclass:\n                probs_ext = probs_ext[:, 0, :]\n            return probs_ext\n\n        def fix_dim(x):\n            return x[0] if one_d else x\n\n        if not 0 <= ret <= 2:\n            raise ValueError(\"invalid value of argument 'ret'\")\n        if ret > 0 and any(v.is_continuous for v in self.domain.class_vars):\n            raise ValueError(\"cannot predict continuous distributions\")\n\n        # Convert 1d structures to 2d and remember doing it\n        one_d = True\n        if isinstance(data, Instance):\n            data = Table.from_list(data.domain, [data])\n        elif isinstance(data, (list, tuple)) \\\n                and not isinstance(data[0], (list, tuple)):\n            data = [data]\n        elif isinstance(data, np.ndarray) and data.ndim == 1:\n            data = np.atleast_2d(data)\n        else:\n            one_d = False\n\n        # if sparse convert to csr_matrix\n        if scipy.sparse.issparse(data):\n            data = data.tocsr()\n\n        # Call the predictor\n        backmappers = None\n        n_values = []\n        if isinstance(data, (np.ndarray, scipy.sparse.csr.csr_matrix)):\n            prediction = self.predict(data)\n        elif isinstance(data, Table):\n            backmappers, n_values = self.get_backmappers(data)\n            data = self.data_to_model_domain(data)\n            prediction = self.predict_storage(data)\n        elif isinstance(data, (list, tuple)):\n            data = Table.from_list(self.original_domain, data)\n            data = data.transform(self.domain)\n            prediction = self.predict_storage(data)\n        else:\n            raise TypeError(\"Unrecognized argument (instance of '{}')\"\n                            .format(type(data).__name__))\n\n        # Parse the result into value and probs\n        if isinstance(prediction, tuple):\n            value, probs = prediction\n        elif prediction.ndim == 1 + multitarget:\n            value, probs = prediction, None\n        elif prediction.ndim == 2 + multitarget:\n            value, probs = None, prediction\n        else:\n            raise TypeError(\"model returned a %i-dimensional array\",\n                            prediction.ndim)\n\n        # Ensure that we have what we need to return; backmapp everything\n        if probs is None and (ret != Model.Value or backmappers is not None):\n            probs = one_hot_probs(value)\n        if probs is not None:\n            probs = extend_probabilities(probs)\n            probs = self.backmap_probs(probs, n_values, backmappers)\n        if ret != Model.Probs:\n            if value is None:\n                value = np.argmax(probs, axis=-1)\n                # probs are already backmapped\n            else:\n                value = self.backmap_value(value, probs, n_values, backmappers)\n\n        # Return what we need to\n        if ret == Model.Probs:\n            return fix_dim(probs)\n        if isinstance(data, Instance) and not multitarget:\n            value = [Value(self.domain.class_var, value[0])]\n        if ret == Model.Value:\n            return fix_dim(value)\n        else:  # ret == Model.ValueProbs\n            return fix_dim(value), fix_dim(probs)\n\n    def __getstate__(self):\n        \"\"\"Skip (possibly large) data when pickling models\"\"\"\n        state = self.__dict__\n        if 'original_data' in state:\n            state = state.copy()\n            state['original_data'] = None\n        return state\n\n\nclass SklModel(Model, metaclass=WrapperMeta):\n    used_vals = None\n\n    def __init__(self, skl_model):\n        self.skl_model = skl_model\n\n    def predict(self, X):\n        value = self.skl_model.predict(X)\n        # SVM has probability attribute which defines if method compute probs\n        has_prob_attr = hasattr(self.skl_model, \"probability\")\n        if (has_prob_attr and self.skl_model.probability\n                or not has_prob_attr\n                and hasattr(self.skl_model, \"predict_proba\")):\n            probs = self.skl_model.predict_proba(X)\n            return value, probs\n        return value\n\n    def __repr__(self):\n        # Params represented as a comment because not passed into constructor\n        return super().__repr__() + '  # params=' + repr(self.params)\n\n\nclass SklLearner(Learner, metaclass=WrapperMeta):\n    \"\"\"\n    ${skldoc}\n    Additional Orange parameters\n\n    preprocessors : list, optional\n        An ordered list of preprocessors applied to data before\n        training or testing.\n        Defaults to\n        `[RemoveNaNClasses(), Continuize(), SklImpute(), RemoveNaNColumns()]`\n    \"\"\"\n    __wraps__ = None\n    __returns__ = SklModel\n    _params = {}\n\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        Continuize(),\n        RemoveNaNColumns(),\n        SklImpute()]\n\n    @property\n    def params(self):\n        return self._params\n\n    @params.setter\n    def params(self, value):\n        self._params = self._get_sklparams(value)\n\n    def _get_sklparams(self, values):\n        skllearner = self.__wraps__\n        if skllearner is not None:\n            spec = list(\n                inspect.signature(skllearner.__init__).parameters.keys()\n            )\n            # first argument is 'self'\n            assert spec[0] == \"self\"\n            params = {\n                name: values[name] for name in spec[1:] if name in values\n            }\n        else:\n            raise TypeError(\"Wrapper does not define '__wraps__'\")\n        return params\n\n    def preprocess(self, data, progress_callback=None):\n        data = super().preprocess(data, progress_callback)\n\n        if any(v.is_discrete and len(v.values) > 2\n               for v in data.domain.attributes):\n            raise ValueError(\"Wrapped scikit-learn methods do not support \" +\n                             \"multinomial variables.\")\n\n        return data\n\n    def __call__(self, data, progress_callback=None):\n        m = super().__call__(data, progress_callback)\n        m.params = self.params\n        return m\n\n    def _initialize_wrapped(self):\n        # pylint: disable=not-callable\n        return self.__wraps__(**self.params)\n\n    def fit(self, X, Y, W=None):\n        clf = self._initialize_wrapped()\n        Y = Y.reshape(-1)\n        if W is None or not self.supports_weights:\n            return self.__returns__(clf.fit(X, Y))\n        return self.__returns__(clf.fit(X, Y, sample_weight=W.reshape(-1)))\n\n    @property\n    def supports_weights(self):\n        \"\"\"Indicates whether this learner supports weighted instances.\n        \"\"\"\n        return 'sample_weight' in self.__wraps__.fit.__code__.co_varnames\n\n    def __getattr__(self, item):\n        try:\n            return self.params[item]\n        except (KeyError, AttributeError):\n            raise AttributeError(item) from None\n\n    # TODO: Disallow (or mirror) __setattr__ for keys in params?\n\n    def __dir__(self):\n        dd = super().__dir__()\n        return list(sorted(set(dd) | set(self.params.keys())))\n\n\nclass TreeModel(Model):\n    pass\n\n\nclass RandomForestModel(Model):\n    \"\"\"Interface for random forest models\n    \"\"\"\n\n    @property\n    def trees(self):\n        \"\"\"Return a list of Trees in the forest\n\n        Returns\n        -------\n        List[Tree]\n        \"\"\"\n\n\nclass KNNBase:\n    \"\"\"Base class for KNN (classification and regression) learners\n    \"\"\"\n\n    # pylint: disable=unused-argument\n    def __init__(self, n_neighbors=5, metric=\"euclidean\", weights=\"uniform\",\n                 algorithm='auto', metric_params=None,\n                 preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n    def fit(self, X, Y, W=None):\n        if self.params[\"metric_params\"] is None and \\\n                        self.params.get(\"metric\") == \"mahalanobis\":\n            self.params[\"metric_params\"] = {\"V\": np.cov(X.T)}\n        return super().fit(X, Y, W)\n\n\nclass NNBase:\n    \"\"\"Base class for neural network (classification and regression) learners\n    \"\"\"\n    preprocessors = SklLearner.preprocessors + [Normalize()]\n\n    # pylint: disable=unused-argument,too-many-arguments\n    def __init__(self, hidden_layer_sizes=(100,), activation='relu',\n                 solver='adam', alpha=0.0001, batch_size='auto',\n                 learning_rate='constant', learning_rate_init=0.001,\n                 power_t=0.5, max_iter=200, shuffle=True, random_state=None,\n                 tol=0.0001, verbose=False, warm_start=False, momentum=0.9,\n                 nesterovs_momentum=True, early_stopping=False,\n                 validation_fraction=0.1, beta_1=0.9, beta_2=0.999,\n                 epsilon=1e-08, preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n\nclass CatGBModel(Model, metaclass=WrapperMeta):\n    def __init__(self, cat_model, cat_features, domain):\n        super().__init__(domain)\n        self.cat_model = cat_model\n        self.cat_features = cat_features\n\n    def predict(self, X):\n        if self.cat_features:\n            X = X.astype(str)\n        value = self.cat_model.predict(X).flatten()\n        if hasattr(self.cat_model, \"predict_proba\"):\n            probs = self.cat_model.predict_proba(X)\n            return value, probs\n        return value\n\n    def __repr__(self):\n        # Params represented as a comment because not passed into constructor\n        return super().__repr__() + '  # params=' + repr(self.params)\n\n\nclass CatGBBaseLearner(Learner, metaclass=WrapperMeta):\n    \"\"\"\n    ${skldoc}\n    Additional Orange parameters\n\n    preprocessors : list, optional\n        An ordered list of preprocessors applied to data before\n        training or testing.\n        Defaults to\n        `[RemoveNaNClasses(), RemoveNaNColumns()]`\n    \"\"\"\n    supports_weights = True\n    __wraps__ = None\n    __returns__ = CatGBModel\n    _params = {}\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        RemoveNaNColumns(),\n    ]\n\n    # pylint: disable=unused-argument,too-many-arguments,too-many-locals\n    def __init__(self,\n                 iterations=None,\n                 learning_rate=None,\n                 depth=None,\n                 l2_leaf_reg=None,\n                 model_size_reg=None,\n                 rsm=None,\n                 loss_function=None,\n                 border_count=None,\n                 feature_border_type=None,\n                 per_float_feature_quantization=None,\n                 input_borders=None,\n                 output_borders=None,\n                 fold_permutation_block=None,\n                 od_pval=None,\n                 od_wait=None,\n                 od_type=None,\n                 nan_mode=None,\n                 counter_calc_method=None,\n                 leaf_estimation_iterations=None,\n                 leaf_estimation_method=None,\n                 thread_count=None,\n                 random_seed=None,\n                 use_best_model=None,\n                 verbose=False,\n                 logging_level=None,\n                 metric_period=None,\n                 ctr_leaf_count_limit=None,\n                 store_all_simple_ctr=None,\n                 max_ctr_complexity=None,\n                 has_time=None,\n                 allow_const_label=None,\n                 classes_count=None,\n                 class_weights=None,\n                 one_hot_max_size=None,\n                 random_strength=None,\n                 name=None,\n                 ignored_features=None,\n                 train_dir=cache_dir(),\n                 custom_loss=None,\n                 custom_metric=None,\n                 eval_metric=None,\n                 bagging_temperature=None,\n                 save_snapshot=None,\n                 snapshot_file=None,\n                 snapshot_interval=None,\n                 fold_len_multiplier=None,\n                 used_ram_limit=None,\n                 gpu_ram_part=None,\n                 allow_writing_files=False,\n                 final_ctr_computation_mode=None,\n                 approx_on_full_history=None,\n                 boosting_type=None,\n                 simple_ctr=None,\n                 combinations_ctr=None,\n                 per_feature_ctr=None,\n                 task_type=None,\n                 device_config=None,\n                 devices=None,\n                 bootstrap_type=None,\n                 subsample=None,\n                 sampling_unit=None,\n                 dev_score_calc_obj_block_size=None,\n                 max_depth=None,\n                 n_estimators=None,\n                 num_boost_round=None,\n                 num_trees=None,\n                 colsample_bylevel=None,\n                 random_state=None,\n                 reg_lambda=None,\n                 objective=None,\n                 eta=None,\n                 max_bin=None,\n                 scale_pos_weight=None,\n                 gpu_cat_features_storage=None,\n                 data_partition=None,\n                 metadata=None,\n                 early_stopping_rounds=None,\n                 cat_features=None,\n                 grow_policy=None,\n                 min_data_in_leaf=None,\n                 min_child_samples=None,\n                 max_leaves=None,\n                 num_leaves=None,\n                 score_function=None,\n                 leaf_estimation_backtracking=None,\n                 ctr_history_unit=None,\n                 monotone_constraints=None,\n                 feature_weights=None,\n                 penalties_coefficient=None,\n                 first_feature_use_penalties=None,\n                 model_shrink_rate=None,\n                 model_shrink_mode=None,\n                 langevin=None,\n                 diffusion_temperature=None,\n                 posterior_sampling=None,\n                 boost_from_average=None,\n                 text_features=None,\n                 tokenizers=None,\n                 dictionaries=None,\n                 feature_calcers=None,\n                 text_processing=None,\n                 preprocessors=None):\n        super().__init__(preprocessors=preprocessors)\n        self.params = vars()\n\n    @property\n    def params(self):\n        return self._params\n\n    @params.setter\n    def params(self, value):\n        self._params = self._get_wrapper_params(value)\n\n    def _get_wrapper_params(self, values):\n        spec = list(inspect.signature(\n            self.__wraps__.__init__).parameters.keys())\n        return {name: values[name] for name in spec[1:] if name in values}\n\n    def __call__(self, data, progress_callback=None):\n        m = super().__call__(data, progress_callback)\n        m.params = self.params\n        return m\n\n    def fit_storage(self, data: Table):\n        domain, X, Y, W = data.domain, data.X, data.Y.reshape(-1), None\n        if self.supports_weights and data.has_weights():\n            W = data.W.reshape(-1)\n        # pylint: disable=not-callable\n        clf = self.__wraps__(**self.params)\n        cat_features = [i for i, attr in enumerate(domain.attributes)\n                        if attr.is_discrete]\n        if cat_features:\n            X = X.astype(str)\n        cat_model = clf.fit(X, Y, cat_features=cat_features, sample_weight=W)\n        return self.__returns__(cat_model, cat_features, domain)\n\n    def __getattr__(self, item):\n        try:\n            return self.params[item]\n        except (KeyError, AttributeError):\n            raise AttributeError(item) from None\n\n    def __dir__(self):\n        dd = super().__dir__()\n        return list(sorted(set(dd) | set(self.params.keys())))\n\n\nclass XGBBase(SklLearner):\n    \"\"\"Base class for xgboost (classification and regression) learners \"\"\"\n    preprocessors = default_preprocessors = [\n        HasClass(),\n        Continuize(),\n        RemoveNaNColumns(),\n    ]\n\n    def __init__(self, preprocessors=None, **kwargs):\n        super().__init__(preprocessors=preprocessors)\n        self.params = kwargs\n\n    @SklLearner.params.setter\n    def params(self, values: Dict):\n        self._params = values\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Calibration Overwrites Model Domain Incorrectly, Causing Prediction Errors with NumPy Data

**Description**
When using Calibration learners, the model's domain is being overwritten regardless of whether it was previously set. This leads to improper data transformations when passing NumPy arrays, resulting in invalid inputs for prediction methods.

**Example Buggy Code:**
```python
from Orange.classification import LogisticRegressionLearner, CalibratedLearner
from Orange.data import Table

data = Table('heart_disease')
base_learner = LogisticRegressionLearner()
model = CalibratedLearner(base_learner)(data)
predictions = model(model.data_to_model_domain(data).X)
```
In this example, the `CalibratedLearner` incorrectly sets `model.domain` to `data.domain` even if `model.domain` is already defined. As a result, the NumPy data passed to the model is not properly transformed, introducing `NaN` values.

**Expected Behavior**
The `CalibratedLearner` should respect the existing `model.domain` if it is already set and not overwrite it. This ensures that NumPy data is correctly transformed according to the model's domain, preventing the introduction of `NaN` or infinite values during predictions.

**Actual Behavior**
The `CalibratedLearner` overwrites `model.domain` unconditionally, leading to improper data transformations. When making predictions with NumPy data, this results in `ValueError` due to the presence of `NaN` or infinite values in the input.

**Error Message:**
```
ValueError: Input contains NaN, infinity or a value too large for dtype('float64').
```

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### Orange/base.py
import inspect
import itertools
from collections.abc import Iterable
import re
import warnings
from typing import Callable, Dict

import numpy as np
import scipy

from Orange.data import Table, Storage, Instance, Value
from Orange.data.filter import HasClass
from Orange.data.table import DomainTransformationError
from Orange.data.util import one_hot
from Orange.misc.environ import cache_dir
from Orange.misc.wrapper_meta import WrapperMeta
from Orange.preprocess import Continuize, RemoveNaNColumns, SklImpute, Normalize
from Orange.statistics.util import all_nan
from Orange.util import Reprable, OrangeDeprecationWarning, wrap_callback, \
    dummy_callback

__all__ = ["Learner", "Model", "SklLearner", "SklModel",
           "ReprableWithPreprocessors"]


class ReprableWithPreprocessors(Reprable):
    def _reprable_omit_param(self, name, default, value):
        if name == "preprocessors":
            default_cls = type(self).preprocessors
            if value is default or value is default_cls:
                return True
            else:
                try:
                    return all(p1 is p2 for p1, p2 in
                               itertools.zip_longest(value, default_cls))
                except (ValueError, TypeError):
                    return False
        else:
            return super()._reprable_omit_param(name, default, value)


class Learner(ReprableWithPreprocessors):
    """The base learner class.

    Preprocessors can behave in a number of different ways, all of which are
    described here.
    If the user does not pass a preprocessor argument into the Learner
    constructor, the default learner preprocessors are used. We assume the user
    would simply like to get things done without having to worry about
    preprocessors.
    If the user chooses to pass in their own preprocessors, we assume they know
    what they are doing. In this case, only the user preprocessors are used and
    the default preprocessors are ignored.
    In case the user would like to use the default preprocessors as well as
    their own ones, the `use_default_preprocessors` flag should be set.

    Parameters
    ----------
    preprocessors : Preprocessor or tuple[Preprocessor], optional
        User defined preprocessors. If the user specifies their own
        preprocessors, the default ones will not be used, unless the
        `use_default_preprocessors` flag is set.

    Attributes
    ----------
    preprocessors : tuple[Preprocessor] (default None)
        The used defined preprocessors that will be used on any data.
    use_default_preprocessors : bool (default False)
        This flag indicates whether to use the default preprocessors that are
        defined on the Learner class. Since preprocessors can be applied in a
        number of ways
    active_preprocessors : tuple[Preprocessor]
        The processors that will be used when data is passed to the learner.
        This depends on whether the user has passed in their own preprocessors
        and whether the `use_default_preprocessors` flag is set.

        This property is needed mainly because of the `Fitter` class, which can
        not know in advance, which preprocessors it will need to use. Therefore
        this resolves the active preprocessors using a lazy approach.
    params : dict
        The params that the learner is constructed with.

    """
    supports_multiclass = False
    supports_weights = False
    #: A sequence of data preprocessors to apply on data prior to
    #: fitting the model
    preprocessors = ()
    learner_adequacy_err_msg = ''

    def __init__(self, preprocessors=None):
        self.use_default_preprocessors = False
        if isinstance(preprocessors, Iterable):
            self.preprocessors = tuple(preprocessors)
        elif preprocessors:
            self.preprocessors = (preprocessors,)

    def fit(self, X, Y, W=None):
        raise RuntimeError(
            "Descendants of Learner must overload method fit or fit_storage")

    def fit_storage(self, data):
        """Default implementation of fit_storage defaults to calling fit.
        Derived classes must define fit_storage or fit"""
        X, Y, W = data.X, data.Y, data.W if data.has_weights() else None
        return self.fit(X, Y, W)

    def __call__(self, data, progress_callback=None):
        if not self.check_learner_adequacy(data.domain):
            raise ValueError(self.learner_adequacy_err_msg)

        origdomain = data.domain

        if isinstance(data, Instance):
            data = Table(data.domain, [data])
        origdata = data

        if progress_callback is None:
            progress_callback = dummy_callback
        progress_callback(0, "Preprocessing...")
        try:
            cb = wrap_callback(progress_callback, end=0.1)
            data = self.preprocess(data, progress_callback=cb)
        except TypeError:
            data = self.preprocess(data)
            warnings.warn("A keyword argument 'progress_callback' has been "
                          "added to the preprocess() signature. Implementing "
                          "the method without the argument is deprecated and "
                          "will result in an error in the future.",
                          OrangeDeprecationWarning)

        if len(data.domain.class_vars) > 1 and not self.supports_multiclass:
            raise TypeError("%s doesn't support multiple class variables" %
                            self.__class__.__name__)

        progress_callback(0.1, "Fitting...")
        model = self._fit_model(data)
        model.used_vals = [np.unique(y).astype(int) for y in data.Y[:, None].T]
        model.domain = data.domain
        model.supports_multiclass = self.supports_multiclass
        model.name = self.name
        model.original_domain = origdomain
        model.original_data = origdata
        progress_callback(1)
        return model

    def _fit_model(self, data):
        if type(self).fit is Learner.fit:
            return self.fit_storage(data)
        else:
            X, Y, W = data.X, data.Y, data.W if data.has_weights() else None
            return self.fit(X, Y, W)

    def preprocess(self, data, progress_callback=None):
        """Apply the `preprocessors` to the data"""
        if progress_callback is None:
            progress_callback = dummy_callback
        n_pps = len(list(self.active_preprocessors))
        for i, pp in enumerate(self.active_preprocessors):
            progress_callback(i / n_pps)
            data = pp(data)
        progress_callback(1)
        return data

    @property
    def active_preprocessors(self):
        yield from self.preprocessors
        if (self.use_default_preprocessors and
                self.preprocessors is not type(self).preprocessors):
            yield from type(self).preprocessors

    def check_learner_adequacy(self, _):
        return True

    @property
    def name(self):
        """Return a short name derived from Learner type name"""
        try:
            return self.__name
        except AttributeError:
            name = self.__class__.__name__
            if name.endswith('Learner'):
                name = name[:-len('Learner')]
            if name.endswith('Fitter'):
                name = name[:-len('Fitter')]
            if isinstance(self, SklLearner) and name.startswith('Skl'):
                name = name[len('Skl'):]
            name = name or 'learner'
            # From http://stackoverflow.com/a/1176023/1090455 <3
            self.name = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2',
                               re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name)).lower()
            return self.name

    @name.setter
    def name(self, value):
        self.__name = value

    def __str__(self):
        return self.name


class Model(Reprable):
    supports_multiclass = False
    supports_weights = False
    Value = 0
    Probs = 1
    ValueProbs = 2

    def __init__(self, domain=None, original_domain=None):
        self.domain = domain
        if original_domain is not None:
            self.original_domain = original_domain
        else:
            self.original_domain = domain
        self.used_vals = None

    def predict(self, X):
        if type(self).predict_storage is Model.predict_storage:
            raise TypeError("Descendants of Model must overload method predict")
        else:
            Y = np.zeros((len(X), len(self.domain.class_vars)))
            Y[:] = np.nan
            table = Table(self.domain, X, Y)
            return self.predict_storage(table)

    def predict_storage(self, data):
        if isinstance(data, Storage):
            return self.predict(data.X)
        elif isinstance(data, Instance):
            return self.predict(np.atleast_2d(data.x))
        raise TypeError("Unrecognized argument (instance of '{}')"
                        .format(type(data).__name__))

    def get_backmappers(self, data):
        backmappers = []
        n_values = []

        dataclasses = data.domain.class_vars
        modelclasses = self.domain.class_vars
        if not (modelclasses and dataclasses):
            return None, []  # classless model or data; don't touch
        if len(dataclasses) != len(modelclasses):
            raise DomainTransformationError(
                "Mismatching number of model's classes and data classes")
        for dataclass, modelclass in zip(dataclasses, modelclasses):
            if dataclass != modelclass:
                if dataclass.name != modelclass.name:
                    raise DomainTransformationError(
                        f"Model for '{modelclass.name}' "
                        f"cannot predict '{dataclass.name}'")
                else:
                    raise DomainTransformationError(
                        f"Variables '{modelclass.name}' in the model is "
                        "incompatible with the variable of the same name "
                        "in the data.")
            n_values.append(dataclass.is_discrete and len(dataclass.values))
            if dataclass is not modelclass and dataclass.is_discrete:
                backmappers.append(dataclass.get_mapper_from(modelclass))
            else:
                backmappers.append(None)
        if all(x is None for x in backmappers):
            backmappers = None
        return backmappers, n_values

    def backmap_value(self, value, mapped_probs, n_values, backmappers):
        if backmappers is None:
            return value

        if value.ndim == 2:  # For multitarget, recursive call by columns
            new_value = np.zeros(value.shape)
            for i, n_value, backmapper in zip(
                    itertools.count(), n_values, backmappers):
                new_value[:, i] = self.backmap_value(
                    value[:, i], mapped_probs[:, i, :], [n_value], [backmapper])
            return new_value

        backmapper = backmappers[0]
        if backmapper is None:
            return value

        value = backmapper(value)
        nans = np.isnan(value)
        if not np.any(nans) or n_values[0] < 2:
            return value
        if mapped_probs is not None:
            value[nans] = np.argmax(mapped_probs[nans], axis=1)
        else:
            value[nans] = np.random.RandomState(0).choice(
                backmapper(np.arange(0, n_values[0] - 1)),
                (np.sum(nans), ))
        return value

    def backmap_probs(self, probs, n_values, backmappers):
        if backmappers is None:
            return probs

        if probs.ndim == 3:
            new_probs = np.zeros((len(probs), len(n_values), max(n_values)),
                                 dtype=probs.dtype)
            for i, n_value, backmapper in zip(
                    itertools.count(), n_values, backmappers):
                new_probs[:, i, :n_value] = self.backmap_probs(
                    probs[:, i, :], [n_value], [backmapper])
            return new_probs

        backmapper = backmappers[0]
        if backmapper is None:
            return probs
        n_value = n_values[0]
        new_probs = np.zeros((len(probs), n_value), dtype=probs.dtype)
        for col in range(probs.shape[1]):
            target = backmapper(col)
            if not np.isnan(target):
                new_probs[:, int(target)] = probs[:, col]
        tots = np.sum(new_probs, axis=1)
        zero_sum = tots == 0
        new_probs[zero_sum] = 1
        tots[zero_sum] = n_value
        new_probs = new_probs / tots[:, None]
        return new_probs

    def data_to_model_domain(
            self, data: Table, progress_callback: Callable = dummy_callback
    ) -> Table:
        """
        Transforms data to the model domain if possible.

        Parameters
        ----------
        data
            Data to be transformed to the model domain
        progress_callback
            Callback - callable - to report the progress

        Returns
        -------
        Transformed data table

        Raises
        ------
        DomainTransformationError
            Error indicates that transformation is not possible since domains
            are not compatible
        """
        if data.domain == self.domain:
            return data

        progress_callback(0)
        if self.original_domain.attributes != data.domain.attributes \
                and data.X.size \
                and not all_nan(data.X):
            progress_callback(0.5)
            new_data = data.transform(self.original_domain)
            if all_nan(new_data.X):
                raise DomainTransformationError(
                    "domain transformation produced no defined values")
            progress_callback(0.75)
            data = new_data.transform(self.domain)
            progress_callback(1)
            return data

        progress_callback(0.5)
        data = data.transform(self.domain)
        progress_callback(1)
        return data

    def __call__(self, data, ret=Value):
        multitarget = len(self.domain.class_vars) > 1

        def one_hot_probs(value):
            if not multitarget:
                return one_hot(
                    value,
                    dim=len(self.domain.class_var.values)
                    if self.domain is not None else None
                )

            max_card = max(len(c.values) for c in self.domain.class_vars)
            probs = np.zeros(value.shape + (max_card,), float)
            for i in range(len(self.domain.class_vars)):
                probs[:, i, :] = one_hot(value[:, i])
            return probs

        def extend_probabilities(probs):
            """
            Since SklModels and models implementing `fit` and not `fit_storage`
            do not guarantee correct prediction dimensionality, extend
            dimensionality of probabilities when it does not match the number
            of values in the domain.
            """
            class_vars = self.domain.class_vars
            max_values = max(len(cv.values) for cv in class_vars)
            if max_values == probs.shape[-1]:
                return probs

            if not self.supports_multiclass:
                probs = probs[:, np.newaxis, :]

            probs_ext = np.zeros((len(probs), len(class_vars), max_values))
            for c, used_vals in enumerate(self.used_vals):
                for i, cv in enumerate(used_vals):
                    probs_ext[:, c, cv] = probs[:, c, i]

            if not self.supports_multiclass:
                probs_ext = probs_ext[:, 0, :]
            return probs_ext

        def fix_dim(x):
            return x[0] if one_d else x

        if not 0 <= ret <= 2:
            raise ValueError("invalid value of argument 'ret'")
        if ret > 0 and any(v.is_continuous for v in self.domain.class_vars):
            raise ValueError("cannot predict continuous distributions")

        # Convert 1d structures to 2d and remember doing it
        one_d = True
        if isinstance(data, Instance):
            data = Table.from_list(data.domain, [data])
        elif isinstance(data, (list, tuple)) \
                and not isinstance(data[0], (list, tuple)):
            data = [data]
        elif isinstance(data, np.ndarray) and data.ndim == 1:
            data = np.atleast_2d(data)
        else:
            one_d = False

        # if sparse convert to csr_matrix
        if scipy.sparse.issparse(data):
            data = data.tocsr()

        # Call the predictor
        backmappers = None
        n_values = []
        if isinstance(data, (np.ndarray, scipy.sparse.csr.csr_matrix)):
            prediction = self.predict(data)
        elif isinstance(data, Table):
            backmappers, n_values = self.get_backmappers(data)
            data = self.data_to_model_domain(data)
            prediction = self.predict_storage(data)
        elif isinstance(data, (list, tuple)):
            data = Table.from_list(self.original_domain, data)
            data = data.transform(self.domain)
            prediction = self.predict_storage(data)
        else:
            raise TypeError("Unrecognized argument (instance of '{}')"
                            .format(type(data).__name__))

        # Parse the result into value and probs
        if isinstance(prediction, tuple):
            value, probs = prediction
        elif prediction.ndim == 1 + multitarget:
            value, probs = prediction, None
        elif prediction.ndim == 2 + multitarget:
            value, probs = None, prediction
        else:
            raise TypeError("model returned a %i-dimensional array",
                            prediction.ndim)

        # Ensure that we have what we need to return; backmapp everything
        if probs is None and (ret != Model.Value or backmappers is not None):
            probs = one_hot_probs(value)
        if probs is not None:
            probs = extend_probabilities(probs)
            probs = self.backmap_probs(probs, n_values, backmappers)
        if ret != Model.Probs:
            if value is None:
                value = np.argmax(probs, axis=-1)
                # probs are already backmapped
            else:
                value = self.backmap_value(value, probs, n_values, backmappers)

        # Return what we need to
        if ret == Model.Probs:
            return fix_dim(probs)
        if isinstance(data, Instance) and not multitarget:
            value = [Value(self.domain.class_var, value[0])]
        if ret == Model.Value:
            return fix_dim(value)
        else:  # ret == Model.ValueProbs
            return fix_dim(value), fix_dim(probs)

    def __getstate__(self):
        """Skip (possibly large) data when pickling models"""
        state = self.__dict__
        if 'original_data' in state:
            state = state.copy()
            state['original_data'] = None
        return state


class SklModel(Model, metaclass=WrapperMeta):
    used_vals = None

    def __init__(self, skl_model):
        self.skl_model = skl_model

    def predict(self, X):
        value = self.skl_model.predict(X)
        # SVM has probability attribute which defines if method compute probs
        has_prob_attr = hasattr(self.skl_model, "probability")
        if (has_prob_attr and self.skl_model.probability
                or not has_prob_attr
                and hasattr(self.skl_model, "predict_proba")):
            probs = self.skl_model.predict_proba(X)
            return value, probs
        return value

    def __repr__(self):
        # Params represented as a comment because not passed into constructor
        return super().__repr__() + '  # params=' + repr(self.params)


class SklLearner(Learner, metaclass=WrapperMeta):
    """
    ${skldoc}
    Additional Orange parameters

    preprocessors : list, optional
        An ordered list of preprocessors applied to data before
        training or testing.
        Defaults to
        `[RemoveNaNClasses(), Continuize(), SklImpute(), RemoveNaNColumns()]`
    """
    __wraps__ = None
    __returns__ = SklModel
    _params = {}

    preprocessors = default_preprocessors = [
        HasClass(),
        Continuize(),
        RemoveNaNColumns(),
        SklImpute()]

    @property
    def params(self):
        return self._params

    @params.setter
    def params(self, value):
        self._params = self._get_sklparams(value)

    def _get_sklparams(self, values):
        skllearner = self.__wraps__
        if skllearner is not None:
            spec = list(
                inspect.signature(skllearner.__init__).parameters.keys()
            )
            # first argument is 'self'
            assert spec[0] == "self"
            params = {
                name: values[name] for name in spec[1:] if name in values
            }
        else:
            raise TypeError("Wrapper does not define '__wraps__'")
        return params

    def preprocess(self, data, progress_callback=None):
        data = super().preprocess(data, progress_callback)

        if any(v.is_discrete and len(v.values) > 2
               for v in data.domain.attributes):
            raise ValueError("Wrapped scikit-learn methods do not support " +
                             "multinomial variables.")

        return data

    def __call__(self, data, progress_callback=None):
        m = super().__call__(data, progress_callback)
        m.params = self.params
        return m

    def _initialize_wrapped(self):
        # pylint: disable=not-callable
        return self.__wraps__(**self.params)

    def fit(self, X, Y, W=None):
        clf = self._initialize_wrapped()
        Y = Y.reshape(-1)
        if W is None or not self.supports_weights:
            return self.__returns__(clf.fit(X, Y))
        return self.__returns__(clf.fit(X, Y, sample_weight=W.reshape(-1)))

    @property
    def supports_weights(self):
        """Indicates whether this learner supports weighted instances.
        """
        return 'sample_weight' in self.__wraps__.fit.__code__.co_varnames

    def __getattr__(self, item):
        try:
            return self.params[item]
        except (KeyError, AttributeError):
            raise AttributeError(item) from None

    # TODO: Disallow (or mirror) __setattr__ for keys in params?

    def __dir__(self):
        dd = super().__dir__()
        return list(sorted(set(dd) | set(self.params.keys())))


class TreeModel(Model):
    pass


class RandomForestModel(Model):
    """Interface for random forest models
    """

    @property
    def trees(self):
        """Return a list of Trees in the forest

        Returns
        -------
        List[Tree]
        """


class KNNBase:
    """Base class for KNN (classification and regression) learners
    """

    # pylint: disable=unused-argument
    def __init__(self, n_neighbors=5, metric="euclidean", weights="uniform",
                 algorithm='auto', metric_params=None,
                 preprocessors=None):
        super().__init__(preprocessors=preprocessors)
        self.params = vars()

    def fit(self, X, Y, W=None):
        if self.params["metric_params"] is None and \
                        self.params.get("metric") == "mahalanobis":
            self.params["metric_params"] = {"V": np.cov(X.T)}
        return super().fit(X, Y, W)


class NNBase:
    """Base class for neural network (classification and regression) learners
    """
    preprocessors = SklLearner.preprocessors + [Normalize()]

    # pylint: disable=unused-argument,too-many-arguments
    def __init__(self, hidden_layer_sizes=(100,), activation='relu',
                 solver='adam', alpha=0.0001, batch_size='auto',
                 learning_rate='constant', learning_rate_init=0.001,
                 power_t=0.5, max_iter=200, shuffle=True, random_state=None,
                 tol=0.0001, verbose=False, warm_start=False, momentum=0.9,
                 nesterovs_momentum=True, early_stopping=False,
                 validation_fraction=0.1, beta_1=0.9, beta_2=0.999,
                 epsilon=1e-08, preprocessors=None):
        super().__init__(preprocessors=preprocessors)
        self.params = vars()


class CatGBModel(Model, metaclass=WrapperMeta):
    def __init__(self, cat_model, cat_features, domain):
        super().__init__(domain)
        self.cat_model = cat_model
        self.cat_features = cat_features

    def predict(self, X):
        if self.cat_features:
            X = X.astype(str)
        value = self.cat_model.predict(X).flatten()
        if hasattr(self.cat_model, "predict_proba"):
            probs = self.cat_model.predict_proba(X)
            return value, probs
        return value

    def __repr__(self):
        # Params represented as a comment because not passed into constructor
        return super().__repr__() + '  # params=' + repr(self.params)


class CatGBBaseLearner(Learner, metaclass=WrapperMeta):
    """
    ${skldoc}
    Additional Orange parameters

    preprocessors : list, optional
        An ordered list of preprocessors applied to data before
        training or testing.
        Defaults to
        `[RemoveNaNClasses(), RemoveNaNColumns()]`
    """
    supports_weights = True
    __wraps__ = None
    __returns__ = CatGBModel
    _params = {}
    preprocessors = default_preprocessors = [
        HasClass(),
        RemoveNaNColumns(),
    ]

    # pylint: disable=unused-argument,too-many-arguments,too-many-locals
    def __init__(self,
                 iterations=None,
                 learning_rate=None,
                 depth=None,
                 l2_leaf_reg=None,
                 model_size_reg=None,
                 rsm=None,
                 loss_function=None,
                 border_count=None,
                 feature_border_type=None,
                 per_float_feature_quantization=None,
                 input_borders=None,
                 output_borders=None,
                 fold_permutation_block=None,
                 od_pval=None,
                 od_wait=None,
                 od_type=None,
                 nan_mode=None,
                 counter_calc_method=None,
                 leaf_estimation_iterations=None,
                 leaf_estimation_method=None,
                 thread_count=None,
                 random_seed=None,
                 use_best_model=None,
                 verbose=False,
                 logging_level=None,
                 metric_period=None,
                 ctr_leaf_count_limit=None,
                 store_all_simple_ctr=None,
                 max_ctr_complexity=None,
                 has_time=None,
                 allow_const_label=None,
                 classes_count=None,
                 class_weights=None,
                 one_hot_max_size=None,
                 random_strength=None,
                 name=None,
                 ignored_features=None,
                 train_dir=cache_dir(),
                 custom_loss=None,
                 custom_metric=None,
                 eval_metric=None,
                 bagging_temperature=None,
                 save_snapshot=None,
                 snapshot_file=None,
                 snapshot_interval=None,
                 fold_len_multiplier=None,
                 used_ram_limit=None,
                 gpu_ram_part=None,
                 allow_writing_files=False,
                 final_ctr_computation_mode=None,
                 approx_on_full_history=None,
                 boosting_type=None,
                 simple_ctr=None,
                 combinations_ctr=None,
                 per_feature_ctr=None,
                 task_type=None,
                 device_config=None,
                 devices=None,
                 bootstrap_type=None,
                 subsample=None,
                 sampling_unit=None,
                 dev_score_calc_obj_block_size=None,
                 max_depth=None,
                 n_estimators=None,
                 num_boost_round=None,
                 num_trees=None,
                 colsample_bylevel=None,
                 random_state=None,
                 reg_lambda=None,
                 objective=None,
                 eta=None,
                 max_bin=None,
                 scale_pos_weight=None,
                 gpu_cat_features_storage=None,
                 data_partition=None,
                 metadata=None,
                 early_stopping_rounds=None,
                 cat_features=None,
                 grow_policy=None,
                 min_data_in_leaf=None,
                 min_child_samples=None,
                 max_leaves=None,
                 num_leaves=None,
                 score_function=None,
                 leaf_estimation_backtracking=None,
                 ctr_history_unit=None,
                 monotone_constraints=None,
                 feature_weights=None,
                 penalties_coefficient=None,
                 first_feature_use_penalties=None,
                 model_shrink_rate=None,
                 model_shrink_mode=None,
                 langevin=None,
                 diffusion_temperature=None,
                 posterior_sampling=None,
                 boost_from_average=None,
                 text_features=None,
                 tokenizers=None,
                 dictionaries=None,
                 feature_calcers=None,
                 text_processing=None,
                 preprocessors=None):
        super().__init__(preprocessors=preprocessors)
        self.params = vars()

    @property
    def params(self):
        return self._params

    @params.setter
    def params(self, value):
        self._params = self._get_wrapper_params(value)

    def _get_wrapper_params(self, values):
        spec = list(inspect.signature(
            self.__wraps__.__init__).parameters.keys())
        return {name: values[name] for name in spec[1:] if name in values}

    def __call__(self, data, progress_callback=None):
        m = super().__call__(data, progress_callback)
        m.params = self.params
        return m

    def fit_storage(self, data: Table):
        domain, X, Y, W = data.domain, data.X, data.Y.reshape(-1), None
        if self.supports_weights and data.has_weights():
            W = data.W.reshape(-1)
        # pylint: disable=not-callable
        clf = self.__wraps__(**self.params)
        cat_features = [i for i, attr in enumerate(domain.attributes)
                        if attr.is_discrete]
        if cat_features:
            X = X.astype(str)
        cat_model = clf.fit(X, Y, cat_features=cat_features, sample_weight=W)
        return self.__returns__(cat_model, cat_features, domain)

    def __getattr__(self, item):
        try:
            return self.params[item]
        except (KeyError, AttributeError):
            raise AttributeError(item) from None

    def __dir__(self):
        dd = super().__dir__()
        return list(sorted(set(dd) | set(self.params.keys())))


class XGBBase(SklLearner):
    """Base class for xgboost (classification and regression) learners """
    preprocessors = default_preprocessors = [
        HasClass(),
        Continuize(),
        RemoveNaNColumns(),
    ]

    def __init__(self, preprocessors=None, **kwargs):
        super().__init__(preprocessors=preprocessors)
        self.params = kwargs

    @SklLearner.params.setter
    def params(self, values: Dict):
        self._params = values

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user